Office文档转pdf格式(二)
上一篇我们使用的是微软的Office组件将Word、Excel、Powerpoint转为pdf格式,本文将使用WPS Office组件进行转换。步骤如下:
① 添加WPS组件相关引用
注:wpsapi.dll 对应的是Word 文件API;etapi.dll 对应的是Excel 文件API;wppapi 对应的是PPT 文件API;
② 编写Office帮助类

public class WPSOfficeHelper { /// <summary> /// Word转换为pdf文件,适合(.doc、.docx、.mht、.htm文件类型) /// </summary> /// <param name="sourceFileName">源文件</param> /// <param name="targetFileName">目标文件</param> /// <returns></returns> public static bool WordToPdf(string sourceFileName, string targetFileName) { Word.Application wordApp = new Word.Application(); Word._Document wordDoc = null; try { wordApp.Visible = false; wordDoc = wordApp.Documents.Open(sourceFileName, false, true); wordDoc.ExportAsFixedFormat(targetFileName, Word.WdExportFormat.wdExportFormatPDF); return true; } catch (Exception ex) { return false; } finally { if (wordDoc != null) { wordDoc.Close(false); wordDoc = null; } if (wordApp != null) { wordApp.Quit(false); wordApp = null; } } } /// <summary> /// Excel转换为pdf文件 /// </summary> /// <param name="sourceFileName">源文件</param> /// <param name="targetFileName">目标文件</param> /// <returns></returns> public static bool ExcelToPdf(string sourceFileName,string targetFileName) { Excel.Application excelApp = new Excel.Application(); Excel._Workbook excelDoc = null; try { excelApp.Visible = false; excelDoc = excelApp.Workbooks.Open(sourceFileName, false, true); excelDoc.ExportAsFixedFormat(Excel.XlFixedFormatType.xlTypePDF, targetFileName); return true; } catch (Exception ex) { return false; } finally { if (excelDoc != null) { excelDoc.Close(false); excelDoc = null; } if (excelApp != null) { excelApp.Quit(); excelApp = null; } } } /// <summary> /// PPT转换为pdf文件 /// </summary> /// <param name="sourceFileName">源文件</param> /// <param name="targetFileName">目标文件</param> /// <returns></returns> public static bool PPTToPdf(string sourceFileName, string targetFileName) { PowerPoint.Application pptApp = new PowerPoint.Application(); PowerPoint.Presentation pptDoc = null; try { pptDoc = pptApp.Presentations.Open(sourceFileName); pptDoc.ExportAsFixedFormat(targetFileName,PowerPoint.PpFixedFormatType.ppFixedFormatTypePDF); return true; } catch (Exception ex) { return false; } finally { if (pptDoc != null) { pptDoc.Close(); pptDoc = null; } if (pptApp != null) { pptApp.Quit(); pptApp = null; } } } }
最后,就可以调用进行转换了。
注意:
①该方式目前只能用于Windows系统
②该方式依赖WPS Office软件
③在.net framework和.net core的项目下均可使用(以Win Form项目为例)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· 字符编码:从基础到乱码解决
· Open-Sora 2.0 重磅开源!