通过使用 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 = ;
int paramEndPage = ;
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;
}
} } }

最新文章

  1. javascript内建对象
  2. 《Effective C++》读书摘要
  3. 前台传来的文件通过流stream转成bytes 再把文件写入数据库 类型是blob
  4. Hadoop新生报到(一) hadoop2.6.0伪分布式配置详解
  5. Selenium_WebDriver_定位元素
  6. May 26. 2018 Week 21st Saturday
  7. NEST - 返回部分文档
  8. Mybatis抛出:Cannot obtain primary key information from the database, generated objects may be incomplete
  9. day 06 字符串和列表的方法
  10. MDX 脚本语句 -- Scope
  11. SharePoint 2019 离线安装准备工具
  12. 十二 总结JS原型
  13. 【转】【java】论integer是地址传递还是值传递
  14. 转(C# 类似右键菜单弹出窗体)
  15. WPF中的命令简介
  16. PHP 连接oracle
  17. Vs2012 编写代码规则
  18. Mysql安装过程中出现apply security settings错误的解决方法
  19. PHP结合zyupload多功能图片上传实例
  20. 【资料】wod烟草

热门文章

  1. day 10 预科
  2. JanusGraph多图配置 (cassandra)
  3. node基础学习——http基础知识-02-http响应数据流
  4. 从输入 URL 到页面展示到底发生了什么?
  5. KVM网络
  6. .pro文件部分命令详解
  7. gulp-htmlmin 页面压缩插件 gulp插件 参数说明
  8. LeetCode 1046. Last Stone Weight
  9. yolov1详细讲解
  10. 洛谷 P1908 逆序对 题解