Showing posts with label Word Automation Services. Show all posts
Showing posts with label Word Automation Services. Show all posts

Friday, 17 February 2012

Developing with SharePoint 2010 Word Automation Services

To build the application




  1. Start Microsoft Visual Studio 2010.

  2. On the File menu, point to New, and then click Project.

  3. In the New Project dialog box, in the Recent Template pane, expand Visual C#, and then click Windows.

  4. To the right side of the Recent Template pane, click Console Application.

  5. By default, Visual Studio creates a project that targets .NET Framework 4. However, you must target .NET Framework 3.5. From the list at the upper part of the File Open dialog box, select .NET Framework 3.5.

  6. In the Name box, type the name that you want to use for your project, such as FirstWordAutomationServicesApplication.

  7. In the Location box, type the location where you want to place the project.

    Figure 1. Creating a solution in the New Project dialog box

    Creating solution in the New Project box

  8. Click OK to create the solution.

  9. By default, Visual Studio 2010 creates projects that target x86 CPUs, but to build SharePoint Server applications, you must target any CPU.

  10. If you are building a Microsoft Visual C# application, in Solution Explorer window, right-click the project, and then click Properties.

  11. In the project properties window, click Build.

  12. Point to the Platform Target list, and select Any CPU.

    Figure 2. Target Any CPU when building a C# console application

    Changing target to any CPU

  13. If you are building a Microsoft Visual Basic .NET Framework application, in the project properties window, click Compile.

    Figure 3. Compile options for a Visual Basic application

    Compile options for Visual Basic applications

  14. Click Advanced Compile Options.

    Figure 4. Advanced Compiler Settings dialog box

    Advanced Compiler Settings dialog box

  15. Point to the Platform Target list, and then click Any CPU.

  16. To add a reference to the Microsoft.Office.Word.Server assembly, on the Project menu, click Add Reference to open the Add Reference dialog box.

  17. Select the .NET tab, and add the component named Microsoft Office 2010 component.

    Figure 5. Adding a reference to Microsoft Office 2010 component

    Add reference to Microsoft Office 2010 component

  18. Next, add a reference to the Microsoft.SharePoint assembly.

    Figure 6. Adding a reference to Microsoft SharePoint

    Adding reference to Microsoft SharePoint



The following examples provide the complete C# and Visual Basic listings for the simplest Word Automation Services application.






using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.Office.Word.Server.Conversions;

class Program
{
static void Main(string[] args)
{
string siteUrl = "http://localhost";
// If you manually installed Word automation services, then replace the name
// in the following line with the name that you assigned to the service when
// you installed it.
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/Test.docx",
siteUrl + "/Shared%20Documents/Test.pdf");
job.Start();
}
}
}





To build and run the example




  1. Add a Word document named Test.docx to the Shared Documents folder in the SharePoint site.

  2. Build and run the example.

  3. After waiting one minute for the conversion process to run, navigate to the Shared Documents folder in the SharePoint site, and refresh the page. The document library now contains a new PDF document, Test.pdf.



Monitoring Conversion Status




In many scenarios, you want to monitor the status of conversions, to inform the user when the conversion process is complete, or to process the converted documents in additional ways. You can use the ConversionJobStatus class to query Word Automation Services about the status of a conversion job. You pass the name of the WordServiceApplicationProxy class as a string (by default, "Word Automation Services"), and the conversion job identifier, which you can get from the ConversionJob object. You can also pass a GUID that specifies a tenant partition. However, if the SharePoint Server farm is not configured for multiple tenants, you can pass null (Nothing in Visual Basic) as the argument for this parameter.

After you instantiate a ConversionJobStatus object, you can access several properties that indicate the status of the conversion job. The following are the three most interesting properties.

ConversionJobStatus Properties





















PropertyReturn Value
CountNumber of documents currently in the conversion job.
SucceededNumber of documents successfully converted.
FailedThe number of documents that failed conversion.

Whereas the first example specified a single document to convert, the following example converts all documents in a specified document library. You have the option of creating all converted documents in a different document library than the source library, but for simplicity, the following example specifies the same document library for both the input and output document libraries. In addition, the following example specifies that the conversion job should overwrite the output document if it already exists.






Console.WriteLine("Starting conversion job");
ConversionJob job = new ConversionJob(wordAutomationServiceName);
job.UserToken = spSite.UserToken;
job.Settings.UpdateFields = true;
job.Settings.OutputFormat = SaveFormat.PDF;
job.Settings.OutputSaveBehavior = SaveBehavior.AlwaysOverwrite;
SPList listToConvert = spSite.RootWeb.Lists["Shared Documents"];
job.AddLibrary(listToConvert, listToConvert);
job.Start();
Console.WriteLine("Conversion job started");
ConversionJobStatus status = new ConversionJobStatus(wordAutomationServiceName,
job.JobId, null);
Console.WriteLine("Number of documents in conversion job: {0}", status.Count);
while (true)
{
Thread.Sleep(5000);
status = new ConversionJobStatus(wordAutomationServiceName, job.JobId,
null);
if (status.Count == status.Succeeded + status.Failed)
{
Console.WriteLine("Completed, Successful: {0}, Failed: {1}",
status.Succeeded, status.Failed);
break;
}
Console.WriteLine("In progress, Successful: {0}, Failed: {1}",
status.Succeeded, status.Failed);
}





To run this example, add some WordprocessingML documents in the Shared Documents library. When you run this example, you see output similar to this code snippet,





Starting conversion job
Conversion job started
Number of documents in conversion job: 4
In progress, Successful: 0, Failed: 0
In progress, Successful: 0, Failed: 0
Completed, Successful: 4, Failed: 0






Identifying Documents That Failed to Convert




You may want to determine which documents failed conversion, perhaps to inform the user, or take remedial action such as removing the invalid document from the input document library. You can call the GetItems method, which returns a collection of ConversionItemInfo objects. When you call the GetItems method, you pass a parameter that specifies whether you want to retrieve a collection of failed conversions or successful conversions.

C#





Console.WriteLine("Starting conversion job");
ConversionJob job = new ConversionJob(wordAutomationServiceName);
job.UserToken = spSite.UserToken;
job.Settings.UpdateFields = true;
job.Settings.OutputFormat = SaveFormat.PDF;
job.Settings.OutputSaveBehavior = SaveBehavior.AlwaysOverwrite;
SPList listToConvert = spSite.RootWeb.Lists["Shared Documents"];
job.AddLibrary(listToConvert, listToConvert);
job.Start();
Console.WriteLine("Conversion job started");
ConversionJobStatus status = new ConversionJobStatus(wordAutomationServiceName,
job.JobId, null);
Console.WriteLine("Number of documents in conversion job: {0}", status.Count);
while (true)
{
Thread.Sleep(5000);
status = new ConversionJobStatus(wordAutomationServiceName, job.JobId, null);
if (status.Count == status.Succeeded + status.Failed)
{
Console.WriteLine("Completed, Successful: {0}, Failed: {1}",
status.Succeeded, status.Failed);
ReadOnlyCollection<ConversionItemInfo> failedItems =
status.GetItems(ItemTypes.Failed);
foreach (var failedItem in failedItems)
Console.WriteLine("Failed item: Name:{0}", failedItem.InputFile);
break;
}
Console.WriteLine("In progress, Successful: {0}, Failed: {1}", status.Succeeded,
status.Failed);
}





To run this example, create an invalid document and upload it to the document library. An easy way to create an invalid document is to rename the WordprocessingML document, appending .zip to the file name. Then delete the main document part (known as document.xml), which is in the Word folder of the package. Rename the document, removing the .zip extension so that it contains the normal .docx extension.

When you run this example, it produces output similar to the following.






Starting conversion job
Conversion job started
Number of documents in conversion job: 5
In progress, Successful: 0, Failed: 0
In progress, Successful: 0, Failed: 0
In progress, Successful: 4, Failed: 0
In progress, Successful: 4, Failed: 0
In progress, Successful: 4, Failed: 0
Completed, Successful: 4, Failed: 1
Failed item: Name:http://intranet.contoso.com/Shared%20Documents/IntentionallyInvalidDocument.docx





Another approach to monitoring a conversion process is to use event handlers on a SharePoint list to determine when a converted document is added to the output document library.


Deleting Source Files after Conversion









Console.WriteLine("Starting conversion job");
ConversionJob job = new ConversionJob(wordAutomationServiceName);
job.UserToken = spSite.UserToken;
job.Settings.UpdateFields = true;
job.Settings.OutputFormat = SaveFormat.PDF;
job.Settings.OutputSaveBehavior = SaveBehavior.AlwaysOverwrite;
SPFolder folderToConvert = spSite.RootWeb.GetFolder("Shared Documents");
job.AddFolder(folderToConvert, folderToConvert, false);
job.Start();
Console.WriteLine("Conversion job started");
ConversionJobStatus status = new ConversionJobStatus(wordAutomationServiceName,
job.JobId, null);
Console.WriteLine("Number of documents in conversion job: {0}", status.Count);
while (true)
{
Thread.Sleep(5000);
status = new ConversionJobStatus(wordAutomationServiceName, job.JobId, null);
if (status.Count == status.Succeeded + status.Failed)
{
Console.WriteLine("Completed, Successful: {0}, Failed: {1}",
status.Succeeded, status.Failed);
Console.WriteLine("Deleting only items that successfully converted");
ReadOnlyCollection<ConversionItemInfo> convertedItems =
status.GetItems(ItemTypes.Succeeded);
foreach (var convertedItem in convertedItems)
{
Console.WriteLine("Deleting item: Name:{0}", convertedItem.InputFile);
folderToConvert.Files.Delete(convertedItem.InputFile);
}
break;
}
Console.WriteLine("In progress, Successful: {0}, Failed: {1}",
status.Succeeded, status.Failed);
}











Console.WriteLine("Starting conversion job")
Dim job As ConversionJob = New ConversionJob(wordAutomationServiceName)
job.UserToken = spSite.UserToken
job.Settings.UpdateFields = True
job.Settings.OutputFormat = SaveFormat.PDF
job.Settings.OutputSaveBehavior = SaveBehavior.AlwaysOverwrite
Dim folderToConvert As SPFolder = spSite.RootWeb.GetFolder("Shared Documents")
job.AddFolder(folderToConvert, folderToConvert, False)
job.Start()
Console.WriteLine("Conversion job started")
Dim status As ConversionJobStatus = _
New ConversionJobStatus(wordAutomationServiceName, job.JobId, Nothing)
Console.WriteLine("Number of documents in conversion job: {0}", status.Count)
While True
Thread.Sleep(5000)
status = New ConversionJobStatus(wordAutomationServiceName, job.JobId, _
Nothing)
If status.Count = status.Succeeded + status.Failed Then
Console.WriteLine("Completed, Successful: {0}, Failed: {1}", _
status.Succeeded, status.Failed)
Console.WriteLine("Deleting only items that successfully converted")
Dim convertedItems As ReadOnlyCollection(Of ConversionItemInfo) = _
status.GetItems(ItemTypes.Succeeded)
For Each convertedItem In convertedItems
Console.WriteLine("Deleting item: Name:{0}", convertedItem.InputFile)
folderToConvert.Files.Delete(convertedItem.InputFile)
Next
Exit While
End If
Console.WriteLine("In progress, Successful: {0}, Failed: {1}",
status.Succeeded, status.Failed)
End While





 


Integrating with the Open XML SDK




The power of using Word Automation Services becomes clear when you use it in combination with the Welcome to the Open XML SDK 2.0 for Microsoft Office. You can programmatically modify a document in a document library by using the Welcome to the Open XML SDK 2.0 for Microsoft Office, and then use Word Automation Services to perform one of the difficult tasks by using the Open XML SDK. A common need is to programmatically generate a document, and then generate or update the table of contents of the document. Consider the following document, which contains a table of contents.

Figure 7. Document with a table of contents

Document with table of contentsLet’s assume you want to modify this document, adding content that should be included in the table of contents. This next example takes the following steps.

  1. Opens the site and retrieves the Test.docx document by using a Collaborative Application Markup Language (CAML) query.

  2. Opens the document by using the Open XML SDK 2.0, and adds a new paragraph styled as Heading 1 at the beginning of the document.

  3. Starts a conversion job, converting Test.docx to TestWithNewToc.docx. It waits for the conversion to complete, and reports whether it was converted successfully.




C#
Console.WriteLine("Querying for Test.docx");
SPList list = spSite.RootWeb.Lists["Shared Documents"];
SPQuery query = new SPQuery();
query.ViewFields = @"<FieldRef Name='FileLeafRef' />";
query.Query =
@"<Where>
<Eq>
<FieldRef Name='FileLeafRef' />
<Value Type='Text'>Test.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))
{
Document document = wordDoc.MainDocumentPart.Document;
Paragraph firstParagraph = document.Body.Elements<Paragraph>()
.FirstOrDefault();
if (firstParagraph != null)
{
Paragraph newParagraph = new Paragraph(
new ParagraphProperties(
new ParagraphStyleId() { Val = "Heading1" }),
new Run(
new Text("About the Author")));
Paragraph aboutAuthorParagraph = new Paragraph(
new Run(
new Text("Eric White")));
firstParagraph.Parent.InsertBefore(newParagraph, firstParagraph);
firstParagraph.Parent.InsertBefore(aboutAuthorParagraph,
firstParagraph);
}
}
Console.WriteLine("Saving");
string linkFileName = file.Item["LinkFilename"] as string;
file.ParentFolder.Files.Add(linkFileName, memStr, true);
}
Console.WriteLine("Starting conversion job");
ConversionJob job = new ConversionJob(wordAutomationServiceName);
job.UserToken = spSite.UserToken;
job.Settings.UpdateFields = true;
job.Settings.OutputFormat = SaveFormat.Document;
job.AddFile(siteUrl + "/Shared%20Documents/Test.docx",
siteUrl + "/Shared%20Documents/TestWithNewToc.docx");
job.Start();
Console.WriteLine("After starting conversion job");
while (true)
{
Thread.Sleep(5000);
Console.WriteLine("Polling...");
ConversionJobStatus status = new ConversionJobStatus(
wordAutomationServiceName, job.JobId, null);
if (status.Count == status.Succeeded + status.Failed)
{
Console.WriteLine("Completed, Successful: {0}, Failed: {1}",
status.Succeeded, status.Failed);
break;
}
}




After running this example with a document similar to the one used earlier in this section, a new document is produced, as shown in Figure 8.

Figure 8. Document with updated table of contents

Document with updated table of contents

Conclusion




The Open XML SDK 2.0 is a powerful tool for building server-side document generation and document processing systems. However, there are aspects of document manipulation that are difficult, such a document conversions, and updating of fields, table of contents, and more. Word Automation Services fills this gap with a high-performance solution that can scale out to your requirements. Using the Open XML SDK 2.0 in combination with Word Automation Services enables many scenarios that are difficult when using only the Open XML SDK 2.0.

Document Creation and Conversion with the OpenXML SDK and SharePoint 2010 Word Automation Services

the solution to write the documents to a document library in SharePoint and then use Word Automation Services to automatically convert the docx files to PDF format.

Setup


To follow along with this walkthrough without changes, setup your SharePoint instance (at http://localhost) as follows:

  • Create a document library called "Created Docs" in the root site

  • Create a document library called "Converted Docs" in the root site


If you use a remote server, and/or a different site or library names, you'll need to adjust some of the URI and path strings in the code below to make it work.

Writing to a SharePoint Library


Carrying on from last time, wire up the click event of the CreateOneSharePointDocumentButton:


Click event handler



  1. private void CreateOneDocumentOnSharePointButton_Click(object sender, EventArgs e)

  2. {

  3.     gen.CreateOneDocumentOnSharePoint();

  4. }





Generate a stub for the CreateOneDocumentOnSharePoint() method in the DocGenerator class using the Ctrl+. technique made possible by the Visual Studio 2010 Productivity Power Tools.

Switch to and add a using statement to the DocGenerator class to give you access to the SharePoint Client Libraries - giving it an alias will help disambiguate the File class later:




  1. using SPC = Microsoft.SharePoint.Client;





Using the SharePoint Client Libraries, it's very easy to write documents to a document library, and there's no need to write a document to a local drive. This means we'll use a different overload of the OpenXML SDK's WordprocessingDocument.Create() method that writes, not to a file, but to a MemoryStream.


CreateOneDocumentOnSharePoint



  1. internal void CreateOneDocumentOnSharePoint()

  2. {

  3.   SPC.ClientContext clientContext = new SPC.ClientContext("http://localhost");

  4.   string fileUrl = "/Created Docs/MyVeryVeryCoolDoc.docx";


  5.   sw.Reset();

  6.   sw.Start();


  7.   using (MemoryStream ms = gen.CreatePackage())

  8.   {

  9.     ms.Seek(0, SeekOrigin.Begin);

  10.     SPC.File.SaveBinaryDirect(clientContext, fileUrl, ms, true);

  11.   }





In this code, you create a new SharePoint.Client.ClientContext that gives access to the site (in this case at http://localhost, but if you've got things set up differently, change it here).

Create an overload of the CreatePackage() method in the DocumentCreator class that creates and populates a MemoryStream:


CreatPackage Overload



  1. internal MemoryStream CreatePackage()

  2. {


  3.   MemoryStream ms = new MemoryStream();

  4.   using (WordprocessingDocument package =

  5.     WordprocessingDocument.Create

  6.     (ms, WordprocessingDocumentType.Document))

  7.   {

  8.     CreateParts(package);

  9.   }


  10.   return ms;


  11. }





Move the pointer to the start of the MemoryStream and call the File.SaveBinaryDirect() method passing in the ClientContext, a string indicating where the file should be written, the stream and a boolean that tells SharePoint whether or not to overwrite an existing file with the same name.

Running the app and clicking the One document in SharePoint button shows that it's very fast - in my case 102ms

Writing 1 document to SharePoint took 0.1 seconds

Writing lots of documents is fast too - add an event handler to the CreateOneSharePointDocumentButton:


Click Event Handler



  1. private void CreateManyDocumentsOnSharePointButton_Click(object sender, EventArgs e)

  2. {

  3.   gen.CreateManyDocumentsOnSharePointInParallel((int)NumberOfDocumentsToCreate.Value);


  4. }





And add a CreateManyDocumentsOnSharePointInParallel() method that uses a Parallel.For() loop to call CreatePackage() and File.SaveBinaryDirect() for as many files as you create:


Create lots of SharePoint Docs



  1. internal void CreateManyDocumentsOnSharePointInParallel(int NumberOfDocs)

  2. {

  3.   SPC.ClientContext clientContext = new SPC.ClientContext("http://localhost");

  4.   string fileUrl = "/Created Docs/MyEvenCoolerDoc{0:D5}.docx";


  5.   sw.Reset();

  6.   sw.Start();


  7.   Parallel.For(0, NumberOfDocs, i =>

  8.   {


  9.     using (MemoryStream ms = gen.CreatePackage())

  10.     {

  11.       ms.Seek(0, SeekOrigin.Begin);

  12.       SPC.File.SaveBinaryDirect(clientContext, string.Format(fileUrl, i), ms, true);

  13.     }


  14.   });


  15.   sw.Stop();


  16.   System.Windows.Forms.MessageBox.Show(string.Format(

  17.       "Wrote {3} documents to SharePoint ({1}{2}) in {0} ms (using parallel processing)",

  18.       sw.ElapsedMilliseconds,

  19.       clientContext.Url,

  20.       fileUrl,

  21.       NumberOfDocs));


  22. }





This is also pretty fast - in my case 40ms per document.

Writing 100 documents to SharePoint (in parallel) took 4 seconds

Navigating to the document library shows all those documents sitting just where you'd expect to see them:

Cool documents created en-masse

Converting Word Documents to a Fixed Format (PDF or XPS)


PDFUp until now, we've not had to use Word (or any other Office client) as all we've been doing is generating documents, not rendering them. Just like you can create an HTML document without requiring a browser, it's perfectly valid to create a Word document (or any other OpenXML format document) without using Word.

However, to view the document, or to create a fixed version of it like PDF or XPS, it's necessary to render it. Up until the release of SharePoint 2010, the highest fidelity way to do this was to open the document in Word. Of course, doing that on the server was fraught with difficulty. Word is not designed to be a server-side tool - it throws (sometimes modal) dialogs, it spends a lot of resources on updating the screen and it's not optimised for multi-processor, large memory scenarios. When there is a user interacting with Word though, the bottleneck is rarely the computer.

The SharePoint team addressed this problem with the Word Automation Services feature in SharePoint 2010 (standard edition and higher). Word Automation Services is the client code from Word with the UI bits stripped out and optimised to run as a server process. All of the rendering engine is available for SharePoint to use without any of the issues (both technical and from a licensing point of view) of using Word on a server. There's lots of great info on Word Automation Services on MSDN and elsewhere. Here's the list of resources I provided in the first post in this series:

Word Automation Services (WAS) document conversion jobs run as as an asynchronous server-side job that can either be scheduled automatically (for example, when a document is placed in a folder) or programmatically. Either way, the job won't start immediately, just the next time the WAS scheduler runs. The frequency of the scheduler running is set in Central Administration - see the links above for details on how to set it up. I set it to the minimum interval - one minute.

Interacting programmatically with the service is pretty straightforward, but there are two gotchas:

  1. the .NET libraries are 3.5 only, so the project you create must be a .NET 3.5 project, and

  2. the calls will fail (with cryptic exceptions) if it's not a 64-bit call, so you must target either x64 or Any processor type, not x86.


Create a new console application and make sure that the target framework is 3.5.

Create a new console application targetting Framework 3.5

Open the Visual Studio Configuration Manager dialog by dropping down the Solution Configurations drop-down on the Visual Studio Standard toolbar (or choosing Configuration Manager from the Build menu):

Choose Configuration Manager

Next, add a Solution Platform:

image

to target Any CPU (or x64)

image

Now you're ready to start building.

Converting a single document to PDF


Add references to the Microsoft.SharePoint and Microsoft.Office.Word.Server assemblies.

Add using statements for those assemblies:




  1. using Microsoft.SharePoint;

  2. using Microsoft.Office.Word.Server.Conversions;





Add a couple of static string properties to the class that you can adjust to suit the way you've got your SharePoint setup configured:




  1. // If you manually installed Word Automation Services, then replace the name

  2. // in the following line with the name that you assigned to the service when

  3. // you installed it.

  4. static string cWordServicesName = "Word Automation Services";

  5. static string siteUrl = "http://localhost";





Now you can initiate the conversion of a single document:


Convert a single document



  1. private static void SingleConv()

  2. {

  3.   using (SPSite spSite = new SPSite(siteUrl))

  4.   {

  5.     ConversionJob job = new ConversionJob(cWordServicesName);

  6.     job.UserToken = spSite.UserToken;

  7.     job.Settings.UpdateFields = true;

  8.     job.Settings.OutputFormat = SaveFormat.PDF;

  9.     job.AddFile(siteUrl + "/Created%20Docs/MyAwesomeDoc.docx",

  10.         siteUrl + "/Converted%20Docs/MyAwesomeDoc.pdf");

  11.     job.Start();

  12.     Console.WriteLine("Job ID: {0} started", job.JobId);

  13.     Console.WriteLine("Press the any key ...");

  14.     Console.ReadKey();

  15.   }

  16. }





There are a few things to note here.

Firstly, you get a reference to the Site using the SharePoint libraries, not the SharePoint Client libraries that we used to write the Word docs to the list in the first place.

Next, you need to pass a user token to the new ConversionJob, and you get that from the SPSite user token.

Third, you specify the output format using the SaveFormat enumeration.

Finally, remember the service is performed asynchronously and so although you get a Job ID back, you don't get any more information about the job status (more on that when we do bulk conversions)

Converting documents to PDF en-masse


Converting whole libraries at once is also very easy. The ConversionJob class has an AddLibrary() method that takes as parameters a source and destination SPList object.


Converting whole libraries



  1. private static void BulkConv()

  2. {

  3.   using (SPSite spSite = new SPSite(siteUrl))

  4.   {

  5.     Console.WriteLine("Starting conversion job");

  6.     ConversionJob job = new ConversionJob(cWordServicesName);

  7.     job.UserToken = spSite.UserToken;

  8.     job.Settings.UpdateFields = true;

  9.     job.Settings.OutputFormat = SaveFormat.PDF;

  10.     job.Settings.OutputSaveBehavior = SaveBehavior.AlwaysOverwrite;

  11.     SPList listToConvert = spSite.RootWeb.Lists["Created Docs"];

  12.     SPList listToPopulate = spSite.RootWeb.Lists["Converted Docs"];

  13.     job.AddLibrary(listToConvert, listToPopulate);

  14.     job.Start();

  15.     Console.WriteLine("Bulk conversion job {0} started", job.JobId);

  16.     ConversionJobStatus status = new ConversionJobStatus(cWordServicesName,

  17.         job.JobId, null);

  18.     Console.WriteLine("Number of documents in conversion job: {0}", status.Count);

  19.     while (true)

  20.     {

  21.       System.Threading.Thread.Sleep(5000);


  22.       status.Refresh();

  23.       if (status.Count == status.Succeeded + status.Failed)

  24.       {

  25.         Console.WriteLine("{2} Completed, Successful: {0}, Failed: {1}",

  26.             status.Succeeded, status.Failed, DateTime.Now);

  27.         break;

  28.       }

  29.       Console.WriteLine("{2} In progress, Successful: {0}, Failed: {1}",

  30.           status.Succeeded, status.Failed, DateTime.Now);

  31.     }


  32.     Console.ReadKey();

  33.   }

  34. }





Checking the status of the job is straightforward (as long as you have the JobId - a GUID uniquely identifying this conversion job). The ConversionJobStatus object holds information about the conversion job including how many documents are to be converted, how many have been converted successfully and how many have failed. Calling the Refresh() method gets the most up-to-date status and you can use that to poll for completion. Remember that jobs only start every <n> minutes, where n is a setting in SharePoint Central Administration

Converting documents is an asynchronous process

The result is a SharePoint list full of PDF files, created without ever needing to open Word.

A library full of converted PDFs

A converted PDF in Adobe Reader

Conclusion


The combination of the OpenXML SDK and Word Automation Services makes server-side document creation simple, scalable and efficient. This is definitely a tool worth adding to your arsenal.

Monday, 19 December 2011

Word Automation Services: Asynchronous

What that Means


That has two important consequences for solutions:

  • First, it means that you don't know immediately when a conversion has completed – the Start() call for a ConversionJob returns as soon as the job is submitted into the queue. You must monitor the job's status (via the ConversionJobStatus object) or use list-level events if you want to know when the conversion is complete and/or perform actions post-conversion.

  • Second, it means that maximum throughput is defined by the frequency with which the queue is polled for work, and the amount of new work requested on each polling interval.


Dissecting those consequences a little further:

Asynchronous


The asynchronous nature of the service means you need to set up your solutions to use either list events or the job status API to find out when a conversion is complete. For example, if I wanted to delete the original file once the converted one was written, as commenter Flynn suggested, I would need to do something like this:
public void ConvertAndDelete(string[] inputFiles, string[] outputFiles)
{
    //start the conversion
    ConversionJob job = new ConversionJob("Word Automation Services");
    job.UserToken = SPContext.Site.UserToken;
    for (int i = 0; i < inputFiles.Count; i++)
        job.AddFile(inputfiles[i], outputFiles[i]);
    job.Start();

    bool done = false;
    while(!done)
    {
        Thread.Sleep(5000);
        ConversionJobStatus status = new ConversionJobStatus("Word Automation Services", jobId, null);
        
        if(status.Count == (status.Succeeded + status.Failed + status.Canceled)) //everything done
        {
            done = true;
            
            //only delete successful conversions
            ConversionItemInfo[] items = status.GetItems(ItemType.Succeeded);
            foreach(ConversionItemInfo item in items)
                SPContext.Web.Files.Delete(item);
        }
    }
}

Now, clearly using Thread.Sleep isn't something you'd want to do if this is going to happen on many threads simultaneously on the server, but you get the idea – a workflow with a Delay activity is another example of a solution to this situation.

Friday, 16 December 2011

Convert docx to pdf document in SharePoint 2010 using Word Automation Services

Word Automation Services is a new feature available in SharePoint 2010. It supports converting Word documents to other formats. Here we are going to convert the word document into pdf document. In the API for Word Automation Services there are different ways to convert documents including AddFile(), AddFolder() and AddLibrary() methods. Here we will be using AddFile() method to convert the word document (this method will convert the word document within the same list).
This article describes the following steps to show how to call the Word Automation Services to convert a document:




  • Add a word document to the SharePoint Shared Documents.

  • Create a console Application.

  • Add a reference to the Microsoft.Office.Word.Server assembly.


Add a word document in the Shared Documents:
Create a console application:


  • Open Visual Studio 2010.

  • Go to File => New => Project.

  • Select the Console Application template and enter the Name.

  • Click Ok.

  • Add a reference to the Microsoft.Office.Word.Server assembly (C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI\ Microsoft.Office.Word.Server.dll)

  • Open Program.cs file and replace the code with the following.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Word.Server.Conversions;
using Microsoft.SharePoint;

namespace Test
{
class Program
{
static void Main(string[] args)
{
using (SPSite spSite = new SPSite( "http://servername:4040/"))
{
//Defines a collection of settings for all conversions within a single conversion job.
ConversionJobSettings jobSettings=new ConversionJobSettings();
jobSettings.OutputFormat = SaveFormat.PDF;
//Represents a collection of file conversions (of single files or entire libraries) that share a common set of conversion properties and are
logically tracked as a single unit.
ConversionJob pdfConversion = new ConversionJob("Word Automation Services", jobSettings);
// Set the credentials to use when running the conversion job.
pdfConversion.UserToken = spSite.UserToken;
pdfConversion.AddFile("http://servername:4040/Shared%20Documents/ExternalList.docx",
"http://servername:4040/Shared%20Documents/ExternalList.pdf");
pdfConversion.Start();
}
}
}
}

 

Converting Word Documents to PDF Using SharePoint Server 2010 and Word Automation Services

Summary:   Learn to programmatically convert Word documents to PDF format on the server by using Word Automation Services with SharePoint Server 2010.

Applies to:   Microsoft SharePoint Server 2010 | Microsoft Business Connectivity Services| Microsoft Visual Studio 2010






OverviewSharePoint 2010 Word Automation Services available with SharePoint Server 2010 supports converting Word documents to other formats. This includes PDF. This article describes using a document library list item event receiver to call Word Automation Services to convert Word documents to PDF when they are added to the list. The event receiver checks whether the list item added is a Word document. If so, it creates a conversion job to create a PDF version of the Word document and pushes the conversion job to the Word Automation Services conversion job queue.

Code ItThis article describes the following steps to show how to call the Word Automation Services to convert a document:

  1. Creating a SharePoint 2010 list definition application solution in Visual Studio 2010.

  2. Adding a reference to the Microsoft.Office.Word.Server assembly.

  3. Adding an event receiver.

  4. Adding the sample code to the solution.


 

Creating a SharePoint 2010 List Definition Application in Visual Studio 2010

This article uses a SharePoint 2010 list definition application for the sample code.

To create a SharePoint 2010 list definition application in Visual Studio 2010




  1. Start Microsoft Visual Studio 2010 as an administrator.

  2. From the File Menu, point to the Project menu and then click New.

  3. In the New Project dialog box select the Visual C# SharePoint 2010 template type in the Project Templates pane.

  4. Select List Definition in the Templates pane.

  5. Name the project and solution ConvertWordToPDF.

    Figure 1. Creating the Solution

    Creating the solution

  6. To create the solution, click OK.

  7. Select a site to use for debugging and deployment.

  8. Select the site to use for debugging and the trust level for the SharePoint solution.










    note Note:
    Make sure to select the trust level Deploy as a farm solution. If you deploy as a sandboxed solution, it does not work because the solution uses the Microsoft.Office.Word.Server assembly. This assembly does not allow for calls from partially trusted callers.

     


    Figure 2. Selecting the trust level

    Creating the solution

  9. To finish creating the solution, click Finish.



Adding a Reference to the Microsoft Office Word Server Assembly

To use Word Automation Services, you must add a reference to the Microsoft.Office.Word.Server to the solution.

To add a reference to the Microsoft Office Word Server Assembly




  1. In Visual Studio, from the Project menu, select Add Reference.

  2. Locate the assembly. By using the Browse tab, locate the assembly. The Microsoft.Office.Word.Server assembly is located in the SharePoint 2010 ISAPI folder. This is usually located at C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI. After the assembly is located, click OK to add the reference.

    Figure 3. Adding the Reference

    Adding the reference



Adding an Event Receiver

This article uses an event receiver that uses the Microsoft.Office.Word.Server assembly to create document conversion jobs and add them to the Word Automation Services conversion job queue.

To add an event receiver




  1. In Visual Studio, on the Project menu, click Add New Item.

  2. In the Add New Item dialog box, in the Project Templates pane, click the Visual C# SharePoint 2010 template.

  3. In the Templates pane, click Event Receiver.

  4. Name the event receiver ConvertWordToPDFEventReceiver and then click Add.

    Figure 4. Adding an Event Receiver

    Adding an event receiver

  5. The event receiver converts Word Documents after they are added to the List. Select the An item was added item from the list of events that can be handled.

    Figure 5. Choosing Event Receiver Settings

    Choosing even receiver settings

  6. Click Finish to add the event receiver to the project.



Adding the Sample Code to the Solution

Replace the contents of the ConvertWordToPDFEventReceiver.cs source file with the following code.






using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;

using Microsoft.Office.Word.Server.Conversions;

namespace ConvertWordToPDF.ConvertWordToPDFEventReceiver
{
/// <summary>
/// List Item Events
/// </summary>
public class ConvertWordToPDFEventReceiver : SPItemEventReceiver
{
/// <summary>
/// An item was added.
/// </summary>
public override void ItemAdded(SPItemEventProperties properties)
{
base.ItemAdded(properties);

// Verify the document added is a Word document
// before starting the conversion.
if (properties.ListItem.Name.Contains(".docx")
|| properties.ListItem.Name.Contains(".doc"))
{
//Variables used by the sample code.
ConversionJobSettings jobSettings;
ConversionJob pdfConversion;
string wordFile;
string pdfFile;

// Initialize the conversion settings.
jobSettings = new ConversionJobSettings();
jobSettings.OutputFormat = SaveFormat.PDF;

// Create the conversion job using the settings.
pdfConversion =
new ConversionJob("Word Automation Services", jobSettings);

// Set the credentials to use when running the conversion job.
pdfConversion.UserToken = properties.Web.CurrentUser.UserToken;

// Set the file names to use for the source Word document
// and the destination PDF document.
wordFile = properties.WebUrl + "/" + properties.ListItem.Url;
if (properties.ListItem.Name.Contains(".docx"))
{
pdfFile = wordFile.Replace(".docx", ".pdf");
}
else
{
pdfFile = wordFile.Replace(".doc", ".pdf");
}

// Add the file conversion to the conversion job.
pdfConversion.AddFile(wordFile, pdfFile);

// Add the conversion job to the Word Automation Services
// conversion job queue. The conversion does not occur
// immediately but is processed during the next run of
// the document conversion job.
pdfConversion.Start();

}
}
}
}





 

Read ItWord Automation Services provided with SharePoint Server 2010 enables you to create server-based document solutions. Combining the functionality that is provided by Word Automation Services with the document content manipulation support provided with the Open XML SDK enables you to create rich document solutions that execute on the server that do not require Automation of the Word client application.

Examples of the kinds of operations supported by Word Automation Services are as follows:

  • Converting between document formats (e.g. DOC to DOCX)

  • Converting to fixed formats (e.g. PDF or XPS)

  • Updating fields

  • Importing "alternate format chunks"


This article contains sample code that shows how to create a SharePoint list event handler that can create Word Automation Services conversion jobs in response to Word documents being added to the list. This section uses code examples taken from the complete, working sample code provided earlier in this article to describe the approach taken by this article.

The ItemAdded event handler in the list event handler first verifies that the item added to the document library list is a Word document by checking the name of the document for the .doc or .docx file name extension.






// Verify the document added is a Word document
// before starting the conversion.
if (properties.ListItem.Name.Contains(".docx")
|| properties.ListItem.Name.Contains(".doc"))
{





If the item is a Word document then the code creates and initializes ConversionJobSettings and ConversionJob objects to convert the document to the PDF format.






//Variables used by the sample code.
ConversionJobSettings jobSettings;
ConversionJob pdfConversion;
string wordFile;
string pdfFile;

// Initialize the conversion settings.
jobSettings = new ConversionJobSettings();
jobSettings.OutputFormat = SaveFormat.PDF;

// Create the conversion job using the settings.
pdfConversion =
new ConversionJob("Word Automation Services", jobSettings);

// Set the credentials to use when running the conversion job.
pdfConversion.UserToken = properties.Web.CurrentUser.UserToken;





The Word document to be converted and the name of the PDF document to be created are added to the ConversionJob.






// Set the file names to use for the source Word document
// and the destination PDF document.
wordFile = properties.WebUrl + "/" + properties.ListItem.Url;
if (properties.ListItem.Name.Contains(".docx"))
{
pdfFile = wordFile.Replace(".docx", ".pdf");
}
else
{
pdfFile = wordFile.Replace(".doc", ".pdf");
}

// Add the file conversion to the Conversion Job.
pdfConversion.AddFile(wordFile, pdfFile);





Finally the ConversionJob is added to the Word Automation Services conversion job queue.






// Add the conversion job to the Word Automation Services 
// conversion job queue. The conversion does not occur
// immediately but is processed during the next run of
// the document conversion job.
pdfConversion.Start();