版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/jianyuerensheng/article/details/78190964
本文主要是采用C#将word文件转为PDF。程序中添加引用using Microsoft.Office.Interop.Word; 具体源码如下所示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using Microsoft.Office.Interop.Word;
namespace Test.Zjn.Utils
{
public class WordToPdfHelper : IDisposable
{
public static readonly log4net.ILog log =
log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
dynamic wps;
public WordToPdfHelper()
{
//创建wps实例,需提前安装wps
Type type = Type.GetTypeFromProgID("KWps.Application");
wps = Activator.CreateInstance(type);
}
/// <summary>
/// Word转PDF
/// </summary>
/// <param name="wordPath">Wps文件路径</param>
/// <param name="pdfPath">Pdf文件路径</param>
/// <returns></returns>
public void ToPdf(string wordPath, string pdfPath = null)
{
try
{
if (wordPath == null)
{
throw new ArgumentNullException("wpsFilename");
}
if (pdfPath == null)
{
pdfPath = Path.ChangeExtension(wordPath, "pdf");
}
Console.WriteLine(string.Format(@"正在转换 [{0}] -> [{1}]", wordPath, pdfPath));
//用wps 打开word不显示界面
dynamic doc = wps.Documents.Open(wordPath, Visible: false);
//doc 转pdf
doc.ExportAsFixedFormat(pdfPath, WdExportFormat.wdExportFormatPDF);
//设置隐藏菜单栏和工具栏
//wps.setViewerPreferences(PdfWriter.HideMenubar | PdfWriter.HideToolbar);
doc.Close();
}
catch (Exception ex)
{
log.Error("ToPdf()", ex);
}
}
public void Dispose()
{
if (wps != null) { wps.Quit(); }
}
}
}
注意:使用时如果将public void ToPdf()方法改为public static void ToPdf()时,代码doc.ExportAsFixedFormat(pdfPath, WdExportFormat.wdExportFormatPDF);
处会报异常。