通过使用 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. sublime text3常用的一些快捷键

    --------------------------------下面的内容可以打印出来贴在电脑旁提醒自己-------------------- Ctrl + Shift + D  快速复制当前的一行 ...

  2. H3C 802.11 WEP加密原理

  3. Gtest:参数化

    转自:玩转Google开源C++单元测试框架Google Test系列(gtest)之四 - 参数化 一.前言 在设计测试案例时,经常需要考虑给被测函数传入不同的值的情况.我们之前的做法通常是写一个通 ...

  4. ab 接口压力测试工具使用

    安装: yum install httpd-tools 使用: ab -n 1000 -c 100 http://www.baidu.com/; -n 总的请求数;  -c 并发数; -k 是否开启长 ...

  5. 学习app开发思路

    1.首先在学习之前进行一次或者是整体或者是部分的检测,当第一次检测就通过,则可以认为是熟练掌握的东西(可以在后期对其进行验证是否是熟练)2.后面的学习过程,对回答的正确与否以及从第一次开始学习到目前为 ...

  6. 数据库迁移Flyway

    为什么需要Flyway 日常开发常常会遇到一些这样的场景 小红开发一个模块在本地数据库增加了两个字段,并且改动了dao层的代码提交到git.这时候小黄拉取了代码Run很可能报错. 如果在上线正式环境的 ...

  7. 本地电脑视频播放器推荐PotPlayer、KMPlayer

    链接:https://pan.baidu.com/s/1aSfBFUtEm_XzDU2HGKDkQw 提取码:7z0d  

  8. WebService(一)

    最近一段时间研究webservice,一般来说,开发java的Webservice经常使用axis2和cxf这两个比较流行的框架 先使用cxf,开发一个完整示例,方便对webservice有一个整体的 ...

  9. gcc分步骤编译的记录

  10. vue解决大文件断点续传

    一.概述 所谓断点续传,其实只是指下载,也就是要从文件已经下载的地方开始继续下载.在以前版本的HTTP协议是不支持断点的,HTTP/1.1开始就支持了.一般断点下载时才用到Range和Content- ...