欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

转换Word文档为PDF文件

程序员文章站 2022-04-14 10:15:54
1.使用 Office COM组件的Microsoft.Office.Interop.word.dll库 该方法需要在电脑上安装Office软件,并且需要Office支持转换为PDF格式,如果不支持,从官网下载一个SaveAsPDFandXPS.exe插件 Interop.word程序集可以通过Nu ......

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;
 }