转换Word文档为PDF文件

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

 该方法须要在电脑上安装Office软件,而且须要Office支持转换为PDF格式,若是不支持,从官网下载一个SaveAsPDFandXPS.exe插件spa

 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组件 code

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

      代码以下:blog

      

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;
 }
相关文章
相关标签/搜索