C#实现Word转PDF

本文主要是采用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);
        }

        /// 
        /// Word转PDF
        /// 
        /// Wps文件路径
        /// Pdf文件路径
        /// 
        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);处会报异常

你可能感兴趣的:(管理系统常用功能实现方式)