Word文档转PDF方法探索

最近的项目中须要将Word转换为PDF文件,找了不少方法和组件,最后找到了一些方法,和你们分享。
1、使用微软官方自带转换方法
好处是写法方便,官方支持,缺点是须要在服务器上安装office,并且要配置COM组件的调用,至关麻烦;感兴趣的能够查一查并配置,代码以下;git

public void WordToPDF()
        {
            string pathAndName = "D:/test/test.docx";
            Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application();
            Microsoft.Office.Interop.Word.Document document = null;
            try
            {
                    string wordname = pathAndName + ".docx";                  
                    application.Visible = false;
                    document = application.Documents.Open(wordname);
                    string pdfPath = pathAndName.Replace(".docx", ".pdf"); //pdf存放位置
                    if (!System.IO.File.Exists(pdfPath)) //存在PDF,不须要继续转换
                    {
                        document.ExportAsFixedFormat(pdfPath,
                            Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF);
                    }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                throw new Exception("word转换失败");
            }
            finally
            {
                document.Close();
            }       
        }

2、使用免费的Spire.Doc组件来转换
Spire.Doc有免费的版本和收费的版本,免费的版本能够转换3页的word到pdf,收费的没有使用过;可是使用转换后效果不是很好,和word文档有一些出入,好比word有有下划线没写入内容,转换后下划线不见了等问题,遂放弃了该组件;
代码以下:github

public void wordToPdfWithSpireDoc(string filePath,string wordName,string pdfName)
        {
            try
            {
                Document doc = new Document();
                doc.LoadFromFile(filePath+wordName);
                doc.SaveToFile(filePath + pdfName, FileFormat.PDF);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
          
        }

3、使用Aspose.Words组件
Aspose.Words是一个商业组件,咱们能够使用破解版等;有点转换方便快捷,并且转换效果与word相比,几乎无差异;服务器

if (File.Exists(exportPath + wordName))
                {
                    Document doc = new Document(exportPath + wordName);
                    doc.Save(exportPath + pdfName, Aspose.Words.SaveFormat.Pdf);
                }

4、总结
word模板导出方法,找到了开源的Xceed.docx,用起来还不错;
Excel模板导出方法,找到了开源的ExcelReport,git地址 https://github.com/hanzhaoxin/ExcelReport
还有wps转换word等方法,就不一一列举,在网上也找了好久,组件不少,合适且免费的相对较少,你们有好的方法和组件也能够相互交流。app

相关文章
相关标签/搜索