Monthly Archives: June 2013

Power Point to PDF Conversion using PowerPoint Automation Services

Continuing from my previous article to convert word document to PDF, I would like to show you on how to utilize Power Point Automation Service to convert Power Point document into PDF document.

The requirement is Power Point Automation Service needs to be configured and started. I will not go through with you how to setup Power Point Automation Service, you could refer it here.

Below is the function to convert Power Point to PDF document, it will return file stream.

private SPFileStream ConvertPowerPointToPDF(SPFile file)
{
   string sFileName = file.Name.Trim();
   string sFileNameExtension = sFileName.Substring(sFileName.LastIndexOf('.') + 1);
   SPFileStream result = null;

   try
   {
      // Convert the file to a stream and create an SPFileStream object for the conversion output.
      Stream fStream = file.OpenBinaryStream();
      SPFileStream stream = new SPFileStream(file.Web, 0x1000);

      // Create the presentation conversion request.
      PdfRequest request = new PdfRequest(fStream, sFileNameExtension, stream);

      // Send the request synchronously, passing in a ‘null’ value for the callback parameter and capturing the response in the result object.
      IAsyncResult aSyncResult = request.BeginConvert(SPServiceContext.GetContext(file.Web.Site), null, null);

      // Use the EndConvert method to get the result. 
      request.EndConvert(aSyncResult);

      if (stream != null)
         result = stream;
   }
   catch (Exception ex)
   {
      // Do your error management here.
   }
   return result;
}

The ItemUpdated event, it will look like below. The PDF document will be added into “Documents Public” library with all custom column / metadata updated as well.

        public override void ItemUpdated(SPItemEventProperties properties)
        {
            base.ItemUpdated(properties);

            try
            {
                SPWeb web = properties.Web;
                SPFolder sourceFolder = properties.List.RootFolder;
                SPListItem sourceItem = properties.ListItem;
                SPFile sourceFile = sourceItem.File;
                string sourceFileName = sourceFile.Name.Trim();

                SPFolder destFolder = web.Lists["Documents Public"].RootFolder;
                SPFile destFile = null;
                string destFileName = sourceFileName.Substring(0, sourceFileName.LastIndexOf('.')) + ".pdf";
                bool isOverwrite = true;
                bool isDestApprovalRequired = false;

                // If File Approved
                if (sourceItem.ModerationInformation.Status == SPModerationStatusType.Approved)
                {
                    // Convert the office file
                    if (sourceFileName.EndsWith(".docx") || sourceFileName.EndsWith(".doc"))
                    {
                        // Check out existing PDF file if exists
                        CheckOutFile(web, String.Format("{0}/{1}/{2}", web.Url, destFolder.Url, destFileName));
                        destFile = destFolder.Files.Add(destFileName, ConvertWordToPDF(sourceFile, properties.Site.UserToken), isOverwrite );
                    }
                    else if (sourceFileName.EndsWith(".pptx") || sourceFileName.EndsWith(".ppt"))
                    {
                        // Check out existing PDF file if exists
                        CheckOutFile(web, String.Format("{0}/{1}/{2}", web.Url, destFolder.Url, destFileName));
                        destFile = destFolder.Files.Add(destFileName, ConvertPowerPointToPDF(sourceFile), isOverwrite);
                    }

                    if (destFile != null)
                    {
                        // Update PDF File metadata
                        foreach (SPField eachPdfField in destFile.Item.Fields)
                        {
                            if (eachPdfField.FromBaseType == false && !eachPdfField.ReadOnlyField)
                            {
                                destFile.Item[eachPdfField.Id] = sourceItem[eachPdfField.Id];
                            }
                        }

                        // Apply Update to PDF File
                        destFile.Item.Update();
                        destFolder.Update();

                        // Check In PDF File
                        if (destFile != null && destFile.CheckOutType != SPFile.SPCheckOutType.None)
                            destFile.CheckIn("");

                        // Approve
                        if(isDestApprovalRequired)
                            destFile.Approve("");

                        destFolder.Update();
                    }
                }
            }
            catch (Exception ex)
            {
                // Do your error management here.
            }
        }

        private void CheckOutFile(SPWeb web, string sFileUrl)
        {
            try
            {
                SPFile currFile = web.GetFile(sFileUrl);
                if (currFile != null && currFile.CheckOutType == SPFile.SPCheckOutType.None)
                {
                    currFile.CheckOut();
                }
            }
            catch (Exception ex)
            {
                // Do your error management here.
            }
        }
Advertisements

Word to PDF Conversion using Word Automation Service

In this article, I would like to show you on how to utilize Word Automation Service to convert word document into PDF document. Recently, I have an objective to convert document to PDF when it has been approved. So, I just use it with ItemUpdated event receiver and it works as expected.

The requirement is Word Automation Service needs to be configured and started. I will not go through with you how to setup Word Automation Service, you could refer it here.

Below is the function to convert Word to PDF document, it will return byte array. Replace WORD_AUTOMATION_SERVICE with your “Word Automation Service” service name.

        private byte[] ConvertWordToPDF(SPFile spFile, SPUserToken usrToken)
        {
            byte[] result = null;
            try
            {
                using (Stream read = spFile.OpenBinaryStream())
                {
                    using (MemoryStream write = new MemoryStream())
                    {
                        // Initialise Word Automation Service
                        SyncConverter sc = new SyncConverter(WORD_AUTOMATION_SERVICE);
                        sc.UserToken = usrToken;
                        sc.Settings.UpdateFields = true;
                        sc.Settings.OutputFormat = SaveFormat.PDF;

                        // Convert to PDF
                        ConversionItemInfo info = sc.Convert(read, write);
                        if (info.Succeeded)
                            result = write.ToArray();
                    }
                }
            }
            catch (Exception ex)
            {
                // Do your error management here.
            }
            return result;
        }

The ItemUpdated event, it will look like below. The PDF document will be added into “Documents Public” library with all custom column / metadata updated as well.

        public override void ItemUpdated(SPItemEventProperties properties)
        {
            base.ItemUpdated(properties);

            try
            {
                SPWeb web = properties.Web;
                SPFolder sourceFolder = properties.List.RootFolder;
                SPListItem sourceItem = properties.ListItem;
                SPFile sourceFile = sourceItem.File;
                string sourceFileName = sourceFile.Name.Trim();

                SPFolder destFolder = web.Lists["Documents Public"].RootFolder;
                SPFile destFile = null;
                string destFileName = sourceFileName.Substring(0, sourceFileName.LastIndexOf('.')) + ".pdf";
                bool isOverwrite = true;
                bool isDestApprovalRequired = false;

                // If File Approved
                if (sourceItem.ModerationInformation.Status == SPModerationStatusType.Approved)
                {
                    // Convert the office file
                    if (sourceFileName.EndsWith(".docx") || sourceFileName.EndsWith(".doc"))
                    {
                        // Check out existing PDF file if exists
                        CheckOutFile(web, String.Format("{0}/{1}/{2}", web.Url, destFolder.Url, destFileName));
                        destFile = destFolder.Files.Add(destFileName, ConvertWordToPDF(sourceFile, properties.Site.UserToken), isOverwrite );
                    }

                    if (destFile != null)
                    {
                        // Update PDF File metadata
                        foreach (SPField eachPdfField in destFile.Item.Fields)
                        {
                            if (eachPdfField.FromBaseType == false && !eachPdfField.ReadOnlyField)
                            {
                                destFile.Item[eachPdfField.Id] = sourceItem[eachPdfField.Id];
                            }
                        }

                        // Apply Update to PDF File
                        destFile.Item.Update();
                        destFolder.Update();

                        // Check In PDF File
                        if (destFile != null && destFile.CheckOutType != SPFile.SPCheckOutType.None)
                            destFile.CheckIn("");

                        // Approve
                        if(isDestApprovalRequired)
                            destFile.Approve("");

                        destFolder.Update();
                    }
                }
            }
            catch (Exception ex)
            {
                // Do your error management here.
            }
        }

        private void CheckOutFile(SPWeb web, string sFileUrl)
        {
            try
            {
                SPFile currFile = web.GetFile(sFileUrl);
                if (currFile != null && currFile.CheckOutType == SPFile.SPCheckOutType.None)
                {
                    currFile.CheckOut();
                }
            }
            catch (Exception ex)
            {
                // Do your error management here.
            }
        }
%d bloggers like this: