Monday, June 25, 2012

word document to pdf conversion in SharePoint 2010

Points to remember:
1. Use this as a Farm Solution, Sandbox may have some API's restrictions.
2. Assume you want to add a document to a document library and that document should be converted to a PDF document.



Here is the code, for example you can add this code on ITEMADDED() event receiver of the document library.

using System.
using Microsoft.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities
using Microsoft.office.word.server.Conversions;


//verify is document added is a word document
if(properties.Listitem.Name.Contains(".docx") || properties.Listitem.Name.Contains(".doc"))
{
ConversionJosSettings jobSettings;
ConversionJob pdfConversion;
string wordfile;
string pdffile;
//Initiate the conversion settings
jobSettings = new ConversionJosSettings();
jobsettings.Outputformat = saveFormat.PDF;
Create the conversion job using the settings
pdfConversion  = new ConversionJob("Work Automation Services", jobSettings);
//Set the credentials to use when running the conversion job.
pdfConversion.UserToken = properties.web.CurrentUser.UserToken;
//Set the file names
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 conversion job
pdfConversion.AddFile(wordFile, pdfFile);
//Add the conversion job to the word automation services, conversion job queue.
// Conversion job will not take place immediately ( approx15 min process)
pdfConversion.Start();
}



Cheers!!!
Suneet

No comments: