SharePoint 2010 has established a new service called “Word Automation Services” to operate word files. This service will be installed when install SharePoint 2010. It is useful for archive documents or convert word format in server. But we need initialize and configure this service on Central Administration or PowerShell.(How to set up Word Automation Services? see:http://msdn.microsoft.com/en-us/library/ee557330(v=office.14).aspx)

After initialized, SharePoint 2010 will setup a database named:”WordAutomationServices_XXXX”. We can find the service status in Central Administration->Application Management->Service Applications->Manage services on server:

Make sure the service is started.

Call Word Automation Services

Next, we can use C# code to call the Word Automation Services. For example, this is a word file in Shared Documents, we need to convert the word file to pdf format and saved in another document library (named Docs), we can write code like this:

string siteUrl = "http://localhost";
string wordAutomationServiceName = "Word Automation Services";
using (SPSite spSite = new SPSite(siteUrl))
{
ConversionJob job = new ConversionJob(wordAutomationServiceName);
job.UserToken = spSite.UserToken;
job.Settings.UpdateFields = true;
job.Settings.OutputFormat = SaveFormat.PDF;
job.AddFile(siteUrl + "/Shared%20Documents/Contract%20Management.docx",
siteUrl + "/Docs/Contract%20Management.pdf");
job.Start();
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Note: Word Automation Services use a timer to process our job, so even we finished our process in code, we still cannot find the pdf file in document library. After a few minutes, the timer will complate our job, refresh the document library page we can see the pdf file. If we want to make the timer work frequently, we can go to Central Administration->Monitoring->Timer Jobs->Review job definitions, click the “Word Automation Services Timer Job”, change the “Recurring Schedule” value such as 1 minute. If we want to run the job immediately, we can click the "Run Now” button.

User Open XML SDK to generate word file

Open XML is a common standard format for Office files since Office 2007. We can use Open XML SDK to develop the application that combine the user define template and data (from database, SharePoint list, interface or other user input).

Open XML SDK is not contained in Visual Studio by default, so we must download the SDK from Microsoft.(Download address:http://www.microsoft.com/en-us/download/details.aspx?id=5124) After install the SDK, we can reference the component: DocumentFormat.OpenXml and WindowsBase.

In the code, we can read the template from disk or SharePoint document library. The template contains some special word than we will replace them by user data.

For example, there is a template, we need to fill the vender name, amount and date, so we can define the template like this:

Purchasing Contract

Vender:$Vender,

Description:bala bala~~~

Total Amount: $Amount

Signature Date:$Today

We save the template as a docx file in disk, and we can read the template by Open XML SDK and replace the words like this:

FileStream fs=new FileStream("Template.docx",FileMode.Open,FileAccess.Read);
byte[] byteArray = new byte[fs.Length];
fs.Read(byteArray, 0, (int)(fs.Length)); using (MemoryStream memStr = new MemoryStream())
{
memStr.Write(byteArray, 0, byteArray.Length);
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(memStr, true))
{ string docText = null;
using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
{
docText = sr.ReadToEnd();
}
docText = docText.Replace("$Vender", "Microsoft");
docText = docText.Replace("$Amount", "1234.56");
docText = docText.Replace("$Today", DateTime.Today.ToShortDateString()); using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
{
sw.Write(docText);
}
}
Console.WriteLine("Saving");
//save new file from stream memStr...

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Run this code, we can find the result document content like this:

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

Purchasing Contract

Vender:Microsoft,

Description:bala bala~~~

Total Amount: 1234.56

Signature Date:2013/9/27

Use both the Word Automation Services and Open XML SDK, we can generate the word document by template and user data, and convert the result as a pdf file and save to another document library.

This my example code:

string siteUrl = "http://localhost";
using (SPSite spSite = new SPSite(siteUrl))
{
//Querying for Template.docx
SPList list = spSite.RootWeb.GetList("http://localhost/Shared%20Documents");
SPQuery query = new SPQuery();
query.ViewFields = @"<FieldRef Name='FileLeafRef' />";
query.Query =
@"<Where>
<Eq>
<FieldRef Name='FileLeafRef' />
<Value Type='Text'>Template.docx</Value>
</Eq>
</Where>";
SPListItemCollection collection = list.GetItems(query);
if (collection.Count != 1)
{
Console.WriteLine("Test.docx not found");
Environment.Exit(0);
}
Console.WriteLine("Opening");
SPFile file = collection[0].File;
byte[] byteArray = file.OpenBinary(); using (MemoryStream memStr = new MemoryStream())
{
memStr.Write(byteArray, 0, byteArray.Length);
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(memStr, true))
{ string docText = null;
using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
{
docText = sr.ReadToEnd();
}
docText = docText.Replace("$Vender", "Microsoft");
docText = docText.Replace("$Amount", "1234.56");
docText = docText.Replace("$Today", DateTime.Today.ToShortDateString()); using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
{
sw.Write(docText);
}
}
Console.WriteLine("Saving");
string newDocName = "MicrosoftContract.docx";
file.ParentFolder.Files.Add(newDocName, memStr, true);
Console.WriteLine("Starting conversion job");
string wordAutomationServiceName = "Word Automation Services";
ConversionJob job = new ConversionJob(wordAutomationServiceName);
job.UserToken = spSite.UserToken;
job.Settings.UpdateFields = true;
job.Settings.OutputFormat = SaveFormat.PDF;
job.AddFile(siteUrl + "/Shared%20Documents/"+newDocName,
siteUrl + "/Docs/MicrosoftContract.pdf");
job.Start();
}
}

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

User Word Automation Services and Open XML SDK to generate word files in SharePoint2010的更多相关文章

  1. Csharp: create word file using Open XML SDK 2.5

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...

  2. Using XSLT and Open XML to Create a Word 2007 Document

    Summary: Learn how to transform XML data into a Word 2007 document by starting with an existing docu ...

  3. Open Xml SDK Word模板开发最佳实践(Best Practice)

    1.概述 由于前面的引文已经对Open Xml SDK做了一个简要的介绍. 这次来点实际的——Word模板操作. 从本质上来讲,本文的操作都是基于模板替换思想的,即,我们通过替换Word模板中指定元素 ...

  4. Embedding Documents in Word 2007 by Using the Open XML SDK 2.0 for Microsoft Office

    Download the sample code This visual how-to article presents a solution that creates a Word 2007 doc ...

  5. SharePoint 2013 中的 PowerPoint Automation Services

    简介                许多大型和小型企业都将其 Microsoft SharePoint Server 库用作 Microsoft PowerPoint 演示文稿的存储库.所有这些企业在 ...

  6. Open Xml SDK 引文

    什么是Open Xml SDK? 什么是Open Xml? 首先,我们得知道,Open Xml为何物? 我们还是给她起个名字——就叫 “开放Xml”,以方便我们中文的阅读习惯.之所以起开放这个名字,因 ...

  7. 下载和编译 Open XML SDK

    我们需要一些工具来开始 Open XML 的开发. 开发工具 推荐的开发工具是 Visual Studio 社区版. 开发工具:Visual Studio Community 2013 下载地址:ht ...

  8. Open XML SDK 在线编程黑客松

    2015年2月10日-3月20日,开源社 成员 微软开放技术,GitCafe,极客学院联合举办" Open XML SDK 在线编程黑客松 ",为专注于开发提高生产力的应用及服务的 ...

  9. C# : 操作Word文件的API - (将C# source中的xml注释转换成word文档)

    这篇博客将要讨论的是关于: 如何从C#的source以及注释, 生成一份Word格式的关于各个类,函数以及成员变量的说明文档. 他的大背景如下...... 最近的一个项目使用C#, 分N个模块, 在项 ...

随机推荐

  1. mvc jquery 修改 viewbag

    [HttpGet]        public ActionResult Modify(int id)        {            Books mod=db.Books.Where(b = ...

  2. spread表格树实现

    先上图看下效果图: 玩表格的朋友应该对Component和C1Flexgrid并不陌生吧.其实我也有用C1和DGV扩展了一个表格树,占有内存小,效率也可以,但是UI是硬伤,中规中矩,不美观.我上面是基 ...

  3. Struts2例子

    (1)用MyEclipse建立一个Web Project,项目名称为myStruts2,结构如下图: (2)导入struts2需要的包,我是把解压后的struts-2.3.16.3\apps\stru ...

  4. [Linux] ubuntu安装配置vsftpd并锁定目录

    系统环境 ubuntu 14.04 LTS vsftpd安装 apt-get install vsftpd 配置文件 默认配置文件的位置为 /etc/vsftpd.conf local_enable= ...

  5. strtr和str_replace字符替换函数

    (一)strtr是字符替换函数 (1)单个字符替换: <?php echo strtr("abba", "ab", "10"),&qu ...

  6. python统计列表内元素个数

    代码如下: list01 = ['a','b','c','a','c'] set01 = set(list01) print(set01) dict01 = {} for item in set01: ...

  7. 【追寻javascript高手之路03】javascript对象大乱斗

    前言 昨天我们学习了下javascript中函数的参数与作用域的东东,现在回过头来看,其实都是与函数相关的,所以javascript中的函数仍然是王道,我们今天大概会发二篇或者三篇博客一起来巩固我们的 ...

  8. js实现标准无缝滚动

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  9. 【Leafletjs】5.L.Control 自定义一个Control

    L.Control 所有leaflet控制的基础类.继承自IControl接口. 你可以这样添加控件: control.addTo(map); // the same as map.addContro ...

  10. Sharepoint学习笔记—习题系列--70-576习题解析 -(Q21-Q24)

    Question 21 An application will be deployed in a SharePoint 2010 server farm that is managed by depa ...