Tuesday, January 17, 2012

Adding a Converted File to the Same Document Library

The problem:

Sometimes, it is desirable to convert some document to PDF (or some other format) and do it automatically, whenever the document appears in the document library.

The solution:

First of all, there is no easy way to convert a document to PDF without using a third-party product. I use Muhimbi Converter for SharePoint (http://www.muhimbi.com/).

If you want to create a converted document whenever the source document appears in the document library, you need a list item receiver. Override the ItemAdded() and ItemUpdated() methods.

You will need to add a service reference to the Muhimbi Document Converter WCF service. Then, you will need to create a document converter service client to interact with that service. For more information, read

A little problem with this example is that it reads a file from the file system, rather than from the SharePoint library. You will need to get the byte array for the source document file. A good way to do it is:

SPFile spFile = copyItem.File;
string sourceFileName = spFile.Name;
byte[] sourceFile = spFile.OpenBinary();

The Convert() method takes this byte array, the open options, and the conversion settings as parameters and returns the byte array for the new file. Now you will need to add it as a new file to SharePoint. A good way to do it is:

spFolder = (copyItem.Folder == null ? copyItem.ParentList.RootFolder : copyItem.Folder);
string newFileUrl = string.Concat(spFolder.Url, "/", Path.GetFileNameWithoutExtension(sourceFileName), ".", conversionSettings.Format);
SPFile newFile = spFolder.Files.Add(newFileUrl, convFile);
newFile.Update();

No comments:

Post a Comment