C#将Word转换成PDF方法总结(基于Office和WPS两种方案)

有时候,我们需要在线上预览word文档,当然我们可以用NPOI抽出Word中的文字和表格,然后显示到网页上面,但是这样会丢失掉Word中原有的格式和图片。一个比较好的办法就是将word转换成pdf,然后让客户预览,下面来看一下基于Office和WPS的两种解决方案。


一、基于Office的解决方案

  正如标题所说,基于Office就是要求服务器上面要安装的有Office。我们通过C#代码来调用COM接口,实现将Word转换成PDF。下面来看一下具体实现,首先引用Microsoft.Office.Interop.Word.dll,然后编写如下代码:


public bool WordToPDF(string sourcePath, string targetPath)
        {
           bool result = false;
           Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application();
           Document document = null;
           try
           {
              application.Visible = false;
              document = application.Documents.Open(sourcePath);
              document.ExportAsFixedFormat(targetPath, WdExportFormat.wdExportFormatPDF);
              result = true;
           }
           catch (Exception e)
           {
              Console.WriteLine(e.Message);
              result = false;
           }
           finally
           {
              document.Close();
           }
           return result;
        }



二、基于WPS的解决方案

   WPS最大的好处当然是免费,还有就是体积小。要实现Word到PDF的转换,当然,这个要求服务器上面必须安装的有WPS,我们调用的仍然是COM接口,然后编写如下代码:


public bool WordToPdfWithWPS(string sourcePath, string targetPath)
        {
            WPS.ApplicationClass app = new WPS.ApplicationClass();
            WPS.Document doc = null;
           try
           {
              doc = app.Documents.Open(sourcePath, true, true, false, null, null, false, "", null, 100, 0, true, true, 0, true);
              doc.ExportPdf(targetPath, "", "");
           }
           catch (Exception ex)
           {
              Console.WriteLine(ex.Message);
              return false;
           }
           finally
           {
              doc.Close();
           }
           return true;
        }

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值