本文實例講述了C#實現WPS文件轉PDF格式的方法。分享給大家供大家參考,具體如下:
這里主要是采用C#將wps文件轉為PDF。需要提前安裝好WPS,并在程序中添加引用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 JDOMS.WebAPI.Controllers.Zjn.Utils{ class WpsToPdf : IDisposable { dynamic wps; public WpsToPdf() { //創建wps實例,需提前安裝wps Type type = Type.GetTypeFromProgID("KWps.Application"); wps = Activator.CreateInstance(type); } /// <summary> /// 根據文件在服務器上的路徑下載文件 /// </summary> /// <param name="wpsFilename">Wps文件路徑</param> /// <param name="pdfFilename">Pdf文件路徑</param> /// <returns></returns> public void ToPdf(string wpsFilename, string pdfFilename = null) { if (wpsFilename == null) { throw new ArgumentNullException("wpsFilename"); } if (pdfFilename == null) { pdfFilename = Path.ChangeExtension(wpsFilename, "pdf"); } Console.WriteLine(string.Format(@"正在轉換 [{0}] -> [{1}]", wpsFilename, pdfFilename)); //用wps 打開word不顯示界面 dynamic doc = wps.Documents.Open(wpsFilename, Visible: false); //doc 轉pdf doc.ExportAsFixedFormat(pdfFilename, WdExportFormat.wdExportFormatPDF); doc.Close(); } public void Dispose() { if (wps != null) { wps.Quit(); } } }}
希望本文所述對大家C#程序設計有所幫助。
新聞熱點
疑難解答