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:

image

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.

image

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();
 }
}
目录
相关文章
|
9月前
|
Java 开发工具 开发者
dashvector的SDK包内含log4j2.xml,坑
对公SDK自带`log4j2.xml`配置,引发本地配置冲突。建议SDK开发者移除内置日志配置,避免影响用户设置。
128 0
|
XML 数据格式
wps2013打开word是xml
wps2013打开word是xml
|
XML JavaScript 开发工具
|
XML Android开发 数据格式
【Android错误集锦】AppBarLayout is overlapping the RecyclerView in one of my xml files.
问题现象:recyclerview 中的顶部数据被appbar遮盖,如下图红框所示 解决方法: 在activity_main.xml里面CoordinatorLayout布局下 即与AppBarLayout布局并列下加上 如下代码 <!--app:layout_beh.
1617 0
|
XML 数据格式
【word xml】将word转化为xml格式后,如何在xml中卫word添加分页符
1.首先在xml中找到我们需要添加分页符的位置 例如:我需要在这个第一部分上面添加一个分页符 2.找到这个【第一部分】这个位置之后,开始往上找,找到对应的位置 3.在下方添加分页符代码 1 2 ...
1940 0
|
XML 开发工具 数据格式
Csharp: read excel file using Open XML SDK 2.5
/// &lt;summary&gt; /// /// &lt;/summary&gt; public class SheetNameInfo { private int _sheetId; private string _sheetName; private string _rid;
1217 0
|
Web App开发 安全 Java
异常:The absolute uri: http://www.springframework.org/security/tags cannot be resolved in either web.xml or the jar files deployed with this application
The absolute uri: http://www.springframework.org/security/tags cannot be resolved in either web.xml or the jar files deployed with this application   需要添加spring-security-taglibs-3.
1754 0

热门文章

最新文章

  • 1
    【11】flutter进行了聊天页面的开发-增加了即时通讯聊天的整体页面和组件-切换-朋友-陌生人-vip开通详细页面-即时通讯sdk准备-直播sdk准备-即时通讯有无UI集成的区别介绍-开发完整的社交APP-前端客户端开发+数据联调|以优雅草商业项目为例做开发-flutter开发-全流程-商业应用级实战开发-优雅草Alex
  • 2
    【08】flutter完成屏幕适配-重建Android,增加GetX路由,屏幕适配,基础导航栏-多版本SDK以及gradle造成的关于fvm的使用(flutter version manage)-卓伊凡换人优雅草Alex-开发完整的社交APP-前端客户端开发+数据联调|以优雅草商业项目为例做开发-flutter开发-全流程-商业应用级实战开发-优雅草Alex
  • 3
    【02】鸿蒙实战应用开发-华为鸿蒙纯血操作系统Harmony OS NEXT-项目开发实战-准备工具安装-编译器DevEco Studio安装-arkts编程语言认识-编译器devco-鸿蒙SDK安装-模拟器环境调试-hyper虚拟化开启-全过程实战项目分享-从零开发到上线-优雅草卓伊凡
  • 4
    CompreFace:Star6.1k,Github上火爆的轻量化且强大的人脸识别库,api,sdk都支持
  • 5
    【Azure Developer】编写Python SDK代码实现从China Azure中VM Disk中创建磁盘快照Snapshot
  • 6
    【04】鸿蒙实战应用开发-华为鸿蒙纯血操作系统Harmony OS NEXT-正确安装鸿蒙SDK-结构目录介绍-路由介绍-帧动画(ohos.animator)书写介绍-能够正常使用依赖库等-ArkUI基础组件介绍-全过程实战项目分享-从零开发到上线-优雅草卓伊凡
  • 7
    php生成xml文件
  • 8
    TX Text Control文字处理教程(9)XML文件
  • 9
    WCF服务接口多,客户端在引用时出错!报WCF The maximum nametable character count quota (16384) has been exceeded while reading XML data错误
  • 10
    FLEX程序设计-XML(2)
  • 1
    【04】鸿蒙实战应用开发-华为鸿蒙纯血操作系统Harmony OS NEXT-正确安装鸿蒙SDK-结构目录介绍-路由介绍-帧动画(ohos.animator)书写介绍-能够正常使用依赖库等-ArkUI基础组件介绍-全过程实战项目分享-从零开发到上线-优雅草卓伊凡
    31
  • 2
    CompreFace:Star6.1k,Github上火爆的轻量化且强大的人脸识别库,api,sdk都支持
    23
  • 3
    【Azure Developer】编写Python SDK代码实现从China Azure中VM Disk中创建磁盘快照Snapshot
    19
  • 4
    【02】鸿蒙实战应用开发-华为鸿蒙纯血操作系统Harmony OS NEXT-项目开发实战-准备工具安装-编译器DevEco Studio安装-arkts编程语言认识-编译器devco-鸿蒙SDK安装-模拟器环境调试-hyper虚拟化开启-全过程实战项目分享-从零开发到上线-优雅草卓伊凡
    27
  • 5
    【11】flutter进行了聊天页面的开发-增加了即时通讯聊天的整体页面和组件-切换-朋友-陌生人-vip开通详细页面-即时通讯sdk准备-直播sdk准备-即时通讯有无UI集成的区别介绍-开发完整的社交APP-前端客户端开发+数据联调|以优雅草商业项目为例做开发-flutter开发-全流程-商业应用级实战开发-优雅草Alex
    159
  • 6
    【08】flutter完成屏幕适配-重建Android,增加GetX路由,屏幕适配,基础导航栏-多版本SDK以及gradle造成的关于fvm的使用(flutter version manage)-卓伊凡换人优雅草Alex-开发完整的社交APP-前端客户端开发+数据联调|以优雅草商业项目为例做开发-flutter开发-全流程-商业应用级实战开发-优雅草Alex
    162
  • 7
    【01】完整开发即构美颜sdk的uni官方uts插件—让所有开发者可以直接使用即构美颜sdk的能力-优雅草卓伊凡
    75
  • 8
    AutoTalk第十三期-应知必会的自动化工具-阿里云SDK支持策略(一)
    55
  • 9
    自动化AutoTalk第十期:应知必会的自动化工具-阿里云SDK
    54
  • 10
    API稳定安全最佳实践:用阿里云SDK为业务保驾护航
    94
  • 相关课程

    更多