C#调用WPS转换文档到PDF的的实现代码。

1、WPS安装,最好用这个版本别的版本不清楚,安装Pro Plus2016版本。

https://ep.wps.cn/product/wps-office-download.html

2、添加相关的引用:wpsapiex.dll,etapi.dll,wppapi.dll,wpsapi.dll,目前就发现这几个

3、代码类如下

    /// <summary>/// WPS文件转Pdf类/// </summary>public class ToPdfHelper : IDisposable{/// <summary>/// 是否杀死全部WPS程序/// </summary>public bool IsKillAllWps = false;//Wps的动态对象dynamic wps;/// <summary>/// 初始化类基础信息/// </summary>/// <param name="FilePath">文件路径</param>/// <param name="IsKillAllWps">转换完成后是否杀死全部WPS应用</param>public ToPdfHelper(string FilePath, bool IsKillAllWps = false){if (File.Exists(FilePath)){this.IsKillAllWps = IsKillAllWps;this.FilePath = FilePath;string Extension = Path.GetExtension(FilePath).ToLower();//扩展名 ".aspx"switch (Extension){case "xls":Extension = "KET.Application";break;case "xlsx":Extension = "KET.Application";break;case "ppt":Extension = "KWPP.Application";break;case "pptx":Extension = "KWPP.Application";break;default:Extension = "KWps.Application";break;}Type type = Type.GetTypeFromProgID(Extension);if (type == null){Extension = "wps.Application";type = Type.GetTypeFromProgID("wps.Application");}wps = Activator.CreateInstance(type);//比较完整的一些//WPS文字           KWPS.Aplication//WPS的Excel        KET.Application//WPS的演示文档     KWPP.Application//Word              Word.Application//Excel             Excel.Application//Powerpoint        Powerpoint.Application
            }else{throw new Exception("找不到原文件,请检查!");}}/// <summary>/// 源文件路径/// </summary>public string FilePath { get; set; }/// <summary>/// 使用wps将Word转PDF/// </summary>/// <param name="TargetPath">目标文件路径,不传默认在源文件的所属目录</param>/// <returns>Pdf文件路径</returns>public string WordWpsToPdf(string TargetPath = ""){if (string.IsNullOrEmpty(FilePath)){throw new Exception("请传入文件路径");}//如果没传入文件路径就默认使用源目录if (string.IsNullOrEmpty(TargetPath)){TargetPath = Path.ChangeExtension(FilePath, "pdf");}try{//忽略警告提示wps.DisplayAlerts = false;//用wps 打开word不显示界面dynamic doc = wps.Documents.Open(FilePath, Visible: false);//保存为Pdf
                doc.ExportAsFixedFormat(TargetPath, Word.WdExportFormat.wdExportFormatPDF);//设置隐藏菜单栏和工具栏//wps.setViewerPreferences(PdfWriter.HideMenubar | PdfWriter.HideToolbar);
                doc.Close();doc = null;}catch (Exception e){throw e;}finally{Dispose();}return TargetPath;}/// <summary>/// 使用wps将xls转PDF/// </summary>/// <param name="TargetPath">目标文件路径,不传默认在源文件的所属目录</param>/// <returns>Pdf文件路径</returns>public string XlsWpsToPdf(string TargetPath = ""){if (string.IsNullOrEmpty(FilePath)){throw new Exception("请传入文件路径");}//如果没传入文件路径就默认使用源目录if (string.IsNullOrEmpty(TargetPath)){TargetPath = Path.ChangeExtension(FilePath, "pdf");}try{XlFixedFormatType targetType = XlFixedFormatType.xlTypePDF;object missing = Type.Missing;//忽略警告提示wps.DisplayAlerts = false;//xls 转pdfdynamic doc = wps.Application.Workbooks.Open(FilePath, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);//保存为Pdfdoc.ExportAsFixedFormat(targetType, TargetPath, XlFixedFormatQuality.xlQualityStandard, true, false, missing, missing, missing, missing);//设置隐藏菜单栏和工具栏//wps.setViewerPreferences(PdfWriter.HideMenubar | PdfWriter.HideToolbar);
                doc.Close();doc = null;}catch (Exception e){throw e;}finally{Dispose();}return TargetPath;}/// <summary>/// 使用ppt将xls转PDF/// </summary>/// <param name="TargetPath">目标文件路径,不传默认在源文件的所属目录</param>/// <returns>Pdf文件路径</returns>public string PptWpsToPdf(string TargetPath = ""){if (string.IsNullOrEmpty(FilePath)){throw new Exception("请传入文件路径");}//如果没传入文件路径就默认使用源目录if (string.IsNullOrEmpty(TargetPath)){TargetPath = Path.ChangeExtension(FilePath, "pdf");}try{//忽略警告提示wps.DisplayAlerts = false;//ppt 转pdfdynamic doc = wps.Presentations.Open(FilePath, MsoTriState.msoCTrue,MsoTriState.msoCTrue, MsoTriState.msoCTrue);object missing = Type.Missing;//doc.ExportAsFixedFormat(pdfPath, PpFixedFormatType.ppFixedFormatTypePDF,//    PpFixedFormatIntent.ppFixedFormatIntentPrint,//    MsoTriState.msoCTrue, PpPrintHandoutOrder.ppPrintHandoutHorizontalFirst,//    PpPrintOutputType.ppPrintOutputBuildSlides,//      MsoTriState.msoCTrue, null, PpPrintRangeType.ppPrintAll,"",//      false, false, false, false, false, missing);//保存为Pdf
                doc.SaveAs(TargetPath, PowerPoint.PpSaveAsFileType.ppSaveAsPDF, MsoTriState.msoTrue);//设置隐藏菜单栏和工具栏//wps.setViewerPreferences(PdfWriter.HideMenubar | PdfWriter.HideToolbar);
                doc.Close();doc = null;}catch (Exception e){throw e;}finally{Dispose();}return TargetPath;}/// <summary>/// 支持释放资源可以使用using/// </summary>public void Dispose(){if (wps != null){wps.Quit();//释放掉wps对象wps = null;#region 强制关闭所有wps的功能慎用,尤其是带并发的//强制关闭所有wps进程,解决文件占用的问题if (this.IsKillAllWps){System.Diagnostics.Process[] process = System.Diagnostics.Process.GetProcessesByName("wps");foreach (System.Diagnostics.Process prtemp in process){prtemp.Kill();}} #endregion}}}

3、调用代码如下

        /// <summary>/// 开始转换Pdf/// </summary>private void StatButton_Click(object sender, EventArgs e){if (File.Exists(PdfFileTextBox.Text)&& Path.IsPathRooted(PdfFileTextBox.Text)){Stopwatch sw = new Stopwatch();sw.Start();using (ToPdfHelper Help = new ToPdfHelper(PdfFileTextBox.Text,true)){Help.WordWpsToPdf();}sw.Stop();TimeSpan ts2 = sw.Elapsed;TimeLabel.Text = string.Format("转换使用时间:总共花费{0}ms.", ts2.TotalMilliseconds);}else{MessageBox.Show("文件不存在,检查文件路径是否正常,只支持绝对路径!");}}

posted on 2019-09-10 16:32  零-点 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/tom-cat/p/11498239.html

C#调用WPS转换文档到PDF的的实现代码。相关推荐

  1. Python调用WPS进行文档转换PDF及PDF转图片

    这里是利用WPS进行转换,要先安装WPS. 安装依赖 pip install pypiwin32 代码 #!/usr/bin/python # -*- coding: UTF-8 -*-import ...

  2. 调用WPS服务COM组件转换PDF

    由于从客户有可能上传各中类型的附件,那么在客户实现在线阅览就必须统一格式.基本实现方式就是把所有各种类型文件转换成pdf.然后使用SWFTool把pdf转换成.swf播放文件.在客户端安装flash播 ...

  3. 使用JODConverter转换文档为PDF

    1.JODConverter介绍: JODConverter automates conversions between office document formats using OpenOffic ...

  4. 文档在线预览(二)-使用JODConverter转换文档为PDF

    1.JODConverter介绍: JODConverter automates conversions between office document formats using OpenOffic ...

  5. 通过Jacob调用WPS将office文件转为PDF文件

    访问https://sourceforge.net/projects/jacob-project/ 想要调启Windows里的程序需要对应的dll库,下载之后解压 将符合你电脑的dll文件复制到jdk ...

  6. OpenOffice使用JODConverter转换文档为PDF,报错:invalid officeHome: it doesn't contain soffice.bin:

    configuration.setOfficeHome(); officehome 路径应为openoffice安装路径.我装的是4.所以配置路径应为:D:\\Program Files (x86)\ ...

  7. Word文档转PDF的功能

    最近项目中有用到Word文档转PDF的功能,做了一些尝试,也遇到了一些困难.  下面把尝试的情况记录下来,也希望做过类似工作的童鞋能一起探讨一下.  http://www.iteye.com/topi ...

  8. Java程序实现Word文档转为pdf以及出现的问题解决

    做兽医项目需要用到这种需求,很多程序员都遇到过,有些word文档希望直接在浏览器中打开进行预览,但是浏览器往往不是很配合,直接就提示下载,不像pdf文档,浏览器可以直接进行预览. 1. Word文档转 ...

  9. springboot windows下WORD文档转PDF

    windows环境下word转PDF 一.安装openoffice 我自己在官网上下载openoffice的windows版本和linux版本都非常慢,这里我提供一下我的云盘链接(windows版本) ...

最新文章

  1. 全球互联正在创造一个知识极大丰富和隐私终结的时代
  2. 从数据库到迁移调优,鲲鹏高校行太原站正式启动
  3. 前端开发模式--MV*
  4. sql中union 和 union all的区别
  5. Spring 学习总结 使用静态工厂创建Bean
  6. 数据结构:关于重建二叉树的三种思路
  7. oracle批处理参数调用,bat调用jar包并传入多个参数
  8. 苹果mac电脑修改并快速linux网络配置
  9. jquery select css样式,css配合jquery美化 select
  10. 数据库笔记10:创建与管理视图
  11. TensorFlow学习笔记——自然语言处理
  12. js 让鼠标右下角有一排小字_JS实现跟随鼠标的链接文字提示框效果
  13. 读书笔记之C Primer Plus 6
  14. 面试角度分析:微信里面让你删掉一个功能,你选哪个?
  15. 跳一跳改分php源码,小游戏“跳一跳”居然可改分,微信小程序现漏洞
  16. docker 和 k8s预研
  17. Linux中history的巧用
  18. 去哪儿实习面经(拿到offer)
  19. 视频转动漫软件有哪些?小编亲测6款工具,1秒穿越漫画场景
  20. 三员之三权分立BMB20-2007

热门文章

  1. Debian安装软件报错:Media change: please insert the disc labeled
  2. JS不支持冒泡的事件
  3. 忆享科技戟星安全实验室|内网渗透神器-Viper的基本使用
  4. ASP.NET Core教程
  5. C语言使用说明笔记1.2
  6. Unix socket进程间通信
  7. 软件设计师备考知识点笔记
  8. hasOwnProperty用来干嘛的
  9. idea 错误: 找不到或无法加载主类 java.lang.ClassNotFoundException: com.zhou.DemoApplication
  10. 从开源项目学做微信小程序