word转pdf

在日常代码开发中经常用到的功能就是word转pdf,下面就来介绍两种转的方式

第一种:Aspose.word

aspose的开源组件非常多,比如excel的导出,支持的合并单元等功能非常好用,这里用到的是word的相关第三方组组件

这里先提供第三方组件的插件(java和c#)

https://download.csdn.net/download/u013407099/10349630

直接上代码

c#版本

   public void ConvertWordToPdf(string inputFileName, string outputFileName)
        {
            #region 注册Aspose.Words 无需改动

            string licenseFile = AppDomain.CurrentDomain.BaseDirectory + "/bin/Aspose.Words.lic"; //Path.Combine(MapPath("~/bin"), "Aspose.Words.lic");

            if (File.Exists(licenseFile))
            {
                //This shows how to license Aspose.Words, if you don't specify a license, 
                //Aspose.Words works in evaluation mode.
                Aspose.Words.License license = new Aspose.Words.License();
                license.SetLicense(licenseFile);
            }

            #endregion

            // 打开模板文档
            Aspose.Words.Document doc = new Aspose.Words.Document(inputFileName);
            //aspose.words将doc转pdf
            doc.Save(outputFileName, Aspose.Words.SaveFormat.Pdf);
        }

JAVA版本

public  void doc2pdf(String inPath, String outPath) {
        if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
            return;
        }
        try {
            long old = System.currentTimeMillis();
            Document doc = new Document(inPath); // Address是将要被转化的word文档
            doc.save(outPath, SaveFormat.PDF);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
            // EPUB, XPS, SWF 相互转换
            long now = System.currentTimeMillis();
            System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒"); // 转化用时
        } catch (Exception e) {
            System.out.print("fw_wordtopdferror:"+e.toString());
        }
    }

使用Aspose转换时候要注意doc.save方法一定要使用直接存到指定路径为文件,使用其他的方法混村在pdf准还完毕后进程未释放被占用导致文件使用为0字节的问题,代码中已加入去除水印的部分,可以参考

虽然Aspose很好用,但是终究是第三方的东西,有时候转出的来复杂文件效果可能显示不是那么好,那么在c#中可可以使用Microsoft提供的word的com组件来转换,转出来的效果就是和word中另存pdf效果一样,先上代码

 /// <summary>
        /// 在服务器端Doc文档转换为PDF文档
        /// </summary>
        /// <param name="docFilePath">输入路径</param>
        /// <param name="pdfFilePath">输出路径</param>
        /// <returns>Boolean</returns>
        bool ConvertWordToPdf(string docFilePath, string pdfFilePath)
        {
            object paramMissing = Type.Missing;
            if (!File.Exists(docFilePath))
                return false;
            try
            {
                Microsoft.Office.Interop.Word.Application wordApplication = new Microsoft.Office.Interop.Word.Application();
                Document wordDocument = null;

                object paramSourceDocPath = docFilePath;
                string paramExportFilePath = pdfFilePath;

                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.wdExportCreateHeadingBookmarks;//.wdExportCreateWordBookmarks;
                bool paramDocStructureTags = true;
                bool paramBitmapMissingFonts = true;
                bool paramUseISO19005_1 = false;

                try
                {
                    // 打开word文件
                    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);
                    // 输出到pdf格式
                    if (wordDocument != null)
                    {
                      
                        wordApplication.ActiveDocument.Fields.Update();
                        wordDocument.ExportAsFixedFormat(paramExportFilePath,
                                                         paramExportFormat, paramOpenAfterExport,
                                                         paramExportOptimizeFor, paramExportRange, paramStartPage,
                                                         paramEndPage, paramExportItem, paramIncludeDocProps,
                                                         paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
                                                         paramBitmapMissingFonts, paramUseISO19005_1,
                                                         ref paramMissing);
                        //EpointLog4Net.Info(BizLogic.LogName, "doc转pdf Service Info:doc文档转化pdf文档转化成功。");
                    }
                }
                //在服务器端记录错误信息
                catch (Exception ex)
                {
                    //EpointLog4Net.Error(BizLogic.LogName, "doc转pdf Service error:" + ex.ToString());
                    return false;
                }
                finally
                {
                    //关闭文档实体
                    if (wordDocument != null)
                    {
                        wordDocument.Close(ref paramMissing, ref paramMissing,
                                           ref paramMissing);
                        wordDocument = null;
                    }
                    // 关闭word进程
                    if (wordApplication != null)
                    {
                        wordApplication.Quit(ref paramMissing, ref paramMissing,
                                             ref paramMissing);
                        wordApplication = null;
                    }
                    //垃圾回收
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                }
                return true;
            }
            //在服务器端记录错误信息
            catch (Exception err)
            {
                //EpointLog4Net.Error(BizLogic.LogName, "doc转pdf Service error: " + ExceptionOperate.GetExceptionString(err) + "\n");
                return false;
            }
        }

注:项目中需要引用Microsoft.Office.Interop.Word

使用原生转换的效果好是必然的,但是环境条件要求也是有要求的,不想aspose完全独立,下面就介绍下使用com组件转换word需要注意的几个地方

1.服务器必须安装word和adobe pdf(word推荐2010效果较好)

2.必须设置word的com组件权限,可以参考https://wenku.baidu.com/view/7523d531783e0912a2162a5a.html?from=search

3.如果使用window是服务,一定要设置交互式用户或者是管理员账户,否则会出现服务运行没有效果,非常难排查,出现工厂类xxxxx无权限的,使用指定的admin用户

4.word转换字的格式有问题的,请安装相关字体,如方正小标宋等(非windows自带字体)

5.转换时要将word先以文件的形式保存下来,不要以流的形式的重载方法转换,可能出现错乱问题

6.如果服务器装过wps的,卸载时请是用自带卸载,且不保留配置,从控制面满卸载会破坏word文件的注册表导致转换失败(此问题可以通过重新安装wps再卸载解决)

7.如果是64位系统,尝试在C:\Windows\SysWOW64\config\systemprofile\下面建立Desktop

                                                                                        生活永远艰辛,并且永远如此,祝好!





猜你喜欢

转载自blog.csdn.net/u013407099/article/details/79945610