Convert Word to PDF

Update: this blog has been moved to http://brandonzeider.me/2010/microsoft-net/convert-word-to-pdf/.

I recently had a requirement to convert Microsoft Word documents to PDF. I don't mind purchasing libraries for things like this if I have to, as there are several good ones: ABDpdf and Aspose come immediately to mind (there are certainly others). However my preference is always to limit the amount of third party code that I use, so I went in search of a way to do it natively within .NET.

Solution

Pretty simple solution - the sample class below is all you need. You will need to add a reference to the Microsoft.Office.Interop.Word assembly version 12.0.0.0 (or higher) for this to work. Please note that you also need to have Microsoft Word installed on the machine that executes this code. To use, you simply pass in the file path to the Word document that you'd like to convert and the file path where you'd like your PDF to be saved. That's it. You can of course modify this class to fit your needs.

Code

using System;
using Microsoft.Office.Interop.Word;

namespace Framework
{
    public sealed class Conversion
    {
        /// <summary>
        /// Converts the word to PDF.
        /// </summary>
        /// <param name="wordDocumentFilePath">The word document file path.</param>
        /// <param name="pdfFilePath">The PDF file path.</param>
        /// <returns></returns>
        public static bool ConvertWordToPdf(string wordDocumentFilePath, string pdfFilePath)
        {
            return PerformConversion(wordDocumentFilePath, pdfFilePath, WdExportFormat.wdExportFormatPDF);
        }

        /// <summary>
        /// Performs the conversion.
        /// </summary>
        /// <param name="sourceDocPath">The source doc path.</param>
        /// <param name="targetFilePath">The target file path.</param>
        /// <param name="targetFormat">The target format.</param>
        /// <returns></returns>
        private static bool PerformConversion(string sourceDocPath, string targetFilePath, WdExportFormat targetFormat)
        {
            if (!System.IO.File.Exists(sourceDocPath))
                throw new Exception("The specified source document does not exist.");

            Application wordApplication = new Application();
            Document wordDocument = null;

            bool success = false;
            object paramSourceDocPath = sourceDocPath;
            object paramMissing = Type.Missing;
            bool paramOpenAfterExport = false;
            WdExportOptimizeFor paramExportOptimizeFor = WdExportOptimizeFor.wdExportOptimizeForOnScreen;
            WdExportRange paramExportRange = WdExportRange.wdExportAllDocument;
            int paramStartPage = 0;
            int paramEndPage = 0;
            WdExportItem paramExportItem = WdExportItem.wdExportDocumentContent;
            bool paramIncludeDocProps = true;
            bool paramKeepIRM = true;
            WdExportCreateBookmarks paramCreateBookmarks = WdExportCreateBookmarks.wdExportCreateWordBookmarks;
            bool paramDocStructureTags = true;
            bool paramBitmapMissingFonts = true;
            bool paramUseISO19005_1 = false;

            try
            {
                wordDocument = wordApplication.Documents.Open(ref paramSourceDocPath, ref paramMissing, ref paramMissing, ref paramMissing,
                    ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing,
                    ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing, ref paramMissing);

                if (wordDocument != null)
                {
                    wordDocument.ExportAsFixedFormat(targetFilePath, targetFormat, paramOpenAfterExport, paramExportOptimizeFor,
                        paramExportRange, paramStartPage, paramEndPage, paramExportItem, paramIncludeDocProps, paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
                        paramBitmapMissingFonts, paramUseISO19005_1, ref paramMissing);

                    success = true;
                }
            }
            catch (Exception e)
            {
                throw e;
            }
            finally
            {
                if (wordDocument != null)
                {
                    wordDocument.Close(ref paramMissing, ref paramMissing, ref paramMissing);
                    wordDocument = null;
                }

                if (wordApplication != null)
                {
                    wordApplication.Quit(ref paramMissing, ref paramMissing, ref paramMissing);
                    wordApplication = null;
                }

                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }

            return success;
        }
    }
}

 

Creative Commons License
This work is licensed under a Creative Commons Attribution 3.0 Unported License.

 

Bookmark and Share dotnetshoutout
Tags: ,
Categories: Microsoft .NET

Permalink E-mail | Kick it! | DZone it! | del.icio.us Comments (0) Post RSSRSS comment feed

Comments