上一篇我们使用的是微软的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; } } } }View Code
最后,就可以调用进行转换了。
注意:
①该方式目前只能用于Windows系统
②该方式依赖WPS Office软件
③在.net framework和.net core的项目下均可使用(以Win Form项目为例)
标签:false,Word,Office,Excel,return,文档,pdf,null,string From: https://www.cnblogs.com/Artizan/p/17804833.html