软件编程
位置:首页>> 软件编程>> C#编程>> C#将Word转换成PDF方法汇总(基于Office和WPS)

C#将Word转换成PDF方法汇总(基于Office和WPS)

作者:雲霏霏  发布时间:2021-09-12 22:52:58 

标签:C#,Word,PDF

有时候,我们需要在线上预览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;
   }

 三、企业级解决方案

对于大型企业来说,往往有多台服务器,不可能在每台服务器上面安装office或者会WPS,或者说公司根本不想在服务器上面安装这些没用的软件。这个时候该怎么办呢?毕竟服务器上面安装这些软件就是一种资源的浪费。

当然,功能还是要实现的,那么该怎么解决呢?实际上,我们可以在一台服务器上面安装ofiice或者WPS软件,然后部署WCF服务或者remoting等WebService,其他的服务器可以调用这个服务来实现Word到PDF的转换。

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com