Using Word Automation Services with the Open XML SDK using C#

This is the complete sample that shows how to use Word Automation Services with the Open XML SDK from the article Developing with SharePoint 2010 Word Automation Services.

This blog is inactive.
New blog: EricWhite.com/blog

Blog TOCNote for those of you using the SP2010 beta, the capability to update fields (and update the table of contents) was not working in that release. It works in recent builds, and of course will work in RTM.

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.SharePoint;
using Microsoft.Office.Word.Server.Conversions;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

class Program
{
    static void Main(string[] args)
    {
        string siteUrl = "https://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))
        {
            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;
                }
            }
        }
    }
}