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 = ;
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#代码的更多相关文章
- Java代码实现WORD转PDF
第一步: 安装OpenOffice 在此良心提供windows版本安装文件 链接:https://pan.baidu.com/s/17pPCkcS1C46VtLhevqSgPw 密码:vmlu ...
- 使用aspose.word两句代码将word转换为pdf
//Load Document Document document = new Document(@"C:\Users\Administrator\Desktop\人事---新员工转正总结( ...
- C#实现 word、pdf、ppt 转为图片
office word文档.pdf文档.powerpoint幻灯片是非常常用的文档类型,在现实中经常有需求需要将它们转换成图片 -- 即将word.pdf.ppt文档的每一页转换成一张对应的图片,就像 ...
- jacob 操作word转pdf
项目需要对上传的word及pdf进行在线预览,因基于jquery的pdf插件,很方面实现在线预览,而word实现在线预览费劲不少,于是想到在进行上传处理时,直接将word转成pdf,在预览时直接预览p ...
- word、pdf、ppt 转为图片
office word文档.pdf文档.powerpoint幻灯片是非常常用的文档类型,在现实中经常有需求需要将它们转换成图片 -- 即将word.pdf.ppt文档的每一页转换成一张对应的图片,就像 ...
- C#,VB.NET如何将Word转换为PDF和Text
众所周知,Word是我们日常工作中常用的办公软件之一,有时出于某种需求我们需要将Word文档转换为PDF以及Text.那么如何以C#,VB.NET编程的方式来实现这一功能呢? 下面我将分开介绍如何运用 ...
- 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 ...
- python word转pdf
原理 使用python win32 库 调用word底层vba,将word转成pdf 安装pywin32 pip install pywin32 python代码 from win32com.clie ...
- [java,2019-01-15] word转pdf
word转pdf jar包 <dependency> <groupId>org.docx4j</groupId> <artifactId>docx4j& ...
随机推荐
- cookie登录及其保存
requests中request携带cookie请求1 将一个Session实例的cookies属性设置赋值成 一个 CookieJar 实例 import http.cookiejar s = re ...
- Linux指令(文件目录类)
pwd 显示当前工作目录的绝对路径 ls [选项] [目录或是文件] 常用选项 -a 显示当前目录所有的文件和目录,包括隐藏的 -l 以列表的方式显示信息 cd [参数] (功能描述:切换到指定目录) ...
- JSON的Go解析
JSON(Javascript Object Notation)是一种轻量级的数据交换语言,以文字为基础,具有自我描述性且易于让人阅读.尽管JSON是Javascript的一个子集,但JSON是独立于 ...
- 快速部署ldap服务
快速部署ldap服务 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 一.LDAP概述 .什么是目录服务 ()目录是一类为了浏览和搜索数据二十几的特殊的数据库,例如:最知名的的微软公 ...
- 基于CentOS7配置ArcGIS enterprise
Centos7GUI安装过程 1.右键点击列表中的虚拟主机,打开控制台. 点击绿色开机键,开始安装. 这里有一个很关键的点,就是上一步设置中的打开电源自动连接.一开始设置的时候别忘了. 2.开机后会出 ...
- js插件---videojs的使用
js插件---videojs的使用 一.总结 一句话总结: 网上有各种细致的现成的代码可以拿来用,没必要自己死专 1.video.js有两种初始化方式? 一种是在video的html标签之中 一种是使 ...
- 51nod 1254 最大子段和 V2
N个整数组成的序列a[1],a[2],a[3],…,a[n],你可以对数组中的一对元素进行交换,并且交换后求a[1]至a[n]的最大子段和,所能得到的结果是所有交换中最大的.当所给的整数均为负数时和为 ...
- evpp tcp server服务端
// netserver.cpp : 定义控制台应用程序的入口点. // #include "stdafx.h" #include <evpp/tcp_server.h> ...
- Python练习题——用列表的方法输出杨辉三角
def main(): num = int(input('请输入行数: ')) yh = [[]] * num #创建num行空列表 for row in range(len(yh)): #遍历每一行 ...
- python通过LXML库读取xml命名空间
xml实例版本: <a> <city:table xmlns:city="city"> <heilongjiang name="citys& ...