Monday, 30 January 2012

Automatic converting Word file to PDF with replace

Word Automation Services available in SharePoint 2010 supports converting Word documents to other formats. This includes PDF. 
Following MSDN article describes step-by-step how to create Event Receiver, add proper libraries and code. Unfortunately, this creates new copy of PDF file, while I wanted the file to be overwritten to the same item. 

Instead of starting a job, that creates new file, I start conversion job that overwrites the file: 
pdfConversionJob.AddFile(wordFileName, wordFileName);

This creates file in the same item, but now you won't be able to open it, since SharePoint still treats this file as Word document. It would be great, if i could just change file name in ItemUpdated receiver. Problem is, that this job does not trigger Event Receivers. 
I put a waiting loop, that waits until job is finished (or until timeout passes):
int finishedConversionCount = cjStatus.Succeeded + cjStatus.Failed;
while ((finishedConversionCount != 1) && ((DateTime.Now - conversionStarted) < timeSpan))
{
    // wait one minute
    System.Threading.Thread.Sleep(60000);

    cjStatus = new ConversionJobStatus(wordServiceApplicationProxy, pdfConversionJob.JobId, null);
    finishedConversionCount = cjStatus.Succeeded + cjStatus.Failed;
} 
Then I have to change the name of the file. To do this, I use MoveTo method:
SPFile wordFile = properties.ListItem.File;
wordFile.MoveTo(pdfFileName, true);

The full Event Receiver code can be found here.


No comments:

Post a Comment