word 转 pdf,c#代码
通过使用 C# 控制 office 软件 com 组件转 pdf
1 word 转 pdf
方案二:可以使用 netoffice 进行转换
参考文档:https://netoffice.io/documentation/
api 使用方法和 Microsoft.Office.Interop 的使用方法一致
1)添加需要的引用
引用 右击 -》 添加引用 -》 扩展 -》 Microsoft.Office.Interop.Word、Microsoft.Office.Interop.Excel、Microsoft.Office.Interop.PowerPoint 14.0.0.0 版本
2)设置互操作类型为 false
引用的 word excel powerpoint 属性中 -》 设置嵌入互操作类型为 false
3) 关键代码如下
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using Word = Microsoft.Office.Interop.Word; using Excel = Microsoft.Office.Interop.Excel; using PowerPoint = Microsoft.Office.Interop.PowerPoint; using System.ServiceProcess; namespace firstAppConsole { class OfficeToPdfHandler { public string officeFilename; public OfficeToPdfHandler() { } public OfficeToPdfHandler(string officeFilename) { this.officeFilename = officeFilename; } public void convertWord2Pdf() { printService(); Object missing = Type.Missing; Word.ApplicationClass wordApplication = new Word.ApplicationClass(); Word._Document wordDocument = null; bool confirmConversions = false; bool readOnly = false; bool addToRecentFiles = false; bool visible = false; bool openAndRepair = true; bool noEncodingDialog = true; Word.WdExportFormat exportFormat = Word.WdExportFormat.wdExportFormatPDF; Word.WdExportRange paramExportRange = Word.WdExportRange.wdExportAllDocument; Word.WdExportOptimizeFor exportOptimizeFor = Word.WdExportOptimizeFor.wdExportOptimizeForPrint; int paramStartPage = 0; int paramEndPage = 0; Word.WdExportItem exportItem = Word.WdExportItem.wdExportDocumentContent; bool paramIncludeDocProps = true; bool paramKeepIRM = true; Word.WdExportCreateBookmarks paramCreateBookmarks = Word.WdExportCreateBookmarks.wdExportCreateWordBookmarks; bool paramDocStructureTags = true; bool paramBitmapMissingFonts = true; bool paramUseISO19005_1 = false; string pdfFilename = getPdfFilename(); cleanPdfFile(pdfFilename); if (wordApplication != null) { Console.WriteLine("start application success"); wordApplication.Visible = false; wordApplication.NormalTemplate.Saved = true; try { wordDocument = wordApplication.Documents.Open( officeFilename, confirmConversions, readOnly, addToRecentFiles, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, visible, openAndRepair, ref missing, noEncodingDialog, ref missing); if (wordDocument != null) { wordDocument.ExportAsFixedFormat( pdfFilename, exportFormat, false, exportOptimizeFor, paramExportRange, paramStartPage, paramEndPage, exportItem, paramIncludeDocProps, paramKeepIRM, paramCreateBookmarks, paramDocStructureTags, paramBitmapMissingFonts, paramUseISO19005_1, ref missing); } } catch (Exception ex) { Console.WriteLine(ex); } finally { if (wordDocument != null) { wordDocument.Close(Word.WdSaveOptions.wdDoNotSaveChanges, Word.WdOriginalFormat.wdOriginalDocumentFormat, ref missing); wordDocument = null; } if (wordApplication != null) { wordApplication.Quit(); wordApplication = null; } } } } public static void printService() { var serviceControllers = ServiceController.GetServices(); foreach (var service in serviceControllers) { Console.WriteLine("ServiceName:{0}\t\tServiceStatus:{1}", service.ServiceName, service.Status); } } public OfficeFileType getFileType() { if (String.IsNullOrEmpty(officeFilename)) { throw new Exception("officeFilename is null or empty"); } FileInfo fileInfo = new FileInfo(officeFilename); if (!fileInfo.Exists) { throw new Exception("file not exist:" + officeFilename); } string extension = fileInfo.Extension; switch (extension) { case ".doc": case ".docx": return OfficeFileType.WORD; break; case ".xls": case ".xlsx": return OfficeFileType.EXCEL; break; case ".ppt": case ".pptx": return OfficeFileType.PPT; break; } throw new Exception("can't find officeFilename type:" + officeFilename); } public static void cleanPdfFile(string officeFilename) { string pdfFilename= Path.ChangeExtension(officeFilename, ".pdf"); FileInfo fileInfo = new FileInfo(pdfFilename); if (fileInfo.Exists) { fileInfo.Delete(); } } public string getPdfFilename() { return Path.ChangeExtension(officeFilename, ".pdf"); } } enum OfficeFileType { WORD, EXCEL, PPT } class Program { static void Main(string[] args) { OfficeToPdfHandler officeHandler = new OfficeToPdfHandler(@"D:\logs\创作笔记2018.docx"); officeHandler.convertWord2Pdf(); Console.WriteLine("done"); } } }
2 excel 转 pdf,可以参考上面 word 转 pdf 进行设置
关键代码如下
public void convertExcel2Pdf() { if (officeFilename == null) { return; } string tfn = officeFilename.ToLower(); if (!((tfn.EndsWith(".xls") || tfn.EndsWith(".xlsx")))) { return; } FileInfo fileInfo = new FileInfo(officeFilename); if (!fileInfo.Exists) { return; } Object missing = Type.Missing; Excel._Application excelApplication = new Excel.ApplicationClass(); Excel.Workbook workBook = null; string pdfFilename = getPdfFilename(); cleanPdfFile(pdfFilename); bool readOnly = false; bool ignoreReadOnlyRecommended = true; bool editable = false; bool notify = false; bool addToMru = false; bool local = true; Excel.XlFixedFormatType xlFixedFormatType = Excel.XlFixedFormatType.xlTypePDF; Excel.XlFixedFormatQuality xlFixedFormatQuality = Excel.XlFixedFormatQuality.xlQualityStandard; bool includeDocProperties = true; bool ignorePrintAreas = true; bool openAfterPublish = false; if (excelApplication != null) { Console.WriteLine("excel application start success"); excelApplication.Visible = false; try { workBook = excelApplication.Workbooks.Open( officeFilename, missing, readOnly, missing, missing, missing, ignoreReadOnlyRecommended, Excel.XlPlatform.xlWindows, missing, editable, notify, missing, addToMru, local, missing); workBook.ExportAsFixedFormat( xlFixedFormatType, pdfFilename, xlFixedFormatQuality, includeDocProperties, ignorePrintAreas, missing, missing, openAfterPublish, missing); } catch (Exception e) { Console.WriteLine(e.StackTrace); } finally { if (workBook != null) { workBook.Close(false, missing, missing); workBook = null; } if (excelApplication != null) { excelApplication.Quit(); excelApplication = null; } } } }
学习过程中,难免出错。如果您在阅读过程中遇到不太明白,或者有疑问。欢迎指正...联系邮箱crazyCodeLove@163.com
如果觉得有用,想赞助一下请移步赞助页面:赞助一下