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

    Cookie[] cookies=request.getCookies(); for(Cookie c:cookies) out.println(c.getValue()+" ") ...

  2. 展示 Popup 的使用方法

    源码下载:[原创]展示Popup的使用方法.zip

  3. swipe.js 2.0 轻量级框架实现mobile web 左右滑动

    属性总结笔记如下: <style> .swipe { overflow: hidden; //隐藏溢出 清楚浮动 visibility: hidden; //规定元素不可见 (可以设置,当 ...

  4. 数据库热备之SQLServer的数据库镜像实施笔记

    / 最初在为公司设计SQLServer数据库镜像的时候,首先考虑的是高可用性(三台计算机,一台见证服务器,一台做主数据库,一台做镜像) 在虚拟机环境下部署成功,一切都是那么的完美.故障转移3秒之内就可 ...

  5. Web前端开发工程师基本要求

    一位好的Web前端开发工程师在知识体系上既要有广度,又要有深度,所以很多大公司即使出高薪也很难招聘到理想的前端开发工程师.现在说的重点不在于讲解技术,而是更侧重于对技巧的讲解.技术非黑即白,只有对和错 ...

  6. CSS中兼容的一面-----Hack

    国庆了,出去玩耍,也有好长时间没有更新博客了.. 今天就和大家共享一篇技术博文吧.. CSS中兼容的一面-----Hack技术大全 兼容范围: IE:6.0+,FireFox:2.0+,Opera 1 ...

  7. [DeviceOne开发]-白板的示例

    一.简介 该demo通过do_Painterview这个组件实现画板的基本功能,模仿的是Appstore上的叫“白板”的应用,可以更改字体颜色,字体粗细,然后用手指进行绘制,可以回退,清屏,保存到相册 ...

  8. mongodb 数据库操作--备份 还原 导出 导入

    mongodb数据备份和还原主要分为二种,一种是针对于库的mongodump和mongorestore,一种是针对库中表的mongoexport和mongoimport 一,mongodump备份数据 ...

  9. 【Bootstrap】2.作品展示站点

    假设我们已经想好了要给自己的作品弄一个在线站点.一如既往,时间紧迫.我们需要快一点,但作品展示效果又必须专业.当然,站点还得是响应式的,能够在各种设备上正常浏览,因为这是我们向目标客户推销时的卖点.这 ...

  10. github-ssh

        # lsb_release -a    No LSB modules are available.    Distributor ID:    Ubuntu    Description:   ...