Example #1
0
        /// <summary>
        /// 保存为PDF格式
        /// </summary>
        /// <param name="FileName"></param>
        public string SavePDF(string filePath)
        {
            bool paramOpenAfterExport = false;
            WdExportOptimizeFor paramExportOptimizeFor = WdExportOptimizeFor.wdExportOptimizeForPrint;
            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;

            _doc.ExportAsFixedFormat("abc.pdf",
                                     WdExportFormat.wdExportFormatPDF,
                                     paramOpenAfterExport,
                                     paramExportOptimizeFor, paramExportRange, paramStartPage,
                                     paramEndPage, paramExportItem, paramIncludeDocProps,
                                     paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
                                     paramBitmapMissingFonts, paramUseISO19005_1,
                                     ref _nullobj);

            return(filePath);
        }
Example #2
0
 public void ExportAsFixedFormat(string OutputFileName, WdExportFormat ExportFormat, bool OpenAfterExport,
     WdExportOptimizeFor OptimizeFor, WdExportRange Range, int From,
     int To, WdExportItem Item, bool IncludeDocProps, bool KeepIRM,
     WdExportCreateBookmarks CreateBookmarks, bool DocStructureTags,
     bool BitmapMissingFonts, bool UseISO19005_1, ref object FixedFormatExtClassPtr)
 {
     throw new System.NotImplementedException();
 }
Example #3
0
        protected override bool doConvertToPdf(string saveAsFile)
        {
            WdExportFormat      wdExportFormat = WdExportFormat.wdExportFormatPDF;
            _Document           arg_20_0       = this.WordDoc;
            WdExportFormat      arg_20_2       = wdExportFormat;
            bool                arg_20_3       = false;
            WdExportOptimizeFor arg_20_4       = WdExportOptimizeFor.wdExportOptimizeForPrint;
            WdExportRange       arg_20_5       = WdExportRange.wdExportAllDocument;
            int                     arg_20_6   = 1;
            int                     arg_20_7   = 1;
            WdExportItem            arg_20_8   = WdExportItem.wdExportDocumentContent;
            bool                    arg_20_9   = false;
            bool                    arg_20_10  = true;
            WdExportCreateBookmarks arg_20_11  = WdExportCreateBookmarks.wdExportCreateNoBookmarks;
            bool                    arg_20_12  = true;
            bool                    arg_20_13  = true;
            bool                    arg_20_14  = false;
            object                  value      = System.Reflection.Missing.Value;

            arg_20_0.ExportAsFixedFormat(saveAsFile, arg_20_2, arg_20_3, arg_20_4, arg_20_5, arg_20_6, arg_20_7, arg_20_8, arg_20_9, arg_20_10, arg_20_11, arg_20_12, arg_20_13, arg_20_14, ref value);
            return(true);
        }
Example #4
0
        public static void ExportPdf(this Document doc, string fpath, bool open = true)
        {
            if (doc == null)
            {
                return;
            }
            const WdExportFormat      paramExportFormat        = WdExportFormat.wdExportFormatPDF;
            const WdExportOptimizeFor paramExportOptimizeFor   = WdExportOptimizeFor.wdExportOptimizeForPrint;
            const WdExportRange       paramExportRange         = WdExportRange.wdExportAllDocument;
            const int                     paramStartPage       = 0;
            const int                     paramEndPage         = 0;
            const WdExportItem            paramExportItem      = WdExportItem.wdExportDocumentContent;
            const WdExportCreateBookmarks paramCreateBookmarks = WdExportCreateBookmarks.wdExportCreateWordBookmarks;
            var paramMissing = Type.Missing;

            doc.ExportAsFixedFormat(fpath,
                                    paramExportFormat, open,
                                    paramExportOptimizeFor, paramExportRange, paramStartPage,
                                    paramEndPage, paramExportItem, true,
                                    true, paramCreateBookmarks, true,
                                    true, false,
                                    ref paramMissing);
        }
Example #5
0
        public PDF(Document skabelon, string FilePDF)
        {
            object              paramMissing           = Type.Missing;
            WdExportFormat      paramExportFormat      = WdExportFormat.wdExportFormatPDF;
            bool                paramOpenAfterExport   = false;
            WdExportOptimizeFor paramExportOptimizeFor =
                WdExportOptimizeFor.wdExportOptimizeForPrint;
            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;

            skabelon.ExportAsFixedFormat(FilePDF, paramExportFormat, paramOpenAfterExport, paramExportOptimizeFor, paramExportRange,
                                         paramStartPage, paramEndPage, paramExportItem, paramIncludeDocProps, paramKeepIRM, paramCreateBookmarks,
                                         paramDocStructureTags, paramBitmapMissingFonts, paramUseISO19005_1, ref paramMissing);
        }
Example #6
0
        static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.Out.WriteLine("Incorrect number opf parameters.  Expected: <source> <result>, was " + args.Length);
                return;
            }

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

            object paramSourceDocPath  = Path.GetFullPath(args[0]);
            string paramExportFilePath = Path.GetFullPath(args[1]);

            WdExportFormat      paramExportFormat      = WdExportFormat.wdExportFormatPDF;
            bool                paramOpenAfterExport   = false;
            WdExportOptimizeFor paramExportOptimizeFor = WdExportOptimizeFor.wdExportOptimizeForPrint;
            WdExportRange       paramExportRange       = WdExportRange.wdExportAllDocument;

            int paramStartPage = 0;
            int paramEndPage   = 0;

            WdExportItem paramExportItem = WdExportItem.wdExportDocumentContent;

            bool paramIncudeDocProps = true;
            bool paramKeepIRM        = true;
            WdExportCreateBookmarks paramCreateBookmarks = WdExportCreateBookmarks.wdExportCreateWordBookmarks;

            bool paramDocStructureTags   = true;
            bool paramBitmapMissingFonts = true;
            bool paramUseISO19005_1      = false;

            object paramMissing = Type.Missing;

            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(paramExportFilePath, paramExportFormat,
                                                     paramOpenAfterExport, paramExportOptimizeFor, paramExportRange,
                                                     paramStartPage, paramEndPage, paramExportItem, paramIncudeDocProps,
                                                     paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
                                                     paramBitmapMissingFonts, paramUseISO19005_1, ref paramMissing);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("The Error recieved is {0}: ", ex.Message);
            }
            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();
            }
        }
Example #7
0
        private static bool ConvertWordToFixed(List <string> files, WdExportFormat fixedFormatType)
        {
            Microsoft.Office.Interop.Word.Application wordApplication;
            try
            {
                wordApplication = new Microsoft.Office.Interop.Word.Application();
            }
            catch (Exception ex)
            {
                return(false);
            }

            Document            wordDocument           = null;
            object              paramMissing           = Type.Missing;
            WdExportFormat      paramExportFormat      = fixedFormatType;
            bool                paramOpenAfterExport   = false;
            WdExportOptimizeFor paramExportOptimizeFor =
                WdExportOptimizeFor.wdExportOptimizeForPrint;
            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;
            string targetExt = fixedFormatType == WdExportFormat.wdExportFormatPDF ? ".pdf" : ".xps";

            foreach (string file in files)
            {
                object paramSourceDocPath  = file;
                string paramExportFilePath = file.Substring(0, file.LastIndexOf('.')) + targetExt;
                try
                {
                    // Open the source document.
                    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);*/

                    // Export it in the specified format.
                    if (wordDocument != null)
                    {
                        wordDocument.ExportAsFixedFormat(paramExportFilePath,
                                                         paramExportFormat, paramOpenAfterExport,
                                                         paramExportOptimizeFor, paramExportRange, paramStartPage,
                                                         paramEndPage, paramExportItem, paramIncludeDocProps,
                                                         paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
                                                         paramBitmapMissingFonts, paramUseISO19005_1,
                                                         ref paramMissing);
                    }
                }
                catch (Exception ex)
                {
                    return(false);
                }
                finally
                {
                    // Close and release the Document object.
                    if (wordDocument != null)
                    {
                        wordDocument.Close(Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges, ref paramMissing, ref paramMissing);
                        //wordDocument.Close(ref paramMissing, ref paramMissing, ref paramMissing);
                        wordDocument = null;
                    }
                }
            }
            // Quit Word and release the ApplicationClass object.
            if (wordApplication != null)
            {
                wordApplication.Quit(ref paramMissing, ref paramMissing,
                                     ref paramMissing);
                wordApplication = null;
            }

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();
            return(true);
        }
Example #8
0
        /// <summary>
        /// Word转换成PDF(批量文件转换推荐使用)
        /// </summary>
        /// <param name="inputPath">文件完整路径</param>
        /// <param name="outputPath">保存路径</param>
        public static int WordsToPDFs(string[] inputPaths, string outputPath)
        {
            int count = 0;

            #region 初始化
            //初始化一个application
            Application wordApplication = new Application();
            //初始化一个document
            Document wordDocument = null;
            #endregion

            //默认值
            object paramMissing = Type.Missing;

            for (int i = 0; i < inputPaths.Length; i++)
            {
                #region 参数设置~~我去累死宝宝了~~(所谓的参数都是根据这个方法来的:ExportAsFixedFormat)
                //word路径
                object wordPath = Path.GetFullPath(inputPaths[i]);

                //获取文件名
                string outputName = Path.GetFileNameWithoutExtension(inputPaths[i]);

                //输出路径
                string pdfPath = Path.GetFullPath(outputPath + @"\" + outputName + ".pdf");

                //导出格式为PDF
                WdExportFormat wdExportFormat = WdExportFormat.wdExportFormatPDF;

                //导出大文件
                WdExportOptimizeFor wdExportOptimizeFor = WdExportOptimizeFor.wdExportOptimizeForPrint;

                //导出整个文档
                WdExportRange wdExportRange = WdExportRange.wdExportAllDocument;

                //开始页码
                int startIndex = 0;

                //结束页码
                int endIndex = 0;

                //导出不带标记的文档(这个可以改)
                WdExportItem wdExportItem = WdExportItem.wdExportDocumentContent;

                //包含word属性
                bool includeDocProps = true;

                //导出书签
                WdExportCreateBookmarks paramCreateBookmarks = WdExportCreateBookmarks.wdExportCreateWordBookmarks;

                #endregion

                #region 转换
                try
                {
                    //打开word
                    wordDocument = wordApplication.Documents.Open(ref wordPath, 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(pdfPath, wdExportFormat, false, wdExportOptimizeFor, wdExportRange, startIndex, endIndex, wdExportItem, includeDocProps, true, paramCreateBookmarks, true, true, false, ref paramMissing);
                    }
                    count++;
                }
                catch (Exception ex)
                {
                }
                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;
            }
            return(count);

            #endregion
        }
Example #9
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="srcFilePath"></param>
        /// <param name="destFileDir"></param>
        /// <param name="pdfName"></param>
        /// <returns></returns>
        private bool ConvertWord2PDF(string srcFilePath, string destFileDir, string destFileName)
        {
            bool result;

            // validate path
            ValidateHelper.Begin().NotNullAndEmpty(srcFilePath).FileExist(srcFilePath).NotNullAndEmpty(destFileDir).NotNullAndEmpty(destFileName);

            if (!Directory.Exists(destFileDir))
            {
                Directory.CreateDirectory(destFileDir);
            }
            if (Path.GetExtension(destFileName).ToLower() != ".pdf")
            {
                destFileName = destFileName + ".pdf";
            }

            try
            {
                object paramSourceDocPath  = srcFilePath;
                object paramMissing        = Type.Missing;
                string paramExportFilePath = Path.Combine(destFileDir, destFileName);

                // create a word application object
                ApplicationClass wordApplication = new ApplicationClass();
                Microsoft.Office.Interop.Word.Document wordDocument = null;

                //set exportformat to pdf
                WdExportFormat      paramExportFormat           = WdExportFormat.wdExportFormatPDF;
                bool                paramOpenAfterExport        = false;
                WdExportOptimizeFor paramExportOptimizeFor      = WdExportOptimizeFor.wdExportOptimizeForPrint;
                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
                {
                    // Open the source document.
                    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);

                    // Export it in the specified format.
                    if (wordDocument != null)
                    {
                        wordDocument.ExportAsFixedFormat(paramExportFilePath,
                                                         paramExportFormat, paramOpenAfterExport,
                                                         paramExportOptimizeFor, paramExportRange, paramStartPage,
                                                         paramEndPage, paramExportItem, paramIncludeDocProps,
                                                         paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
                                                         paramBitmapMissingFonts, paramUseISO19005_1,
                                                         ref paramMissing);
                    }

                    result = true;
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    // Close and release the Document object.
                    if (wordDocument != null)
                    {
                        wordDocument.Close(ref paramMissing, ref paramMissing, ref paramMissing);
                        wordDocument = null;
                    }

                    // Quit Word and release the ApplicationClass object.
                    if (wordApplication != null)
                    {
                        wordApplication.Quit(ref paramMissing, ref paramMissing, ref paramMissing);
                        wordApplication = null;
                    }

                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(result);
        }
Example #10
0
        /// <summary>
        /// word转换PDF
        /// </summary>
        /// <param name="wordfile">word文件路径<</param>
        /// <param name="newPdfFile">pdf文件路径</param>
        /// <param name="errorMsg">转换失败后的详细信息</param>
        /// <returns></returns>
        public static bool WordConvertPdf(string wordfile, string newPdfFile, out string errorMsg)
        {
            WdExportFormat exportFormat = WdExportFormat.wdExportFormatPDF;
            object         paramMissing = Type.Missing;

            Microsoft.Office.Interop.Word.Application wordApplication = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word._Document   wordDocument    = null;
            try
            {
                object              paramSourceDocPath          = wordfile;
                string              paramExportFilePath         = newPdfFile;
                WdExportFormat      paramExportFormat           = exportFormat;
                bool                paramOpenAfterExport        = false;
                WdExportOptimizeFor paramExportOptimizeFor      = WdExportOptimizeFor.wdExportOptimizeForPrint;
                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;
                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(paramExportFilePath, paramExportFormat,
                                                     paramOpenAfterExport, paramExportOptimizeFor, paramExportRange, paramStartPage,
                                                     paramEndPage, paramExportItem, paramIncludeDocProps, paramKeepIRM, paramCreateBookmarks,
                                                     paramDocStructureTags, paramBitmapMissingFonts, paramUseISO19005_1, ref paramMissing);
                }
                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();

                errorMsg = string.Empty;
                return(true);
            }
            catch (Exception ex)
            {
                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();
                errorMsg = ex.Message;
                return(false);
            }
        }
Example #11
0
        public static void ConvertDocxToPdf(String filename)
        {
            String sourcePath = filename;
            String destPath   = filename.Replace(".docx", ".pdf");

            //Change the path of the .docx file and filename to your file name.
            object paramSourceDocPath = sourcePath;
            object paramMissing       = Type.Missing;

            Microsoft.Office.Interop.Word._Application wordApplication = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word._Document    wordDocument    = null;

            //Change the path of the .pdf file and filename to your file name.
            string              paramExportFilePath    = destPath;
            WdExportFormat      paramExportFormat      = WdExportFormat.wdExportFormatPDF;
            bool                paramOpenAfterExport   = false;
            WdExportOptimizeFor paramExportOptimizeFor =
                WdExportOptimizeFor.wdExportOptimizeForPrint;
            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
            {
                // Open the source document.
                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);

                // Export it in the specified format.
                if (wordDocument != null)
                {
                    wordDocument.ExportAsFixedFormat(paramExportFilePath,
                                                     paramExportFormat, paramOpenAfterExport,
                                                     paramExportOptimizeFor, paramExportRange, paramStartPage,
                                                     paramEndPage, paramExportItem, paramIncludeDocProps,
                                                     paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
                                                     paramBitmapMissingFonts, paramUseISO19005_1,
                                                     ref paramMissing);
                }
            }
            catch (Exception ex)
            {
                // Respond to the error
                Console.WriteLine(ex.Message);
            }
            finally
            {
                // Close and release the Document object.
                if (wordDocument != null)
                {
                    wordDocument.Close(ref paramMissing, ref paramMissing, ref paramMissing);
                    wordDocument = null;
                }

                // Quit Word and release the ApplicationClass object.
                if (wordApplication != null)
                {
                    wordApplication.Quit(ref paramMissing, ref paramMissing, ref paramMissing);
                    wordApplication = null;
                }

                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
        private static void ExportToPdf(string fullRtfFileName, string fullPdfFileName)
        {
            Microsoft.Office.Interop.Word.Application wordApplication = new Application();
            Document wordDocument = null;

            object paramSourceDocPath = fullRtfFileName;
            object paramMissing       = Type.Missing;

            string              paramExportFilePath    = fullPdfFileName;
            WdExportFormat      paramExportFormat      = WdExportFormat.wdExportFormatPDF;
            bool                paramOpenAfterExport   = false;
            WdExportOptimizeFor paramExportOptimizeFor =
                WdExportOptimizeFor.wdExportOptimizeForPrint;
            WdExportRange           paramExportRange     = WdExportRange.wdExportAllDocument;
            int                     paramStartPage       = 0;
            int                     paramEndPage         = 0;
            WdExportItem            paramExportItem      = WdExportItem.wdExportDocumentContent;
            bool                    paramIncludeDocProps = true;
            bool                    paramKeepIRM         = true;
            WdExportCreateBookmarks paramCreateBookmarks =
                WdExportCreateBookmarks.wdExportCreateNoBookmarks; //wdExportCreateWordBookmarks;
            bool paramDocStructureTags   = true;
            bool paramBitmapMissingFonts = true;
            bool paramUseISO19005_1      = false;

            try
            {
                /*
                 *
                 * docs.Open(
                 *           COleVariant("C:\\Test.doc",VT_BSTR),
                 *           covFalse,    // Confirm Conversion.
                 *           covFalse,    // ReadOnly.
                 *           covFalse,    // AddToRecentFiles.
                 *           covOptional, // PasswordDocument.
                 *           covOptional, // PasswordTemplate.
                 *           covFalse,    // Revert.
                 *           covOptional, // WritePasswordDocument.
                 *           covOptional, // WritePasswordTemplate.
                 *           covOptional) // Format. // Last argument for Word 97
                 *              covOptional, // Encoding // New for Word 2000/2002
                 *              covTrue,     // Visible
                 *              covOptional, // OpenConflictDocument
                 *              covOptional, // OpenAndRepair
                 *              (long)0,     // DocumentDirection wdDocumentDirection LeftToRight
                 *              covOptional  // NoEncodingDialog
                 *              )  // Close Open parameters
                 */
                // Open the source document.
                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);

                // Export it in the specified format.
                if (wordDocument != null)
                {
                    wordDocument.ExportAsFixedFormat(paramExportFilePath,
                                                     paramExportFormat, paramOpenAfterExport,
                                                     paramExportOptimizeFor, paramExportRange, paramStartPage,
                                                     paramEndPage, paramExportItem, paramIncludeDocProps,
                                                     paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
                                                     paramBitmapMissingFonts, paramUseISO19005_1,
                                                     ref paramMissing);
                }
            }
            catch (Exception ex)
            {
                // Respond to the error
                string msg = ex.Message;
            }
            finally
            {
                // Close and release the Document object.
                if (wordDocument != null)
                {
                    wordDocument.Close(ref paramMissing, ref paramMissing,
                                       ref paramMissing);
                    wordDocument = null;
                }

                // Quit Word and release the ApplicationClass object.
                if (wordApplication != null)
                {
                    wordApplication.Quit(ref paramMissing, ref paramMissing,
                                         ref paramMissing);
                    wordApplication = null;
                }

                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
Example #13
0
        public bool convert(string source, string output)
        {
            if (System.IO.File.Exists(source))
            {
                //start conversion
                try
                {
                    ApplicationClass wordApplication = new ApplicationClass();

                    Document wordDocument       = null;
                    object   paramSourceDocPath = source;

                    string paramExportFilePath = output;

                    //this part is copied from Microsoft MSDN

                    //set exportformat to pdf
                    WdExportFormat      paramExportFormat      = WdExportFormat.wdExportFormatPDF;
                    bool                paramOpenAfterExport   = false;
                    WdExportOptimizeFor paramExportOptimizeFor =
                        WdExportOptimizeFor.wdExportOptimizeForPrint;
                    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
                    {
                        // Open the source document.
                        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);

                        // Export it in the specified format.
                        if (wordDocument != null)
                        {
                            wordDocument.ExportAsFixedFormat(paramExportFilePath,
                                                             paramExportFormat, paramOpenAfterExport,
                                                             paramExportOptimizeFor, paramExportRange, paramStartPage,
                                                             paramEndPage, paramExportItem, paramIncludeDocProps,
                                                             paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
                                                             paramBitmapMissingFonts, paramUseISO19005_1,
                                                             ref paramMissing);
                        }
                    }
                    catch (Exception ex)
                    {
                        // Respond to the error
                        errormessage = ex.Message;
                    }
                    finally
                    {
                        // Close and release the Document object.
                        if (wordDocument != null)
                        {
                            wordDocument.Close(ref paramMissing, ref paramMissing,
                                               ref paramMissing);
                            wordDocument = null;
                        }

                        // Quit Word and release the ApplicationClass object.
                        if (wordApplication != null)
                        {
                            wordApplication.Quit(ref paramMissing, ref paramMissing,
                                                 ref paramMissing);
                            wordApplication = null;
                        }

                        //i don't know why this is here two times. I just copied it from the MSDN howto interop with word 2007
                        GC.Collect();
                        GC.WaitForPendingFinalizers();
                        GC.Collect();
                        GC.WaitForPendingFinalizers();
                    }
                }
                catch (Exception err)
                {
                    errormessage = err.Message;
                }
                return(true);
            }
            else
            {
                errormessage = "ERROR: Inputfile not found";
            }

            return(false);
        }
Example #14
0
        public int Convert(string sourcePath, string targetPath)
        {
            if (!File.Exists(sourcePath))
            {
                return(ErrorMessages.FileNotExist);
            }

            ApplicationClass wordApplication = new ApplicationClass();
            Document         wordDocument    = null;
            object           paramMissing    = Type.Missing;
            Type             wordType        = wordApplication.GetType();

            try
            {
                object paramSourceDocPath  = sourcePath;
                string paramExportFilePath = targetPath;

                //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);


                Documents docs     = wordApplication.Documents;
                Type      docsType = docs.GetType();
                wordDocument = (Document)docsType.InvokeMember("Open", System.Reflection.BindingFlags.InvokeMethod, null, docs, new Object[] { sourcePath, true, true });

                if (wordDocument != null)
                {
                    WdExportFormat      paramExportFormat           = WdExportFormat.wdExportFormatPDF;
                    bool                paramOpenAfterExport        = false;
                    WdExportOptimizeFor paramExportOptimizeFor      = WdExportOptimizeFor.wdExportOptimizeForPrint;
                    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;

                    wordDocument.ExportAsFixedFormat(paramExportFilePath,
                                                     paramExportFormat, paramOpenAfterExport,
                                                     paramExportOptimizeFor, paramExportRange, paramStartPage,
                                                     paramEndPage, paramExportItem, paramIncludeDocProps,
                                                     paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
                                                     paramBitmapMissingFonts, paramUseISO19005_1,
                                                     ref paramMissing);
                }
                return(ErrorMessages.ConvertSuccess);
            }
            catch (COMException ex)
            {
                _logger.Error(ex.StackTrace);
                _logger.Error(ex.Message);
                return(ErrorMessages.OfficeToPdfUninstall);
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);
                return(ErrorMessages.ConvertFailed);
            }
            finally
            {
                if (wordDocument != null)
                {
                    wordDocument.Close(ref paramMissing, ref paramMissing, ref paramMissing);
                }
                wordType.InvokeMember("Quit", System.Reflection.BindingFlags.InvokeMethod, null, wordApplication, null);
                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
Example #15
0
        private void DocxToPdf(String sourcePath, String destPath)
        {
            //Change the path of the .docx file and filename to your file name.

            object paramSourceDocPath = sourcePath;
            object paramMissing       = Type.Missing;

            toolStripStatusLabel1.Text = "Starting Word...";
            var      wordApplication = new Microsoft.Office.Interop.Word.Application();
            Document wordDocument    = null;

            //Change the path of the .pdf file and filename to your file name.

            string              paramExportFilePath    = destPath;
            WdExportFormat      paramExportFormat      = WdExportFormat.wdExportFormatPDF;
            bool                paramOpenAfterExport   = false;
            WdExportOptimizeFor paramExportOptimizeFor =
                WdExportOptimizeFor.wdExportOptimizeForPrint;
            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
            {
                toolStripStatusLabel1.Text = "Opening Word document...";
                // Open the source document.
                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);

                // Export it in the specified format.
                if (wordDocument != null)
                {
                    toolStripStatusLabel1.Text = "Hiding headers...";

                    wordDocument.Styles["_header"].Font.Color = WdColor.wdColorWhite;

                    foreach (HeaderFooter hf in wordDocument.Sections[1].Headers)
                    {
                        if (hf.IsHeader)
                        {
                            foreach (Range r in hf.Range.Sentences)
                            {
                                if (r.Text.IndexOf("Do Not Delete") >= 0)
                                {
                                    r.Select();
                                    wordApplication.Selection.ClearCharacterDirectFormatting();
                                }
                            }
                        }
                    }

                    toolStripStatusLabel1.Text = "Exporting to PDF...";
                    wordDocument.ExportAsFixedFormat(paramExportFilePath,
                                                     paramExportFormat, paramOpenAfterExport,
                                                     paramExportOptimizeFor, paramExportRange, paramStartPage,
                                                     paramEndPage, paramExportItem, paramIncludeDocProps,
                                                     paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
                                                     paramBitmapMissingFonts, paramUseISO19005_1,
                                                     ref paramMissing);

                    toolStripStatusLabel1.Text = "Done!";
                }
            }
            catch (Exception ex)
            {
                // Respond to the error
                System.Windows.Forms.MessageBox.Show(ex.Message);
                toolStripStatusLabel1.Text = "An error occurred.";
            }
            finally
            {
                // Close and release the Document object.
                if (wordDocument != null)
                {
                    wordDocument.Close(ref paramMissing, ref paramMissing,
                                       ref paramMissing);
                    wordDocument = null;
                }

                // Quit Word and release the ApplicationClass object.
                if (wordApplication != null)
                {
                    wordApplication.Quit(ref paramMissing, ref paramMissing,
                                         ref paramMissing);
                    wordApplication = null;
                }

                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
Example #16
0
        public static void WordToPDF(string docPath)
        {
            Application wordApplication = new Application();
            Document    wordDocument    = null;

            // Get full path of input and output files.
            object paramSourceDocPath  = docPath;
            string paramExportFilePath = Path.GetFullPath("..\\..") + "\\File\\平台借款合同.pdf";

            ///////////////////////////////////////////////
            /// STATIC CONFIGURATION PARAMETERS
            //////////////////////////////////////////////

            WdExportFormat      paramExportFormat      = WdExportFormat.wdExportFormatPDF;
            bool                paramOpenAfterExport   = false;
            WdExportOptimizeFor paramExportOptimizeFor =
                WdExportOptimizeFor.wdExportOptimizeForPrint;
            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;

            object paramMissing = Type.Missing;

            try
            {
                // Open the source document.
                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);

                // Export it in the specified format.
                if (wordDocument != null)
                {
                    wordDocument.ExportAsFixedFormat(paramExportFilePath,
                                                     paramExportFormat, paramOpenAfterExport,
                                                     paramExportOptimizeFor, paramExportRange, paramStartPage,
                                                     paramEndPage, paramExportItem, paramIncludeDocProps,
                                                     paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
                                                     paramBitmapMissingFonts, paramUseISO19005_1,
                                                     ref paramMissing);
                }
            }
            catch (Exception ex)
            {
                System.Console.Out.WriteLine(ex);
            }
            finally
            {
                // Close and release the Document object.
                if (wordDocument != null)
                {
                    wordDocument.Close(ref paramMissing, ref paramMissing,
                                       ref paramMissing);
                    wordDocument = null;
                }

                // Quit Word and release the ApplicationClass object.
                if (wordApplication != null)
                {
                    wordApplication.Quit(ref paramMissing, ref paramMissing,
                                         ref paramMissing);
                    wordApplication = null;
                }

                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
Example #17
0
        /// <summary>
        /// WORD文档转换PDF格式文件
        /// 创建人:张活生
        /// 创建时间:2015年12月10日10:20:37
        /// </summary>
        /// <param name="sourcePath">源文件路径</param>
        /// <param name="targetPath">目标文件路径</param>
        /// <returns>true:转换成功;false:转换失败</returns>
        public static bool DocConvertToPdf(string sourcePath, string targetPath)
        {
            bool             result          = false;
            WdExportFormat   exportFormat    = WdExportFormat.wdExportFormatPDF;
            object           paramMissing    = Type.Missing;
            ApplicationClass wordApplication = new ApplicationClass();
            Document         wordDocument    = null;

            try
            {
                object paramSourceDocPath  = sourcePath;
                string paramExportFilePath = targetPath;

                WdExportFormat      paramExportFormat           = exportFormat;
                bool                paramOpenAfterExport        = false;
                WdExportOptimizeFor paramExportOptimizeFor      = WdExportOptimizeFor.wdExportOptimizeForPrint;
                WdExportRange       paramExportRange            = WdExportRange.wdExportAllDocument;
                int                     paramStartPage          = 0;
                int                     paramEndPage            = 0;
                WdExportItem            paramExportItem         = WdExportItem.wdExportDocumentContent;
                bool                    paramIncludeDocProps    = true;
                bool                    paramKeepIRM            = true;
                WdExportCreateBookmarks paramCreateBookmarks    = Microsoft.Office.Interop.Word.WdExportCreateBookmarks.wdExportCreateWordBookmarks;
                bool                    paramDocStructureTags   = true;
                bool                    paramBitmapMissingFonts = true;
                bool                    paramUseISO19005_1      = false;

                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(paramExportFilePath,
                                                     paramExportFormat, paramOpenAfterExport,
                                                     paramExportOptimizeFor, paramExportRange, paramStartPage,
                                                     paramEndPage, paramExportItem, paramIncludeDocProps,
                                                     paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
                                                     paramBitmapMissingFonts, paramUseISO19005_1,
                                                     ref paramMissing);
                }
                result = true;
            }
            catch
            {
                result = false;
            }
            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(result);
        }
Example #18
0
        /// <summary>
        /// Take a MS Word file, and output a corresponding PDF>
        /// </summary>
        /// <param name="args">[0]: Path to the file to be converted; [1]: Path to the output file</param>
        static void Main(string[] args)
        {
            if (args.Length != 2)
            {
                Console.Out.WriteLine("Incorrect number of parameters. Expected: <source> <result>, was " + args.Length);
                return;
            }

            // Initialize Word interop references.
            Application wordApplication = new Application();
            Document    wordDocument    = null;

            // Get full path of input and output files.
            object paramSourceDocPath  = Path.GetFullPath(args[0]);
            string paramExportFilePath = Path.GetFullPath(args[1]);

            ///////////////////////////////////////////////
            /// STATIC CONFIGURATION PARAMETERS
            //////////////////////////////////////////////

            WdExportFormat      paramExportFormat      = WdExportFormat.wdExportFormatPDF;
            bool                paramOpenAfterExport   = false;
            WdExportOptimizeFor paramExportOptimizeFor =
                WdExportOptimizeFor.wdExportOptimizeForPrint;
            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;

            object paramMissing = Type.Missing;

            ///////////////////////////////////////////////
            /// CONVERSION
            //////////////////////////////////////////////

            try
            {
                // Open the source document.
                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);

                // Export it in the specified format.
                if (wordDocument != null)
                {
                    wordDocument.ExportAsFixedFormat(paramExportFilePath,
                                                     paramExportFormat, paramOpenAfterExport,
                                                     paramExportOptimizeFor, paramExportRange, paramStartPage,
                                                     paramEndPage, paramExportItem, paramIncludeDocProps,
                                                     paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
                                                     paramBitmapMissingFonts, paramUseISO19005_1,
                                                     ref paramMissing);
                }
            }
            catch (Exception ex)
            {
                Console.Out.WriteLine(ex);
            }
            finally
            {
                // Close and release the Document object.
                if (wordDocument != null)
                {
                    wordDocument.Close(ref paramMissing, ref paramMissing,
                                       ref paramMissing);
                    wordDocument = null;
                }

                // Quit Word and release the ApplicationClass object.
                if (wordApplication != null)
                {
                    wordApplication.Quit(ref paramMissing, ref paramMissing,
                                         ref paramMissing);
                    wordApplication = null;
                }

                GC.Collect();
                GC.WaitForPendingFinalizers();
                GC.Collect();
                GC.WaitForPendingFinalizers();
            }
        }
Example #19
0
        /// <summary>
        /// Word转换成PDF(单个文件转换推荐使用)
        /// </summary>
        /// <param name="inputPath">载入完整路径</param>
        /// <param name="outputPath">保存完整路径</param>
        /// <param name="startPage">初始页码(默认为第一页[0])</param>
        /// <param name="endPage">结束页码(默认为最后一页)</param>
        public static bool WordToPDF(string inputPath, string outputPath, int startPage = 0, int endPage = 0)
        {
            bool b = true;

            #region 初始化
            //初始化一个application
            Application wordApplication = new Application();
            //初始化一个document
            Document wordDocument = null;
            #endregion

            #region 参数设置~~我去累死宝宝了~~(所谓的参数都是根据这个方法来的:ExportAsFixedFormat)
            //word路径
            object wordPath = Path.GetFullPath(inputPath);

            //输出路径
            string pdfPath = Path.GetFullPath(outputPath);

            //导出格式为PDF
            WdExportFormat wdExportFormat = WdExportFormat.wdExportFormatPDF;

            //导出大文件
            WdExportOptimizeFor wdExportOptimizeFor = WdExportOptimizeFor.wdExportOptimizeForPrint;

            //导出整个文档
            WdExportRange wdExportRange = WdExportRange.wdExportAllDocument;

            //开始页码
            int startIndex = startPage;

            //结束页码
            int endIndex = endPage;

            //导出不带标记的文档(这个可以改)
            WdExportItem wdExportItem = WdExportItem.wdExportDocumentContent;

            //包含word属性
            bool includeDocProps = true;

            //导出书签
            WdExportCreateBookmarks paramCreateBookmarks = WdExportCreateBookmarks.wdExportCreateWordBookmarks;

            //默认值
            object paramMissing = Type.Missing;

            #endregion

            #region 转换
            try
            {
                //打开word
                wordDocument = wordApplication.Documents.Open(ref wordPath, 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(pdfPath, wdExportFormat, false, wdExportOptimizeFor, wdExportRange, startIndex, endIndex, wdExportItem, includeDocProps, true, paramCreateBookmarks, true, true, false, ref paramMissing);
                }
            }
            catch (Exception ex)
            {
                b = false;
            }
            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;
                }
            }

            return(b);

            #endregion
        }
Example #20
0
        /// <summary>

        /// 把Word文件转换成pdf文件

        /// </summary>

        /// <param name="sourcePath">需要转换的文件路径和文件名称</param>

        /// <param name="targetPath">转换完成后的文件的路径和文件名名称</param>

        /// <returns>成功返回true,失败返回false</returns>
        public static bool WordToPdf(string sourcePath, string targetPath)
        {
            bool result = false;

            WdExportFormat wdExportFormatPDF = WdExportFormat.wdExportFormatPDF;//转换格式1.wdExportFormatPDF转换成pdf格式 2.wdExportFormatXPS转换成xps格式

            object missing = Type.Missing;

            Microsoft.Office.Interop.Word.ApplicationClass applicationClass = null;

            Document document = null;

            try
            {
                applicationClass = new Microsoft.Office.Interop.Word.ApplicationClass();

                object inputfileName = sourcePath;                                                                         //需要转格式的文件路径

                string outputFileName = targetPath;                                                                        //转换完成后PDF或XPS文件的路径和文件名名称

                WdExportFormat exportFormat = wdExportFormatPDF;                                                           //导出文件所使用的格式

                bool openAfterExport = false;                                                                              //转换完成后是否打开

                WdExportOptimizeFor wdExportOptimizeForPrint = WdExportOptimizeFor.wdExportOptimizeForPrint;               //导出方式1.wdExportOptimizeForPrint针对打印进行导出,质量较高,生成的文件大小较大。2.wdExportOptimizeForOnScreen 针对屏幕显示进行导出,质量较差,生成的文件大小较小。

                WdExportRange wdExportAllDocument = WdExportRange.wdExportAllDocument;                                     //导出全部内容(枚举)

                int from = 0;                                                                                              //起始页码

                int to = 0;                                                                                                //结束页码

                WdExportItem wdExportDocumentContent = WdExportItem.wdExportDocumentContent;                               //指定导出过程中是否只包含文本或包含文本的标记.1.wdExportDocumentContent:导出文件没有标记,2.导出文件有标记

                bool includeDocProps = true;                                                                               //指定是否包含新导出的文件在文档属性

                bool keepIRM = true;                                                                                       //

                WdExportCreateBookmarks wdExportCreateWordBookmarks = WdExportCreateBookmarks.wdExportCreateWordBookmarks; //1.wdExportCreateNoBookmarks:不要在导出文件中创建书签,2.wdExportCreateHeadingBookmarks:标题和文本框导出的文件中创建一个书签,3.wdExportCreateWordBookmarks每个字的书签,其中包括除包含页眉和页脚中的所有书签导出的文件中创建一个书签。

                bool docStructureTags = true;

                bool bitmapMissingFonts = true;

                bool UseISO19005_1 = false;//生成的文档是否符合 ISO 19005-1 (PDF/A)

                document = applicationClass.Documents.Open(ref inputfileName, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);

                if (document != null)
                {
                    document.ExportAsFixedFormat(outputFileName, exportFormat, openAfterExport, wdExportOptimizeForPrint, wdExportAllDocument, from, to, wdExportDocumentContent, includeDocProps, keepIRM, wdExportCreateWordBookmarks, docStructureTags, bitmapMissingFonts, UseISO19005_1, ref missing);
                }
                result = true;
            }
            catch
            {
                result = false;
            }
            finally
            {
                if (document != null)
                {
                    document.Close(ref missing, ref missing, ref missing);
                    document = null;
                }
                if (applicationClass != null)
                {
                    applicationClass.Quit(ref missing, ref missing, ref missing);
                    applicationClass = null;
                }
            }
            return(result);
        }
 public void ExportAsFixedFormat(string OutputFileName, WdExportFormat ExportFormat, bool OpenAfterExport,
     WdExportOptimizeFor OptimizeFor, WdExportRange Range, int From,
     int To, WdExportItem Item, bool IncludeDocProps, bool KeepIRM,
     WdExportCreateBookmarks CreateBookmarks, bool DocStructureTags,
     bool BitmapMissingFonts, bool UseISO19005_1, ref object FixedFormatExtClassPtr)
 {
     throw new System.NotImplementedException();
 }
        /// <summary>
        /// 将word转化成PDF
        /// </summary>
        /// <param name="sourcePath">word文件路径</param>
        /// <param name="targetPath"></param>
        /// <returns></returns>
        public static bool ConvertWord2Pdf(string sourcePath, string targetPath)
        {
            bool           result;
            WdExportFormat exportFormat    = WdExportFormat.wdExportFormatPDF;
            object         paramMissing    = Type.Missing;
            Application    wordApplication = new Application();
            Document       wordDocument    = null;

            try
            {
                object              paramSourceDocPath     = "E:/eContract" + sourcePath;
                string              paramExportFilePath    = "E:/eContract" + targetPath;
                WdExportFormat      paramExportFormat      = exportFormat;
                WdExportOptimizeFor paramExportOptimizeFor =
                    WdExportOptimizeFor.wdExportOptimizeForPrint;
                WdExportRange           paramExportRange     = WdExportRange.wdExportAllDocument;
                int                     paramStartPage       = 0;
                int                     paramEndPage         = 0;
                WdExportItem            paramExportItem      = WdExportItem.wdExportDocumentContent;
                WdExportCreateBookmarks paramCreateBookmarks =
                    WdExportCreateBookmarks.wdExportCreateWordBookmarks;

                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(paramExportFilePath,
                                                     paramExportFormat, false,
                                                     paramExportOptimizeFor, paramExportRange, paramStartPage,
                                                     paramEndPage, paramExportItem, true,
                                                     true, paramCreateBookmarks, true,
                                                     true, false,
                                                     ref paramMissing);
                }
                result = true;
            }
            catch (Exception ex)
            {
                //其他日志操作;
                return(false);
            }
            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();
            }
            return(result);
        }
Example #23
0
        public static void ConvertWord2PDF(string wordInputPath, string pdfOutputPath, string pdfName)
        {
            try
            {
                string pdfExtension = ".pdf";

                // validate patameter
                if (!Directory.Exists(pdfOutputPath))
                {
                    Directory.CreateDirectory(pdfOutputPath);
                }
                if (pdfName.Trim().Length == 0)
                {
                    pdfName = Path.GetFileNameWithoutExtension(wordInputPath);
                }
                if (!(Path.GetExtension(pdfName).ToUpper() == pdfExtension.ToUpper()))
                {
                    pdfName = pdfName + pdfExtension;
                }

                object paramSourceDocPath = wordInputPath;
                object paramMissing       = Type.Missing;

                string paramExportFilePath = Path.Combine(pdfOutputPath, pdfName);

                // create a word application object
                ApplicationClass wordApplication = new ApplicationClass();
                Microsoft.Office.Interop.Word.Document wordDocument = null;

                //set exportformat to pdf
                WdExportFormat      paramExportFormat           = WdExportFormat.wdExportFormatPDF;
                bool                paramOpenAfterExport        = false;
                WdExportOptimizeFor paramExportOptimizeFor      = WdExportOptimizeFor.wdExportOptimizeForPrint;
                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
                {
                    // Open the source document.
                    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);

                    // Export it in the specified format.
                    if (wordDocument != null)
                    {
                        wordDocument.ExportAsFixedFormat(paramExportFilePath,
                                                         paramExportFormat, paramOpenAfterExport,
                                                         paramExportOptimizeFor, paramExportRange, paramStartPage,
                                                         paramEndPage, paramExportItem, paramIncludeDocProps,
                                                         paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
                                                         paramBitmapMissingFonts, paramUseISO19005_1,
                                                         ref paramMissing);
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    // Close and release the Document object.
                    if (wordDocument != null)
                    {
                        wordDocument.Close(ref paramMissing, ref paramMissing, ref paramMissing);
                        wordDocument = null;
                    }

                    // Quit Word and release the ApplicationClass object.
                    if (wordApplication != null)
                    {
                        wordApplication.Quit(ref paramMissing, ref paramMissing, ref paramMissing);
                        wordApplication = null;
                    }

                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #24
0
        /// <summary>
        /// Convert a Word file to PDF
        /// </summary>
        /// <param name="inputFile">Full path of the input Word file</param>
        /// <param name="outputFile">Full path of the output PDF</param>
        /// <returns></returns>
        public static new int Convert(String inputFile, String outputFile, Hashtable options)
        {
            Boolean running = (Boolean)options["noquit"];

            Microsoft.Office.Interop.Word.Application word = null;
            object oMissing = System.Reflection.Missing.Value;

            Microsoft.Office.Interop.Word.Template tmpl;
            String           temporaryStorageDir = null;
            float            wordVersion         = 0;
            List <AppOption> wordOptionList      = new List <AppOption>();

            try
            {
                tmpl = null;
                try
                {
                    word = (Microsoft.Office.Interop.Word.Application)Marshal.GetActiveObject("Word.Application");
                }
                catch (System.Exception)
                {
                    word    = new Microsoft.Office.Interop.Word.Application();
                    running = false;
                }
                word.DisplayAlerts = WdAlertLevel.wdAlertsNone;
                // Issue #48 - we should allow control over whether the history is lost
                if (!(Boolean)options["word_keep_history"])
                {
                    word.DisplayRecentFiles = false;
                }
                word.DisplayDocumentInformationPanel = false;
                word.FeatureInstall = Microsoft.Office.Core.MsoFeatureInstall.msoFeatureInstallNone;
                wordVersion         = (float)System.Convert.ToDecimal(word.Version, new CultureInfo("en-US"));
                var wdOptions = word.Options;
                try
                {
                    // Set the Word options in a way that allows us to reset the options when we finish
                    wordOptionList.Add(new AppOption("AllowReadingMode", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("PrecisePositioning", true, ref wdOptions));
                    wordOptionList.Add(new AppOption("UpdateFieldsAtPrint", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("UpdateLinksAtPrint", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("WarnBeforeSavingPrintingSendingMarkup", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("BackgroundSave", true, ref wdOptions));
                    wordOptionList.Add(new AppOption("SavePropertiesPrompt", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("DoNotPromptForConvert", true, ref wdOptions));
                    wordOptionList.Add(new AppOption("PromptUpdateStyle", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("ConfirmConversions", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("CheckGrammarAsYouType", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("CheckGrammarWithSpelling", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("CheckSpellingAsYouType", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("DisplaySmartTagButtons", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("EnableLivePreview", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("ShowReadabilityStatistics", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("SuggestSpellingCorrections", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("AllowDragAndDrop", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("EnableMisusedWordsDictionary", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("ShowFormatError", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("StoreRSIDOnSave", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("SaveNormalPrompt", false, ref wdOptions));
                }
                catch (SystemException)
                {
                }

                Object              filename           = (Object)inputFile;
                Boolean             visible            = !(Boolean)options["hidden"];
                Boolean             nowrite            = (Boolean)options["readonly"];
                Boolean             includeProps       = !(Boolean)options["excludeprops"];
                Boolean             includeTags        = !(Boolean)options["excludetags"];
                Boolean             bitmapMissingFonts = !(Boolean)options["word_ref_fonts"];
                Boolean             autosave           = options.ContainsKey("IsTempWord") && (Boolean)options["IsTempWord"];
                bool                pdfa    = (Boolean)options["pdfa"] ? true : false;
                WdExportOptimizeFor quality = WdExportOptimizeFor.wdExportOptimizeForPrint;
                if ((Boolean)options["print"])
                {
                    quality = WdExportOptimizeFor.wdExportOptimizeForPrint;
                }
                if ((Boolean)options["screen"])
                {
                    quality = WdExportOptimizeFor.wdExportOptimizeForOnScreen;
                }
                WdExportCreateBookmarks bookmarks = (Boolean)options["bookmarks"] ?
                                                    WdExportCreateBookmarks.wdExportCreateHeadingBookmarks :
                                                    WdExportCreateBookmarks.wdExportCreateNoBookmarks;
                WdExportItem showMarkup = WdExportItem.wdExportDocumentContent;
                if ((Boolean)options["markup"])
                {
                    showMarkup = WdExportItem.wdExportDocumentWithMarkup;
                }

                // Large Word files may simply not print reliably - if the word_max_pages
                // configuration option is set, then we must close up and forget about
                // converting the file.
                var maxPages = (int)options[@"word_max_pages"];

                var documents      = word.Documents;
                var normalTemplate = word.NormalTemplate;

                String readPassword = "";
                if (!String.IsNullOrEmpty((String)options["password"]))
                {
                    readPassword = (String)options["password"];
                }
                Object oReadPass = (Object)readPassword;

                String writePassword = "";
                if (!String.IsNullOrEmpty((String)options["writepassword"]))
                {
                    writePassword = (String)options["writepassword"];
                }
                Object oWritePass = (Object)writePassword;

                // Check for password protection and no password
                if (Converter.IsPasswordProtected(inputFile) && String.IsNullOrEmpty(readPassword))
                {
                    normalTemplate.Saved = true;
                    Console.WriteLine("Unable to open password protected file");
                    return((int)ExitCode.PasswordFailure);
                }

                Document doc = null;
                try
                {
                    if ((bool)options["merge"] && !String.IsNullOrEmpty((string)options["template"]) &&
                        File.Exists((string)options["template"]) &&
                        System.Text.RegularExpressions.Regex.IsMatch((string)options["template"], @"^.*\.dot[mx]?$"))
                    {
                        // Create a new document based on a template
                        doc = documents.Add((string)options["template"]);
                        Object rStart = 0;
                        Object rEnd   = 0;
                        Range  range  = doc.Range(rStart, rEnd);
                        range.InsertFile(inputFile);
                        Converter.releaseCOMObject(range);
                        // Make sure we save the file with the original filename so
                        // filename fields update correctly
                        temporaryStorageDir = Path.GetTempFileName();
                        File.Delete(temporaryStorageDir);
                        Directory.CreateDirectory(temporaryStorageDir);
                        doc.SaveAs(Path.Combine(temporaryStorageDir, Path.GetFileName(inputFile)));
                    }
                    else
                    {
                        // Open the source document
                        doc = documents.OpenNoRepairDialog(ref filename, ref oMissing,
                                                           nowrite, ref oMissing, ref oReadPass, ref oMissing, ref oMissing,
                                                           ref oWritePass, ref oMissing, ref oMissing, ref oMissing, visible,
                                                           true, ref oMissing, ref oMissing, ref oMissing);
                    }
                }
                catch (System.Runtime.InteropServices.COMException)
                {
                    Console.WriteLine("Unable to open file");
                    return((int)ExitCode.FileOpenFailure);
                }
                doc.Activate();

                // Check if there are too many pages
                if (maxPages > 0)
                {
                    var pageCount = doc.ComputeStatistics(WdStatistic.wdStatisticPages, false);
                    doc.Saved = true;
                    if (pageCount > maxPages)
                    {
                        throw new Exception(String.Format("Too many pages to process ({0}). More than {1}", pageCount, maxPages));
                    }
                }

                // Prevent "property not available" errors, see http://blogs.msmvps.com/wordmeister/2013/02/22/word2013bug-not-available-for-reading/
                var docWin     = doc.ActiveWindow;
                var docWinView = docWin.View;
                if (wordVersion >= 15)
                {
                    docWinView.ReadingLayout = false;
                }

                // Sometimes the print view will not be available (e.g. for a blog post)
                // Try and switch view
                try
                {
                    docWinView.Type = WdViewType.wdPrintPreview;
                }
                catch (Exception) {}

                // Hide comments
                try
                {
                    docWinView.RevisionsView            = WdRevisionsView.wdRevisionsViewFinal;
                    docWinView.ShowRevisionsAndComments = false;
                }
                catch (SystemException) {}

                // Try to avoid Word thinking any changes are happening to the document
                doc.SpellingChecked = true;
                doc.GrammarChecked  = true;

                // Changing these properties may be disallowed if the document is protected
                if (doc.ProtectionType == WdProtectionType.wdNoProtection)
                {
                    if (autosave)
                    {
                        doc.Save(); doc.Saved = true;
                    }
                    doc.TrackMoves      = false;
                    doc.TrackRevisions  = false;
                    doc.TrackFormatting = false;
                }
                normalTemplate.Saved = true;

                // Hide the document window if need be
                if ((Boolean)options["hidden"])
                {
                    var activeWin = word.ActiveWindow;
                    activeWin.Visible     = false;
                    activeWin.WindowState = WdWindowState.wdWindowStateMinimize;
                    Converter.releaseCOMObject(activeWin);
                }

                // Check if we have a template file to apply to this document
                // The template must be a file and must end in .dot, .dotx or .dotm
                if (!String.IsNullOrEmpty((String)options["template"]) && !(bool)options["merge"])
                {
                    string template = (string)options["template"];
                    if (File.Exists(template) && System.Text.RegularExpressions.Regex.IsMatch(template, @"^.*\.dot[mx]?$"))
                    {
                        doc.set_AttachedTemplate(template);
                        doc.UpdateStyles();
                        tmpl = doc.get_AttachedTemplate();
                    }
                    else
                    {
                        Console.WriteLine("Invalid template '{0}'", template);
                    }
                }


                // See if we have to update fields
                if (!(Boolean)options["word_no_field_update"])
                {
                    updateDocumentFields(doc, word, inputFile, options);
                }

                var pageSetup = doc.PageSetup;
                if ((float)options["word_header_dist"] >= 0)
                {
                    pageSetup.HeaderDistance = (float)options["word_header_dist"];
                }
                if ((float)options["word_footer_dist"] >= 0)
                {
                    pageSetup.FooterDistance = (float)options["word_footer_dist"];
                }

                normalTemplate.Saved = true;
                if (autosave)
                {
                    doc.Save();
                }
                doc.Saved = true;
                doc.ExportAsFixedFormat(outputFile, WdExportFormat.wdExportFormatPDF, false,
                                        quality, WdExportRange.wdExportAllDocument,
                                        1, 1, showMarkup, includeProps, true, bookmarks, includeTags, bitmapMissingFonts, pdfa);

                if (tmpl != null)
                {
                    tmpl.Saved = true;
                }

                object saveChanges = autosave? WdSaveOptions.wdSaveChanges : WdSaveOptions.wdDoNotSaveChanges;
                if (nowrite)
                {
                    doc.Saved = true;
                }
                normalTemplate.Saved = true;
                ((_Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing);

                // Reset options
                foreach (AppOption opt in wordOptionList)
                {
                    opt.resetValue(ref wdOptions);
                }

                Converter.releaseCOMObject(pageSetup);
                Converter.releaseCOMObject(docWinView);
                Converter.releaseCOMObject(docWin);
                Converter.releaseCOMObject(wdOptions);
                Converter.releaseCOMObject(documents);
                Converter.releaseCOMObject(doc);
                Converter.releaseCOMObject(tmpl);
                Converter.releaseCOMObject(normalTemplate);

                return((int)ExitCode.Success);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return((int)ExitCode.UnknownError);
            }
            finally
            {
                if (temporaryStorageDir != null && Directory.Exists(temporaryStorageDir))
                {
                    try
                    {
                        if (File.Exists(Path.Combine(temporaryStorageDir, Path.GetFileName(inputFile))))
                        {
                            File.Delete(Path.Combine(temporaryStorageDir, Path.GetFileName(inputFile)));
                        }
                        Directory.Delete(temporaryStorageDir);
                    }
                    catch (Exception) { }
                }
                if (word != null && !running)
                {
                    ((_Application)word).Quit(ref oMissing, ref oMissing, ref oMissing);
                }
                Converter.releaseCOMObject(word);
            }
        }
Example #25
0
        /// <summary>
        /// Convert a Word file to PDF
        /// </summary>
        /// <param name="inputFile">Full path of the input Word file</param>
        /// <param name="outputFile">Full path of the output PDF</param>
        /// <returns></returns>
        public static new int Convert(String inputFile, String outputFile, Hashtable options)
        {
            Boolean          running  = (Boolean)options["noquit"];
            Application      word     = null;
            object           oMissing = System.Reflection.Missing.Value;
            Template         tmpl;
            String           temporaryStorageDir = null;
            float            wordVersion         = 0;
            List <AppOption> wordOptionList      = new List <AppOption>();

            try
            {
                String  filename           = (String)inputFile;
                Boolean hasSignatures      = WordConverter.HasDigitalSignatures(filename);
                Boolean visible            = !(Boolean)options["hidden"];
                Boolean openAndRepair      = !(Boolean)options["word_no_repair"];
                Boolean nowrite            = (Boolean)options["readonly"];
                Boolean includeProps       = !(Boolean)options["excludeprops"];
                Boolean includeTags        = !(Boolean)options["excludetags"];
                Boolean bitmapMissingFonts = !(Boolean)options["word_ref_fonts"];
                Boolean autosave           = options.ContainsKey("IsTempWord") && (Boolean)options["IsTempWord"];
                bool    pdfa          = (Boolean)options["pdfa"] ? true : false;
                String  writePassword = "";
                String  readPassword  = "";
                int     maxPages      = 0;

                WdExportOptimizeFor     quality    = WdExportOptimizeFor.wdExportOptimizeForPrint;
                WdExportItem            showMarkup = WdExportItem.wdExportDocumentContent;
                WdExportCreateBookmarks bookmarks  = (Boolean)options["bookmarks"] ?
                                                     WdExportCreateBookmarks.wdExportCreateHeadingBookmarks :
                                                     WdExportCreateBookmarks.wdExportCreateNoBookmarks;
                Options   wdOptions      = null;
                Documents documents      = null;
                Template  normalTemplate = null;

                tmpl = null;
                try
                {
                    word = (Microsoft.Office.Interop.Word.Application)Marshal.GetActiveObject("Word.Application");
                }
                catch (System.Exception)
                {
                    int tries = 10;
                    word    = new Microsoft.Office.Interop.Word.Application();
                    running = false;
                    while (tries > 0)
                    {
                        try
                        {
                            // Try to set a property on the object
                            word.ScreenUpdating = false;
                        }
                        catch (COMException)
                        {
                            // Decrement the number of tries and have a bit of a snooze
                            tries--;
                            Thread.Sleep(500);
                            continue;
                        }
                        // Looks ok, so bail out of the loop
                        break;
                    }
                    if (tries == 0)
                    {
                        ReleaseCOMObject(word);
                        return((int)ExitCode.ApplicationError);
                    }
                }

                wdOptions          = word.Options;
                word.DisplayAlerts = WdAlertLevel.wdAlertsNone;
                // Issue #48 - we should allow control over whether the history is lost
                if (!(Boolean)options["word_keep_history"])
                {
                    word.DisplayRecentFiles = false;
                }
                word.DisplayDocumentInformationPanel = false;
                word.FeatureInstall = Microsoft.Office.Core.MsoFeatureInstall.msoFeatureInstallNone;
                wordVersion         = (float)System.Convert.ToDecimal(word.Version, new CultureInfo("en-US"));

                // Set the Word options in a way that allows us to reset the options when we finish
                try
                {
                    wordOptionList.Add(new AppOption("AlertIfNotDefault", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("AllowReadingMode", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("PrecisePositioning", true, ref wdOptions));
                    wordOptionList.Add(new AppOption("UpdateFieldsAtPrint", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("UpdateLinksAtPrint", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("UpdateLinksAtOpen", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("UpdateFieldsWithTrackedChangesAtPrint", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("WarnBeforeSavingPrintingSendingMarkup", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("BackgroundSave", true, ref wdOptions));
                    wordOptionList.Add(new AppOption("SavePropertiesPrompt", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("DoNotPromptForConvert", true, ref wdOptions));
                    wordOptionList.Add(new AppOption("PromptUpdateStyle", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("ConfirmConversions", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("CheckGrammarAsYouType", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("CheckGrammarWithSpelling", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("CheckSpellingAsYouType", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("DisplaySmartTagButtons", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("EnableLivePreview", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("ShowReadabilityStatistics", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("SuggestSpellingCorrections", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("AllowDragAndDrop", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("EnableMisusedWordsDictionary", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("ShowFormatError", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("StoreRSIDOnSave", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("SaveNormalPrompt", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("AllowFastSave", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("BackgroundOpen", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("ShowMarkupOpenSave", false, ref wdOptions));
                    wordOptionList.Add(new AppOption("SaveInterval", 0, ref wdOptions));
                }
                catch (SystemException)
                {
                }

                // Set up the PDF output quality
                if ((Boolean)options["print"])
                {
                    quality = WdExportOptimizeFor.wdExportOptimizeForPrint;
                }
                if ((Boolean)options["screen"])
                {
                    quality = WdExportOptimizeFor.wdExportOptimizeForOnScreen;
                }

                if ((Boolean)options["markup"])
                {
                    showMarkup = WdExportItem.wdExportDocumentWithMarkup;
                }

                if (!String.IsNullOrEmpty((String)options["password"]))
                {
                    readPassword = (String)options["password"];
                }

                if (!String.IsNullOrEmpty((String)options["writepassword"]))
                {
                    writePassword = (String)options["writepassword"];
                }

                // Large Word files may simply not print reliably - if the word_max_pages
                // configuration option is set, then we must close up and forget about
                // converting the file.
                maxPages = (int)options[@"word_max_pages"];

                documents      = word.Documents;
                normalTemplate = word.NormalTemplate;

                // Check for password protection and no password
                if (IsPasswordProtected(inputFile) && String.IsNullOrEmpty(readPassword))
                {
                    normalTemplate.Saved = true;
                    Console.WriteLine("Unable to open password protected file");
                    return((int)ExitCode.PasswordFailure);
                }

                // If we are opening a document with a write password and no read password, and
                // we are not in read only mode, we should follow the document properties and
                // enforce a read only open. If we do not, Word pops up a dialog
                if (!nowrite && String.IsNullOrEmpty(writePassword) && IsReadOnlyEnforced(inputFile))
                {
                    nowrite = true;
                }

                // Having signatures means we should open the document very carefully
                if (hasSignatures)
                {
                    nowrite       = true;
                    autosave      = false;
                    openAndRepair = false;
                }

                Document doc = null;
                try
                {
                    if ((bool)options["merge"] && !String.IsNullOrEmpty((string)options["template"]) &&
                        File.Exists((string)options["template"]) &&
                        System.Text.RegularExpressions.Regex.IsMatch((string)options["template"], @"^.*\.dot[mx]?$", System.Text.RegularExpressions.RegexOptions.IgnoreCase))
                    {
                        // Create a new document based on a template
                        doc = documents.Add((string)options["template"]);
                        Object rStart = 0;
                        Object rEnd   = 0;
                        Range  range  = doc.Range(rStart, rEnd);
                        range.InsertFile(inputFile);
                        ReleaseCOMObject(range);
                        // Make sure we save the file with the original filename so
                        // filename fields update correctly
                        temporaryStorageDir = Path.GetTempFileName();
                        File.Delete(temporaryStorageDir);
                        Directory.CreateDirectory(temporaryStorageDir);
                        doc.SaveAs(Path.Combine(temporaryStorageDir, Path.GetFileName(inputFile)));
                    }
                    else
                    {
                        // Open the source document
                        doc = documents.OpenNoRepairDialog(FileName: filename, ReadOnly: nowrite, PasswordDocument: readPassword, WritePasswordDocument: writePassword, Visible: visible, OpenAndRepair: openAndRepair);
                    }
                }
                catch (COMException)
                {
                    Console.WriteLine("Unable to open file");
                    return((int)ExitCode.FileOpenFailure);
                }

                // Check if there are signatures in the document which changes how we do things
                if (hasSignatures)
                {
                    // Add in a delay to allow signatures to load
                    Thread.Sleep(500);
                }
                else
                {
                    Window docWin     = null;
                    View   docWinView = null;

                    doc.Activate();
                    // Check if there are too many pages
                    if (maxPages > 0)
                    {
                        var pageCount = doc.ComputeStatistics(WdStatistic.wdStatisticPages, false);
                        doc.Saved = true;
                        if (pageCount > maxPages)
                        {
                            throw new Exception(String.Format("Too many pages to process ({0}). More than {1}", pageCount, maxPages));
                        }
                    }

                    // Prevent "property not available" errors, see http://blogs.msmvps.com/wordmeister/2013/02/22/word2013bug-not-available-for-reading/
                    docWin     = doc.ActiveWindow;
                    docWinView = docWin.View;
                    if (wordVersion >= 15)
                    {
                        docWinView.ReadingLayout = false;
                    }

                    // Sometimes the print view will not be available (e.g. for a blog post)
                    // Try and switch view
                    try
                    {
                        docWinView.Type = WdViewType.wdPrintPreview;
                    }
                    catch (Exception) { }

                    // Hide comments
                    try
                    {
                        word.PrintPreview                     = false;
                        docWinView.RevisionsView              = WdRevisionsView.wdRevisionsViewFinal;
                        docWinView.ShowRevisionsAndComments   = false;
                        docWinView.ShowComments               = false;
                        docWinView.ShowFormatChanges          = false;
                        docWinView.ShowInkAnnotations         = false;
                        docWinView.ShowInsertionsAndDeletions = false;
                    }
                    catch (SystemException e) {
                        Console.WriteLine("Failed to set revision settings {0}", e.Message);
                    }

                    // Try to avoid Word thinking any changes are happening to the document
                    doc.SpellingChecked = true;
                    doc.GrammarChecked  = true;

                    // Changing these properties may be disallowed if the document is protected
                    // and is not signed
                    if (doc.ProtectionType == WdProtectionType.wdNoProtection && !hasSignatures)
                    {
                        if (autosave)
                        {
                            doc.Save(); doc.Saved = true;
                        }
                        doc.TrackMoves      = false;
                        doc.TrackRevisions  = false;
                        doc.TrackFormatting = false;

                        if ((Boolean)options["word_fix_table_columns"])
                        {
                            FixWordTableColumnWidths(doc);
                        }
                    }

                    normalTemplate.Saved = true;

                    // Hide the document window if need be
                    if ((Boolean)options["hidden"])
                    {
                        var activeWin = word.ActiveWindow;
                        activeWin.Visible     = false;
                        activeWin.WindowState = WdWindowState.wdWindowStateMinimize;
                        ReleaseCOMObject(activeWin);
                    }

                    // Check if we have a template file to apply to this document
                    // The template must be a file and must end in .dot, .dotx or .dotm
                    if (!String.IsNullOrEmpty((String)options["template"]) && !(bool)options["merge"])
                    {
                        string template = (string)options["template"];
                        if (File.Exists(template) && System.Text.RegularExpressions.Regex.IsMatch(template, @"^.*\.dot[mx]?$"))
                        {
                            doc.set_AttachedTemplate(template);
                            doc.UpdateStyles();
                            tmpl = doc.get_AttachedTemplate();
                        }
                        else
                        {
                            Console.WriteLine("Invalid template '{0}'", template);
                        }
                    }

                    // See if we have to update fields
                    if (!(Boolean)options["word_no_field_update"])
                    {
                        UpdateDocumentFields(doc, word, inputFile, options);
                    }

                    var pageSetup = doc.PageSetup;
                    if ((float)options["word_header_dist"] >= 0)
                    {
                        pageSetup.HeaderDistance = (float)options["word_header_dist"];
                    }
                    if ((float)options["word_footer_dist"] >= 0)
                    {
                        pageSetup.FooterDistance = (float)options["word_footer_dist"];
                    }
                    ReleaseCOMObject(pageSetup);
                    try
                    {
                        // Make sure we are not in a header footer view
                        docWinView.SeekView = WdSeekView.wdSeekPrimaryHeader;
                        docWinView.SeekView = WdSeekView.wdSeekPrimaryFooter;
                        docWinView.SeekView = WdSeekView.wdSeekMainDocument;
                    }
                    catch (Exception)
                    {
                        // We might fail when switching views
                    }

                    normalTemplate.Saved = true;
                    if (autosave)
                    {
                        doc.Save();
                    }
                    doc.Saved = true;
                    ReleaseCOMObject(docWinView);
                    ReleaseCOMObject(docWin);
                }

                // Set up a delegate function if we're using a printer
                PrintDocument printFunc = delegate(string destination, string printerName)
                {
                    word.ActivePrinter = printerName;
                    doc.PrintOut(Background: false, OutputFileName: destination);
                };

                if (String.IsNullOrEmpty((string)options["printer"]))
                {
                    // No printer given, so export
                    try
                    {
                        doc.ExportAsFixedFormat(outputFile, WdExportFormat.wdExportFormatPDF, false,
                                                quality, WdExportRange.wdExportAllDocument,
                                                1, 1, showMarkup, includeProps, true, bookmarks, includeTags, bitmapMissingFonts, pdfa);
                    } catch (Exception)
                    {
                        // Couldn't export, so see if there is a fallback printer
                        if (!String.IsNullOrEmpty((string)options["fallback_printer"]))
                        {
                            PrintToGhostscript((string)options["fallback_printer"], outputFile, printFunc);
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
                else
                {
                    PrintToGhostscript((string)options["printer"], outputFile, printFunc);
                }

                if (tmpl != null)
                {
                    tmpl.Saved = true;
                }

                object saveChanges = autosave? WdSaveOptions.wdSaveChanges : WdSaveOptions.wdDoNotSaveChanges;
                if (nowrite)
                {
                    doc.Saved = true;
                }
                normalTemplate.Saved = true;
                ((_Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing);

                // Reset options
                foreach (AppOption opt in wordOptionList)
                {
                    opt.ResetValue(ref wdOptions);
                }

                ReleaseCOMObject(wdOptions);
                ReleaseCOMObject(documents);
                ReleaseCOMObject(doc);
                ReleaseCOMObject(tmpl);
                ReleaseCOMObject(normalTemplate);

                return((int)ExitCode.Success);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return((int)ExitCode.UnknownError);
            }
            finally
            {
                if (temporaryStorageDir != null && Directory.Exists(temporaryStorageDir))
                {
                    try
                    {
                        if (File.Exists(Path.Combine(temporaryStorageDir, Path.GetFileName(inputFile))))
                        {
                            File.Delete(Path.Combine(temporaryStorageDir, Path.GetFileName(inputFile)));
                        }
                        Directory.Delete(temporaryStorageDir);
                    }
                    catch (Exception) { }
                }
                if (word != null && !running)
                {
                    CloseWordApplication(word);
                }
                ReleaseCOMObject(word);
            }
        }
Example #26
0
        /// <summary>
        /// Convert a Word file to PDF
        /// </summary>
        /// <param name="inputFile">Full path of the input Word file</param>
        /// <param name="outputFile">Full path of the output PDF</param>
        /// <returns></returns>
        public static new int Convert(String inputFile, String outputFile, Hashtable options)
        {
            Boolean running = (Boolean)options["noquit"];

            Microsoft.Office.Interop.Word.Application word = null;
            object oMissing = System.Reflection.Missing.Value;

            Microsoft.Office.Interop.Word.Template tmpl;
            String temporaryStorageDir = null;

            try
            {
                tmpl = null;
                try
                {
                    word = (Microsoft.Office.Interop.Word.Application)Marshal.GetActiveObject("Word.Application");
                }
                catch (System.Exception)
                {
                    word    = new Microsoft.Office.Interop.Word.Application();
                    running = false;
                }
                word.DisplayAlerts      = WdAlertLevel.wdAlertsNone;
                word.DisplayRecentFiles = false;
                word.DisplayDocumentInformationPanel = false;
                word.FeatureInstall = Microsoft.Office.Core.MsoFeatureInstall.msoFeatureInstallNone;
                var wdOptions = word.Options;
                try
                {
                    wdOptions.UpdateFieldsAtPrint = false;
                    wdOptions.UpdateLinksAtPrint  = false;
                    wdOptions.WarnBeforeSavingPrintingSendingMarkup = false;
                    wdOptions.BackgroundSave               = true;
                    wdOptions.SavePropertiesPrompt         = false;
                    wdOptions.DoNotPromptForConvert        = true;
                    wdOptions.PromptUpdateStyle            = false;
                    wdOptions.ConfirmConversions           = false;
                    wdOptions.CheckGrammarAsYouType        = false;
                    wdOptions.CheckGrammarWithSpelling     = false;
                    wdOptions.CheckSpellingAsYouType       = false;
                    wdOptions.DisplaySmartTagButtons       = false;
                    wdOptions.EnableLivePreview            = false;
                    wdOptions.ShowReadabilityStatistics    = false;
                    wdOptions.SuggestSpellingCorrections   = false;
                    wdOptions.AllowDragAndDrop             = false;
                    wdOptions.EnableMisusedWordsDictionary = false;
                }
                catch (SystemException)
                {
                }
                Object              filename     = (Object)inputFile;
                Boolean             visible      = !(Boolean)options["hidden"];
                Boolean             nowrite      = (Boolean)options["readonly"];
                Boolean             includeProps = !(Boolean)options["excludeprops"];
                Boolean             includeTags  = !(Boolean)options["excludetags"];
                bool                pdfa         = (Boolean)options["pdfa"] ? true : false;
                WdExportOptimizeFor quality      = WdExportOptimizeFor.wdExportOptimizeForPrint;
                if ((Boolean)options["print"])
                {
                    quality = WdExportOptimizeFor.wdExportOptimizeForPrint;
                }
                if ((Boolean)options["screen"])
                {
                    quality = WdExportOptimizeFor.wdExportOptimizeForOnScreen;
                }
                WdExportCreateBookmarks bookmarks = (Boolean)options["bookmarks"] ?
                                                    WdExportCreateBookmarks.wdExportCreateHeadingBookmarks :
                                                    WdExportCreateBookmarks.wdExportCreateNoBookmarks;
                WdExportItem showMarkup = WdExportItem.wdExportDocumentContent;
                if ((Boolean)options["markup"])
                {
                    showMarkup = WdExportItem.wdExportDocumentWithMarkup;
                }
                var documents      = word.Documents;
                var normalTemplate = word.NormalTemplate;

                String readPassword = "";
                if (!String.IsNullOrEmpty((String)options["password"]))
                {
                    readPassword = (String)options["password"];
                }
                Object oReadPass = (Object)readPassword;

                String writePassword = "";
                if (!String.IsNullOrEmpty((String)options["writepassword"]))
                {
                    writePassword = (String)options["writepassword"];
                }
                Object oWritePass = (Object)writePassword;

                // Check for password protection and no password
                if (Converter.IsPasswordProtected(inputFile) && String.IsNullOrEmpty(readPassword))
                {
                    normalTemplate.Saved = true;
                    Console.WriteLine("Unable to open password protected file");
                    return((int)ExitCode.PasswordFailure);
                }

                Document doc = null;
                try
                {
                    if ((bool)options["merge"] && !String.IsNullOrEmpty((string)options["template"]) &&
                        File.Exists((string)options["template"]) &&
                        System.Text.RegularExpressions.Regex.IsMatch((string)options["template"], @"^.*\.dot[mx]?$"))
                    {
                        // Create a new document based on a template
                        doc = documents.Add((string)options["template"]);
                        Object rStart = 0;
                        Object rEnd   = 0;
                        Range  range  = doc.Range(rStart, rEnd);
                        range.InsertFile(inputFile);
                        Converter.ReleaseCOMObject(range);
                        // Make sure we save the file with the original filename so
                        // filename fields update correctly
                        temporaryStorageDir = Path.GetTempFileName();
                        File.Delete(temporaryStorageDir);
                        Directory.CreateDirectory(temporaryStorageDir);
                        doc.SaveAs(Path.Combine(temporaryStorageDir, Path.GetFileName(inputFile)));
                    }
                    else
                    {
                        // Open the source document
                        doc = documents.OpenNoRepairDialog(ref filename, ref oMissing,
                                                           nowrite, ref oMissing, ref oReadPass, ref oMissing, ref oMissing,
                                                           ref oWritePass, ref oMissing, ref oMissing, ref oMissing, visible,
                                                           true, ref oMissing, ref oMissing, ref oMissing);
                    }
                }
                catch (System.Runtime.InteropServices.COMException)
                {
                    Console.WriteLine("Unable to open file");
                    return((int)ExitCode.FileOpenFailure);
                }
                doc.Activate();

                // Prevent "property not available" errors, see http://blogs.msmvps.com/wordmeister/2013/02/22/word2013bug-not-available-for-reading/
                var docWin     = doc.ActiveWindow;
                var docWinView = docWin.View;
                docWinView.Type = WdViewType.wdPrintPreview;

                // Try to avoid Word thinking any changes are happening to the document
                doc.SpellingChecked = true;
                doc.GrammarChecked  = true;

                // Changing these properties may be disallowed if the document is protected
                if (doc.ProtectionType == WdProtectionType.wdNoProtection)
                {
                    doc.TrackMoves      = false;
                    doc.TrackRevisions  = false;
                    doc.TrackFormatting = false;
                }
                normalTemplate.Saved = true;

                // Hide the document window if need be
                if ((Boolean)options["hidden"])
                {
                    var activeWin = word.ActiveWindow;
                    activeWin.Visible     = false;
                    activeWin.WindowState = WdWindowState.wdWindowStateMinimize;
                    Converter.ReleaseCOMObject(activeWin);
                }

                // Check if we have a template file to apply to this document
                // The template must be a file and must end in .dot, .dotx or .dotm
                if (!String.IsNullOrEmpty((String)options["template"]) && !(bool)options["merge"])
                {
                    string template = (string)options["template"];
                    if (File.Exists(template) && System.Text.RegularExpressions.Regex.IsMatch(template, @"^.*\.dot[mx]?$"))
                    {
                        doc.set_AttachedTemplate(template);
                        doc.UpdateStyles();
                        tmpl = (Microsoft.Office.Interop.Word.Template)doc.get_AttachedTemplate();
                    }
                    else
                    {
                        Console.WriteLine("Invalid template '{0}'", template);
                    }
                }

                // Update some of the field types in the document so the printed
                // PDF looks correct. Skips some field types (such as ASK) that would
                // create dialogs
                foreach (Microsoft.Office.Interop.Word.Section section in doc.Sections)
                {
                    var sectionRange  = section.Range;
                    var sectionFields = sectionRange.Fields;
                    foreach (Field sectionField in sectionFields)
                    {
                        WordConverter.UpdateField(sectionField, word, inputFile);
                    }

                    var sectionPageSetup = section.PageSetup;
                    var headers          = section.Headers;
                    foreach (Microsoft.Office.Interop.Word.HeaderFooter header in headers)
                    {
                        if (header.Exists)
                        {
                            var range       = header.Range;
                            var rangeFields = range.Fields;
                            foreach (Field rangeField in rangeFields)
                            {
                                WordConverter.UpdateField(rangeField, word, inputFile);
                            }
                            // Simply querying the range of the header will create it.
                            // If the header is empty, this can introduce additional space
                            // between the non-existant header and the top of the page.
                            // To counter this for empty footers, we manually set the header
                            // distance to zero here
                            var shapes = header.Shapes;
                            if (shapes.Count == 0)
                            {
                                sectionPageSetup.HeaderDistance = 0;
                            }
                            Converter.ReleaseCOMObject(shapes);
                            Converter.ReleaseCOMObject(rangeFields);
                            Converter.ReleaseCOMObject(range);
                        }
                    }

                    var footers = section.Footers;
                    foreach (Microsoft.Office.Interop.Word.HeaderFooter footer in footers)
                    {
                        if (footer.Exists)
                        {
                            var range       = footer.Range;
                            var rangeFields = range.Fields;
                            foreach (Field rangeField in rangeFields)
                            {
                                WordConverter.UpdateField(rangeField, word, inputFile);
                            }
                            // Simply querying the range of the footer will create it.
                            // If the footer is empty, this can introduce additional space
                            // between the non-existant footer and the bottom of the page.
                            // To counter this for empty footers, we manually set the footer
                            // distance to zero here
                            var shapes = footer.Shapes;
                            if (shapes.Count == 0)
                            {
                                sectionPageSetup.FooterDistance = 0;
                            }
                            Converter.ReleaseCOMObject(shapes);
                            Converter.ReleaseCOMObject(rangeFields);
                            Converter.ReleaseCOMObject(range);
                        }
                    }
                    Converter.ReleaseCOMObject(sectionFields);
                    Converter.ReleaseCOMObject(sectionRange);
                    Converter.ReleaseCOMObject(headers);
                    Converter.ReleaseCOMObject(footers);
                    Converter.ReleaseCOMObject(sectionPageSetup);
                }

                var docFields = doc.Fields;
                foreach (Field docField in docFields)
                {
                    WordConverter.UpdateField(docField, word, inputFile);
                }
                var storyRanges = doc.StoryRanges;
                foreach (Range range in storyRanges)
                {
                    var rangeFields = range.Fields;
                    foreach (Field field in rangeFields)
                    {
                        WordConverter.UpdateField(field, word, inputFile);
                    }
                    Converter.ReleaseCOMObject(rangeFields);
                }
                Converter.ReleaseCOMObject(storyRanges);
                Converter.ReleaseCOMObject(docFields);

                var pageSetup = doc.PageSetup;
                if ((float)options["word_header_dist"] >= 0)
                {
                    pageSetup.HeaderDistance = (float)options["word_header_dist"];
                }
                if ((float)options["word_footer_dist"] >= 0)
                {
                    pageSetup.FooterDistance = (float)options["word_footer_dist"];
                }

                normalTemplate.Saved = true;
                doc.Saved            = true;
                doc.ExportAsFixedFormat(outputFile, WdExportFormat.wdExportFormatPDF, false,
                                        quality, WdExportRange.wdExportAllDocument,
                                        1, 1, showMarkup, includeProps, true, bookmarks, includeTags, true, pdfa);

                if (tmpl != null)
                {
                    tmpl.Saved = true;
                }

                object saveChanges = WdSaveOptions.wdDoNotSaveChanges;
                if (nowrite)
                {
                    doc.Saved = true;
                }
                normalTemplate.Saved = true;
                ((_Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing);

                Converter.ReleaseCOMObject(pageSetup);
                Converter.ReleaseCOMObject(docWinView);
                Converter.ReleaseCOMObject(docWin);
                Converter.ReleaseCOMObject(wdOptions);
                Converter.ReleaseCOMObject(documents);
                Converter.ReleaseCOMObject(doc);
                Converter.ReleaseCOMObject(tmpl);
                Converter.ReleaseCOMObject(normalTemplate);

                return((int)ExitCode.Success);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                return((int)ExitCode.UnknownError);
            }
            finally
            {
                if (temporaryStorageDir != null && Directory.Exists(temporaryStorageDir))
                {
                    if (File.Exists(Path.Combine(temporaryStorageDir, Path.GetFileName(inputFile))))
                    {
                        File.Delete(Path.Combine(temporaryStorageDir, Path.GetFileName(inputFile)));
                    }
                    Directory.Delete(temporaryStorageDir);
                }
                if (word != null && !running)
                {
                    ((_Application)word).Quit(ref oMissing, ref oMissing, ref oMissing);
                }
                Converter.ReleaseCOMObject(word);
            }
        }