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

word 转 pdf,c#代码的更多相关文章

  1. Java代码实现WORD转PDF

    第一步: 安装OpenOffice   在此良心提供windows版本安装文件 链接:https://pan.baidu.com/s/17pPCkcS1C46VtLhevqSgPw  密码:vmlu ...

  2. 使用aspose.word两句代码将word转换为pdf

    //Load Document Document document = new Document(@"C:\Users\Administrator\Desktop\人事---新员工转正总结( ...

  3. C#实现 word、pdf、ppt 转为图片

    office word文档.pdf文档.powerpoint幻灯片是非常常用的文档类型,在现实中经常有需求需要将它们转换成图片 -- 即将word.pdf.ppt文档的每一页转换成一张对应的图片,就像 ...

  4. jacob 操作word转pdf

    项目需要对上传的word及pdf进行在线预览,因基于jquery的pdf插件,很方面实现在线预览,而word实现在线预览费劲不少,于是想到在进行上传处理时,直接将word转成pdf,在预览时直接预览p ...

  5. word、pdf、ppt 转为图片

    office word文档.pdf文档.powerpoint幻灯片是非常常用的文档类型,在现实中经常有需求需要将它们转换成图片 -- 即将word.pdf.ppt文档的每一页转换成一张对应的图片,就像 ...

  6. C#,VB.NET如何将Word转换为PDF和Text

    众所周知,Word是我们日常工作中常用的办公软件之一,有时出于某种需求我们需要将Word文档转换为PDF以及Text.那么如何以C#,VB.NET编程的方式来实现这一功能呢? 下面我将分开介绍如何运用 ...

  7. Jacob工具类使用文件互转服务 word转html html转excel word转pdf excel转pdf ppt转pdf

    前提条件  必须安装MS office 1.jdk使用jdk1.8 2.jacob.dll放在..\jdk1.8\jre\bin目录下 3.eclipse的jre版本要和jdk一致,window-&g ...

  8. python word转pdf

    原理 使用python win32 库 调用word底层vba,将word转成pdf 安装pywin32 pip install pywin32 python代码 from win32com.clie ...

  9. [java,2019-01-15] word转pdf

    word转pdf jar包 <dependency> <groupId>org.docx4j</groupId> <artifactId>docx4j& ...

随机推荐

  1. ABP问题集结

    添加js跨域访问. 在Startup.cs文件中  public IServiceProvider ConfigureServices(IServiceCollection services)中添加 ...

  2. mybatis添加sql打印功能

    添加配置文件: mybatis-config.xml <?xml version="1.0" encoding="UTF-8"?> <!DOC ...

  3. pstree - 树状显示进程信息

    pstree - display a tree of processes(树状结构显示进程关系) 格式: pstree [option] option: -a --arguments:显示每个程序的完 ...

  4. tomcat redis session共享

    编译redis所需要的序列化包 安装 gradle Linux & MacOS users Configure your PATH environment variable to includ ...

  5. PC软件/web网站/小程序/手机APP产品如何增加个人收款接口

    接入前准备 通过 XorPay 注册个人收款接口,原理是帮助你签约支付宝和微信(不需要营业执照)支持个人支付宝和个人微信支付接口,大概几分钟可以开通,开通后即可永久使用 PC 网站接入 效果:用户点击 ...

  6. 变长数组(variable-length array,VLA)(C99)

    处理二维数组的函数有一处可能不太容易理解,数组的行可以在函数调用的时候传递,但是数组的列却只能被预置在函数内部.例如下面这样的定义: #define COLS 4 int sum3d(int ar[] ...

  7. QA流程

    一.测试人员的介入时间 1.当产品经理与业务人员制定需求的时候,测试人员不宜介入: 2.当下一期的需求原型出来以后,这个时候就进入了需求评审.需求分析阶段,此时,测试人员应该介入: 3.当开发人员在编 ...

  8. P4560 [IOI2014]Wall 砖墙

    题目描述 给定一个长度为 nn且初始值全为 00的序列.你需要支持以下两种操作: Add L, R, hL,R,h:将序列 [L, R][L,R]内所有值小于 hh的元素都赋为 hh,此时不改变高度大 ...

  9. Eclipse搭建maven web项目

    最近在做做一个小实验,搭建ssm框架,要求使用maven来统一管理jar包,接下来就看如何建立maven项目,首先必须有要有相应的开发环境:JDK和maven,以及配置tomcat. 开发环境搭建可以 ...

  10. Beta冲刺(2/7)——2019.5.23

    所属课程 软件工程1916|W(福州大学) 作业要求 Beta冲刺(2/7)--2019.5.23 团队名称 待就业六人组 1.团队信息 团队名称:待就业六人组 团队描述:同舟共济扬帆起,乘风破浪万里 ...