dotNet基于office实现word转pdf

2023-10-30

20171228(WordToPdf_byDotNet)

基于Office的实现步骤

主要是利用了 office com 组件中的 Microsoft.Office.Interop.word.dll 动态链接库文件可以通过 c# 代码实现对 word 文件实现另存为 pdf,xml或者其他格式文件一起对word 文件的修改等等。

相关 API 文档可以参考 microsoft 官方 msdn

一、如何 引入 Microsoft.Office.Interop.word.dll 文件

首先本机安装的是 office 2016 版本,找了好久都没有找到 这个动态链接库文件,这一步挺耗费时间的。

具体查找步骤:

  1. 我使用的是 Everything 软件搜索 Microsoft.Office.Interop.word.dll 才找到这个文件
  2. 找到后拷贝到 自己的project 下或者直接引用到项目中

二、 转换代码实现如下

using Word = Microsoft.Office.Interop.Word

string WordFilePath = @"D:\attatch\product\demo.doc";
object paramMissing = Type.Missing;
Word.Application application = new Word Application();
application.Visible = false;
Word.Document document = null;
wordDocument = wordApplication.Documents.Open(WordFilePath, ref paramMissing, true,
                    ref paramMissing, ref paramMissing, ref paramMissing,
                    ref paramMissing, ref paramMissing, ref paramMissing,
                    ref paramMissing, ref paramMissing, ref paramMissing,
                    ref paramMissing, ref paramMissing, ref paramMissing,
                    ref paramMissing);

document.ExportAsFixedFormat(@"D:\attatch\product\demo.pdf",Word.WdExportFormat.wdExportFormatPDF);
// 关闭进程
application.Quit(ref paramMissing, ref paramMissing, ref paramMissing); 

补充

  1. 基于 .net framework 下 word 转换 除了使用office com组件还可以使用 spire.doc,这是收费软件,前三页转换免费的,或者使用 EVOpdf,EVOpdf 中也有word to pdf 插件,不过这是一个收费的应用。

  2. Everything以及 word.dll 文件下载链接

  3. 基于 office com 组件,我们可以实现很多的 关于word,excel的操作

  4. 原理: 我认为后台还是调用了 office 或者 wps 程序,应是 headless 程序,无界面程序。

  5. 其他blog copy的代码


public bool WordToPDF(string sourcePath, string targetPath)
        {
           bool result = false;
           Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application();
           Document document = null;
           try
           {
              application.Visible = false;
              document = application.Documents.Open(sourcePath);
              document.ExportAsFixedFormat(targetPath, WdExportFormat.wdExportFormatPDF);
              result = true;
           }
           catch (Exception e)
           {
              Console.WriteLine(e.Message);
              result = false;
           }
           finally
           {
              document.Close();
           }
           return result;
        }


//将word文档转换成PDF格式
    private bool Convert(string sourcePath, string targetPath, Word.WdExportFormat exportFormat)
    {
        bool result;
        object paramMissing = Type.Missing;
        Word.ApplicationClass wordApplication = new Word.ApplicationClass();
        Word.Document wordDocument = null;
        try
        {
            object paramSourceDocPath = sourcePath;
            string paramExportFilePath = targetPath;

            Word.WdExportFormat paramExportFormat = exportFormat;
            bool paramOpenAfterExport = false;
            Word.WdExportOptimizeFor paramExportOptimizeFor =
                    Word.WdExportOptimizeFor.wdExportOptimizeForPrint;
            Word.WdExportRange paramExportRange = Word.WdExportRange.wdExportAllDocument;
            int paramStartPage = 0;
            int paramEndPage = 0;
            Word.WdExportItem paramExportItem = 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;

            wordDocument = wordApplication.Documents.Open(
                    ref paramSourceDocPath, ref paramMissing, ref paramMissing,
                    ref paramMissing, ref paramMissing, ref paramMissing,
                    ref paramMissing, ref paramMissing, ref paramMissing,
                    ref paramMissing, ref paramMissing, ref paramMissing,
                    ref paramMissing, ref paramMissing, ref paramMissing,
                    ref paramMissing);

            if (wordDocument != null)
                wordDocument.ExportAsFixedFormat(paramExportFilePath,
                        paramExportFormat, paramOpenAfterExport,
                        paramExportOptimizeFor, paramExportRange, paramStartPage,
                        paramEndPage, paramExportItem, paramIncludeDocProps,
                        paramKeepIRM, paramCreateBookmarks, paramDocStructureTags,
                        paramBitmapMissingFonts, paramUseISO19005_1,
                        ref paramMissing);
            result = true;
        }
        finally
        {
            if (wordDocument != null)
            {
                wordDocument.Close(ref paramMissing, ref paramMissing, ref paramMissing);
                wordDocument = null;
            }
            if (wordApplication != null)
            {
                wordApplication.Quit(ref paramMissing, ref paramMissing, ref paramMissing);
                wordApplication = null;
            }
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
        return result;
    }

    //将excel文档转换成PDF格式
    private bool Convert(string sourcePath, string targetPath, XlFixedFormatType targetType)
    {
        bool result;
        object missing = Type.Missing;
        Excel.ApplicationClass application = null;
        Workbook workBook = null;
        try
        {
            application = new Excel.ApplicationClass();
            object target = targetPath;
            object type = targetType;
            workBook = application.Workbooks.Open(sourcePath, missing, missing, missing, missing, missing,
                    missing, missing, missing, missing, missing, missing, missing, missing, missing);

            workBook.ExportAsFixedFormat(targetType, target, XlFixedFormatQuality.xlQualityStandard, true, false, missing, missing, missing, missing);
            result = true;
        }
        catch
        {
            result = false;
        }
        finally
        {
            if (workBook != null)
            {
                workBook.Close(true, missing, missing);
                workBook = null;
            }
            if (application != null)
            {
                application.Quit();
                application = null;
            }
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
        return result;
    }

    //将ppt文档转换成PDF格式
    private bool Convert(string sourcePath, string targetPath, PpSaveAsFileType targetFileType)
    {
        bool result;
        object missing = Type.Missing;
        PowerPoint.ApplicationClass application = null;
        Presentation persentation = null;
        try
        {
            application = new PowerPoint.ApplicationClass();
            persentation = application.Presentations.Open(sourcePath, MsoTriState.msoTrue, MsoTriState.msoFalse, MsoTriState.msoFalse);
            persentation.SaveAs(targetPath, targetFileType, Microsoft.Office.Core.MsoTriState.msoTrue);

            result = true;
        }
        catch
        {
            result = false;
        }
        finally
        {
            if (persentation != null)
            {
                persentation.Close();
                persentation = null;
            }
            if (application != null)
            {
                application.Quit();
                application = null;
            }
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
        return result;
    }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

dotNet基于office实现word转pdf 的相关文章

  • 量子编程入门第一篇环境搭建dotnet-sdk+Microsoft.Quantum.IQSharp+python3.6+qsharp

    量子编程已经提上日程 xff0c 微软提供了quantum开发工具包 Microsoft Quantum Development Kit简称QDK xff0c 在visual studio 2019环境下 xff0c 可以安装quantum
  • 微软 dotnet.core 文档中文链接

    https docs microsoft com zh cn aspnet core
  • 如何在 Ubuntu 20.04 上安装 Dotnet Core

    NET Core 是一个免费的开源软件框架 其设计时考虑了 Linux 和 macOS 它是 NET Framework 的跨平台继承者 适用于 Linux macOS 和 Windows 系统 NET Core 框架已经提供了用于引导项目
  • Session和Cookie实现购物车

    来自森大科技官方博客 http www cnsendblog com index php p 342 GPS平台 网站建设 软件开发 系统运维 找森大网络科技 http cnsendnet taobao com 使用Session和Cook
  • abp OFFSET 附近有语法错误。 在 FETCH 语句中选项 NEXT 的用法无效。

    在学习abp框架时 出现上述错误 这是因为使用了sql server2008 数据库造成端 数据库版本低 可以更改代码 在项目中ctrl f搜索 UseSqlServer 找到如下代码 添加 b gt b UseRowNumberForPa
  • 依赖注入(转载)

    依赖注入那些事儿 转载 依赖注入那些事儿 1 IGame游戏公司的故事 1 1 讨论会 话说有一个叫IGame的游戏公司 正在开发一款ARPG游戏 动作 角色扮演类游戏 如魔兽世界 梦幻西游这一类的游戏 一般这类游戏都有一个基本的功能 就是
  • 学习abp-1-ContosoUniversity Abp版

    1 去abp官网下载模板工程 https aspnetboilerplate com 项目名称为ContosoAbp 这里使用的是net core 3 x 2 x版本在编辑用户时 会报错 打开下载的解决方案 等待nuget还原包 2 数据库
  • visual studio 2019 sql server localdb 数据库中文乱码解决方法

    今天使用localdb学习asp net core时 发现写入localdb数据库的中文为乱码 按照网上的方法解决 却无法显示 这里只有用sql语句更改了 参考这个 但我试了不成功 用sql语句更改可以 https www cnblogs
  • 欢迎来到 C# 9.0(Welcome to C# 9.0)

    C 9 0 已于 2020年11月10日 正式发布了 请点击链接转至 C 9 0 正式发布了 C 9 0 on the record 阅读最新版内容 https mp weixin qq com s b7yd5FoR6jDrhx8K 310
  • 一行代码去掉Devexpress弹窗

    使用的是 net hook方法 使用代码 using System using System Windows Forms namespace AlexDevexpressToolTest static class Program
  • SQL Server连接字符串句法

    Application Name 应用程序名称 应用程序的名称 如果没有被指定的话 它的值为 NET SqlClient Data Provider 数据提供程序 AttachDBFilename extended properties 扩
  • 深入解析Invoke and BeginInvoke, 同步与异步解析

    Invoke and BeginInvoke 本文后面的源代码分析在我的博客园博客 就是此链接 在 Invoke 或者 BeginInvoke 的使用中无一例外地使用了委托 Delegate 至于委托的本质请参考我的另一随笔 对 net事件
  • Ado.Net总结

    ADO NET总结 ADO NET 是在 NET 平台上访问数据库的组件 它是以 ODBC Open Database Connectivity 技术的方式来访问数据库的一种技术 ADO NET常用命名空间 命名空间 数据提供程序 Syst
  • ASP.NET Core WebAPI学习-6

    ASP NET Core WebAPI学习 1 ASP NET Core WebAPI学习 2 ASP NET Core WebAPI学习 3 ASP NET Core WebAPI学习 4 ASP NET Core WebAPI学习 5
  • ASP.NET Core WebAPI学习-1

    Web API学习 ASP NET Core WebAPI学习 1 ASP NET Core WebAPI学习 2 ASP NET Core WebAPI学习 3 ASP NET Core WebAPI学习 4 ASP NET Core W
  • C# 代码规范和质量检查工具 StyleCop.Analyzers

    简介 原来一直用 ReSharper 来进行代码质量检查 不过毕竟是收费的 所以想找个免费的可以推广给公司的同事也一起用 搜索了一下 找到了StyleCop 但是我在 VS 2015里安装 StyleCop 或者通过 Nuget 包安装 S
  • 通过C#学习redis(集合)

    static void Main string args RedisClient cli new RedisClient 127 0 0 1 6379 password defaultDatabase 0 region 集合操作 Redis
  • 学习C# 哈希表(HashTable)用法

    学习C 哈希表 HashTable 用法 1 哈希表 HashTable 简述 在 NET Framework中 Hashtable是System Collections命名空间提供的一个容器 用于处理和表现类似keyvalue的键值对 其
  • ASP.NET Core WebAPI学习-4

    ASP NET Core WebAPI学习 1 ASP NET Core WebAPI学习 2 ASP NET Core WebAPI学习 3 ASP NET Core WebAPI学习 4 ASP NET Core WebAPI学习 5
  • abp去掉AbpUser中的Name,Surname

    abp是国外的框架 默认的框架中的AbpUser表中的Name和Surname是分开的 这不符合国情 可以先去掉 1 在User类中重写Name和Surname 并设置为私有 2 在DbContext类中 重写OnModelCreating

随机推荐

  • AI大模型公开课来了!免费学习!

    Datawhale分享 课程 知乎AI大模型公开课 近几年AI发展迅猛 行业巨头争先布局AI领域 想切入大热的AI领域 却找不到方向 为了帮助大家零成本学习AI大模型技术 特邀一线大佬发起 AI大模型公开课 AI大模型进阶之旅 直播时间 9
  • 蓝桥杯单片机学习5——外部中断

    上期我们学习了独立按键 矩阵按键 这次我们来学习外部中断 蓝桥杯单片机学习 外部中断 中断 1 中断请求源 2 外部中断 3 中断寄存器 4 中断优先级 5 中断结构 6 中断函数 6 中断嵌套 实战环节 1 任务要求 2 代码实现 3 代
  • 伽罗华域GF,GF(256)来源

    Galois Field 1 域 2 域中单位元和逆元 3 有限域GF p p p 4 有限域GF
  • Element ui多选框实现单选且隐藏全选按钮

    添加表格多选框列
  • Solidworks导出URDF总结(Noetic)

    环境 Solidwoks2018 SP0 Solidwoks2021 SP5 Ubuntu20 04 ROS1 Noetic Solidwoks2018 SP0对于平移副有问题 显示不出来 Solidwoks2021 SP5没有问题 官网有
  • windows bat批量创建文件夹与文件

    一 新建bat文件 批量创建 bat echo off for f i in nameList txt do mkdir i copy muban docx i i docx do mkdir i copy muban docx i i d
  • JDK历史所有版本下载地址(附Oracle帐号)

    由于有时在新的电脑或者服务器上需要安装新的JDK 但现在下载JDK已经没有之前方便了 需要登录才能下载 今天在这里我就来把jdk所有的版本下载地址与帐号列出来 方便大家下载 JDK所有版本下载地址 Java SE 14 Java SE 13
  • 逆向工具常用操作

    IDA 加载文件 Windows 下 用IDA加载文件之后 会在文件同目录下生成几个文件 id0 二叉树数据库 id1 文件包含描述每个程序字节的标志 nam 包含IDA Name 窗口的数据库 til 本地数据库有关信息 常用快捷键 快捷
  • 1120 哈夫曼树的创建遍历查找当前节点的编码

    package com import java util ArrayList import java util Collections import java util LinkedList import java util Stack 类
  • 阿里架构精心整理出来一份(Nginx实战.pdf)资料,请签收

    前言 Nginx 很火 因为它就像一个万能药 在任何存在性能需求的场合总能找见它的身影 它可以轻松在百万并发连接下实现高吞吐量的 Web 服务 同时 类似于 OpenResty 和 Tengine 这样的第三方模块群 进一步发展出了新生态
  • sql注入详解

    目录 前言 一 漏洞原因分析 二 漏洞危害 三 sql注入防范 四 如何挖掘sql注入漏洞 五 常见的注入手法 联合查询 union注入 报错注入 基于布尔的盲注 基于时间的盲注 HTTP头注入 宽字节注入 堆叠查询 二阶注入 六 sql注
  • ElsticSearch学习:ElasticSearch基本概念

    ElasticSearch肯定要和我们常用的MySQL这些关系型数据库对比 ES是面向文档的 下面是一个对比 关系型数据库 例如MySQL ElasticSearch 数据库 database 索引 indicies 表 tables ty
  • substr函数用法详解

    substr string start lt length gt 从string的start位置开始提取字符串 length 要提取字符串的长度 若length为以下任意条件之一时 返回start位置到串尾的所有字符 length不指定 l
  • 解决ubuntu(16.04版本)和windows电脑之间无法复制粘贴问题

    1 执行下列命令 sudo apt get autoremove open vm tools sudo apt get install open vm tools desktop 安装过程中 yes或者y一路通过 2 然后重启ubuntu就
  • 七夕王者服务器维护,2017年8月8日维护公告,七夕限量飞行祥瑞冰晶魅灵部分服务器放出...

    原标题 2017年8月8日维护公告 七夕限量飞行祥瑞冰晶魅灵部分服务器放出 亲爱的玩家朋友 为保证服务器的运行稳定和服务质量 梦幻西游 所有服务器将于2017年8月8日上午8 00停机 进行每周例行的维护工作 预计维护时间为上午8 00至9
  • db2常用的时间操作(数据库查询)

    请注意 使用时 请把文中空格替换 文中的空格有误 获取当前日期 select current date from sysibm sysdummy1 values current date 获取当前日期 select current time
  • onnx 模型转换与 onnxruntime 和caffe2 推理速度比较

    onnx 模型转换与 onnxruntime 和caffe2 推理速度比较 背景 1 模型转换 2 PC端运行onnx模型 背景 pytorch 模型通常包括网络结构 py文件和模型参数文件 pth 通常需要转换为onnx格式再向其他终端或
  • 【算法】广度/宽度优先搜索(BFS)

    挺好的一篇文章 讲的挺清楚 广度 宽度优先搜索 BFS 算法入门 郭志伟 SYSU raphealguo at qq com 2012 04 27 1 前言 广度优先搜索 也称宽度优先搜索 缩写BFS 以下采用广度来描述 是连通图的一种遍历
  • 针对VS2019无法登录问题

    摘要 针对VS2019无法登录问题提出一种可行有效的解决方法 VS2019在提供30天试用期后 会要求用户登录后才能使用 但VS2019提供的登录微软账户方法非常不友好 本文将通过更改登录设置方法实现VS2019的简单快捷登录 问题描述 一
  • dotNet基于office实现word转pdf

    20171228 WordToPdf byDotNet 基于Office的实现步骤 主要是利用了 office com 组件中的 Microsoft Office Interop word dll 动态链接库文件可以通过 c 代码实现对 w