Using SharePoint 2010 Word Automation Services to convert Word documents to PDF files

A very interesting feature of SharePoint 2010 is the Word automation services. Word automation services allows you to convert between multiple document formats which runs as a batch job. This is very useful in many server side scenarios where customers require to archive documents, protect them from editing among many others.

I am Sharing the following code snippets that will allow you to convert between multiple document formats…. 

private void ConvertDocFileToPDF(SPFile filex)
{
    // The job and its settings
    ConversionJobSettings settings;
    ConversionJob job;
    // Set the conversion settings, the enumeration allows you to convert to PDF, RTF, XPS and other word formats
    settings = new ConversionJobSettings();
    settings.OutputFormat = SaveFormat.PDF;
    // Create th conversion job…this must be the name of the job as defined in SharePoint farm
    job = new ConversionJob(ConfigurationHelper.Instance.DocumentConversionService, settings);
    // Most propably, you will want this job to run with system credintials, however, you can use other
    job.UserToken = SPUserToken.SystemAccount;
    // Add your file to the conversion job…in this example, you can also save the converted file to an attachement!!! IN the below code, you might use the SPContext object to get the root URL of your website
    string pdfFile = filex.Url.Replace(“docx”,”pdf”)
    job.AddFile(“http://<your site URL>/”+ filex.Url, “http://<your site URL>/” + pdfFile);

    // Start the conversion job
    job.Start();
}

You will need to add reference to the assembly “Microsoft.Office.Word.Server” which you will find in “C:Program FilesCommon FilesMicrosoft SharedWeb Server Extensions14ISAPI”.

To ensure that your code runs with no problem, ensure that you did setup a Word Automation Service in your SharePoint farm by checking the service applications from the central administration, or create new one…

 

 

 

 

 

 

 

 

 

 

when you want to test it, run the job “Word Automation Services Timer Job” which will allow you to test the conversion immediately. If you cannot find this job, this means that the configuration is missed up and your code will probably not run, so check this job first before running your code.

 Happy coding:)

Leave a Reply