User Word Automation Services and Open XML SDK to generate word files in SharePoint2010

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();
}

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...

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


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();
 }
}
时间: 2024-10-03 20:33:05

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

Build Data-Driven Web Services with Updated XML Support for SQL Server 2000

server|services|web|xml Download the code for this article: SQLXML3.exe (239KB) --->SUMMARY XML is becoming the ubiquitous data format on the Web, and XML support in SQL Server is evolving to meet the additional demand. Using XML, SOAP, HTTP, and SQL

从 VBA 中使用 Visual Basic .NET 将 Word 文档序列化为 XML

visual|word|xml 从 VBA 中使用 Visual Basic .NET 将 Word 文档序列化为 XML Michael CorningMicrosoft Corporation 2002年10月 适用于:   Microsoft Word 2002   Microsoft Visual Studio .NET 摘要:学习如何在 Microsoft Office Visual Basic for Applications (VBA) 程序中利用 .NET 代码将大型 Word

office open xml-有没有关于Office Open XML sdk 对docx文件做索引的例子

问题描述 有没有关于Office Open XML sdk 对docx文件做索引的例子 有没有关于Office Open XML sdk 对docx文件做索引的例子,帮我举一个最简单的例子就好.. 解决方案 直接用npoi就很好.

java-怎么使用Java将word文档转化为xml文档?

问题描述 怎么使用Java将word文档转化为xml文档? 就是提交上word文档,将word文档转为可以直接使用的xml文档,不是直接修改后缀名的 解决方案 IO读取word,解析内容,拼写xml,IO写入xml. 解决方案二: 把word文档解析出来,重新构建想要的XML格式,然后写出文件 解决方案三: 搞个开元项目 poi 或者 jacob 然后在转xml

Csharp: read excel file using Open XML SDK 2.5

/// <summary> /// /// </summary> public class SheetNameInfo { private int _sheetId; private string _sheetName; private string _rid; /// <summary> /// /// </summary> public int SheetID { get{return _sheetId;} set{_sheetId= value;} }

win32-WIN32 SDK怎么实现word文档自动化?

问题描述 WIN32 SDK怎么实现word文档自动化? 如题,各位大哥,小弟不才,最近要做一个Word文档自动生成的程序,我的思路,具体讲就是先制作一个有书签的word文档模板,然后写一个在windows对话框,在编辑框里填写相关文字和数字,将其与word书签对应,最后生成doc文档,并实现打印功能. 请问,用WIN32 sdk怎么编程? 解决方案 纯win32 sdk调用com组件太复杂了.建议你结合mfc或者atl来做. 解决方案二: 用win32比较麻烦,或者用mfc写一个库给win32

Open XML SDK 入门

Office Open XML(缩写为:OpenXML或OOXML),为Microsoft开发的一种以XML为基础并以ZIP格式压缩的电子档案规范,支持档案.表格.备忘录.幻灯片等档案格式.从Office 2007开始,Open XML格式以及成为Office的预设文档格式--DOCX, XLSX, PPTX.并且在2007年开始提供免费下载. 以下是Open XML SDK 2.5的官方下载地址.MSDN介绍文档和GitHub源码地址. http://www.microsoft.com/en-

使用POI3.10里的在word里插入图片的例子,生成的word打不开报错,如何解决

问题描述 使用POI3.10里的在word里插入图片的例子,生成的word打不开报错,如何解决 XWPFDocument doc = new XWPFDocument();//获取文档信息 XWPFParagraph p = doc.createParagraph(); ArrayList list=new ArrayList(); list.add("C:UsersluDesktopPoiSampleimage1.png"); list.add("C:UsersluDesk

[转载]Word直接发布新浪博客(以Word 2013为例)

原文地址:Word直接发布新浪博客(以Word 2013为例)作者:paulke2011 注意:这篇博客直接由Word 2013发出!这虽然也算是一个教程,但更多的是一个试验品. 老早就知道Word有发布博客的功能,但是一直没有用过.倒也不是没有尝试,而是都失败了.昨天写那一篇关于HCM术语的博客,折腾老半天的格式,发布到新浪博客的时候又因为种种限制导致格式丢失,变成了纯文本.于是又激起了我使用Word直接发布博客的欲望.于是到网上去搜了搜看看能不能碰巧找到解决办法. 甭说,还真有.James