通过使用 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. StringUtils系列之StringUtils.isNotBlank()和StringUtils.isNotBlank()的区别

    /** 1. * StringUtils.isNotBlank(); * 判断参数是否不为空. * 1.如果不为空返回true. * 2.如果为空返回false. * StringUtils.isNo ...

  2. 基于TCP通过socketserver简单实现并发效果

    一.首先介绍一下 socketserver 模块中的类: 类 描述 BaseServer 包含服务器的核心功能与混合(mix-in)类的钩子功能.这个类用于派生,不要直接生成这个类的类对象 TCPSe ...

  3. FreeBSD安装后使用su命令显示sorry的解决办法

    FreeBSD中,可以使用su命令成为root用户,但FreeBSD对执行su命令的用户进行了更严格的限制,能使用su命令的用户必须属于wheel组(root的基本属组,组ID为0),否则就不能通过 ...

  4. springcloud中微服务的优雅停机(已验证)

    大部分项目部署中,为了方便,可能都直接使用kill -9 服务的pid来停掉服务. 但是由于Eureka采用心跳的机制来上下线服务,会导致服务消费者调用此已经kill的服务提供者然后出错. 可以采用以 ...

  5. Spring Cloud 微服务:Eureka+Zuul+Ribbon+Hystrix+SpringConfig实现流程图

    相信现在已经有很多小伙伴已经或者准备使用springcloud微服务了,接下来为大家搭建一个微服务框架,后期可以自己进行扩展.会提供一个小案例: 服务提供者和服务消费者 ,消费者会调用提供者的服务,新 ...

  6. 51nod 2502 最多分成多少块

    小b有个长度为n的数组a,她想将这个数组排序. 然而小b很懒,她觉得对整个数组排序太累了,因此她请你将a分成一些块,使得她只需要对每一块分别排序,就能将整个数组排序. 请问你最多能把a分成多少块. 保 ...

  7. MySQL的增、删、改、查

    数据库的常用命令以及作用 用法 作用 CREATE database 数据库名称. 创建新的数据库 DESCRIBE 表单名称; 描述表单 UPDATE 表单名称 SET attribute=新值 W ...

  8. ZOJ - 3157:Weapon (几何 逆序对)

    pro:给定平面上N条直线,保证没有直线和Y轴平行. 求有多少交点的X坐标落在(L,R)开区间之间,注意在x=L或者R处的不算. sol:求出每条直线与L和R的交点,如果A直线和B直线在(L,R)相交 ...

  9. 检测并修改linux服务器日期

    公司的一个应用服务器license到期了,商务上短时间解决不了.只好将服务器的时间调到去年,临时将就一下. 服务器是vmware虚拟机装的centos,日期每隔一段时间会自动同步,百度了好久,也关闭不 ...

  10. Docker部署nodejs应用并使用PM2作为守护进程

    环境:centos7.6 Docker version 18.06.0-ce mkdir /data cd /data 拉取最新keymetrics/pm2:latest-alpine镜像 docke ...