转换Word文档为PDF文件

1.使用 Office COM组件的Microsoft.Office.Interop.word.dll

 该方法需要在电脑上安装Office软件,并且需要Office支持转换为PDF格式,如果不支持,从官网下载一个SaveAsPDFandXPS.exe插件

 Interop.word程序集可以通过Nuget程序包获取,实现代码如下:

public bool WordToPDF2(string sourcePath)
      {

            bool result = false;
            Word.Application application = new Word.Application();
            Word.Document document = null;

            try

            {
                application.Visible = false;

                document = application.Documents.Open(sourcePath);

                string PDFPath = sourcePath.Replace(".doc", ".pdf");//pdf存放位置

                if (!File.Exists(PDFPath))//存在PDF,不需要继续转换

                {
                    document.ExportAsFixedFormat(PDFPath, Word.WdExportFormat.wdExportFormatPDF);
                }
                result = true;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                result = false;
            }
            finally
            {
                document.Close();
            }
            return result;
      }

 

2.使用Aspose.Words组件 

  首先需要引用Aspose.Words.dll,链接地址:https://pan.baidu.com/s/1rJvjp-kMsEterYf_oud28Q  提取码:awiw

      代码如下:

      

public bool WordToPDF1(string sourcePath)
        {
            try
            {

                Document doc = new Document(sourcePath);
                string targetPath = sourcePath.ToUpper().Replace(".DOCX", ".PDF");
                doc.Save(targetPath,SaveFormat.Pdf);
            }
            catch(Exception e)
            {
                Console.WriteLine(e.Message);
                return false;
            }
            return true;
 }

 

  

 

 

 

 

 

 

posted on 2018-11-07 14:55  明君  阅读(510)  评论(0编辑  收藏  举报

导航