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. ContentObserver类的使用
  2. REST 在 Java 中的使用
  3. 关于Increased rates of convergence through learning rate adaptation一文的理解
  4. java访问远程共享文件
  5. esp32 arduino adc_英雄联盟手游射手出装怎么出 adc英雄出装推荐
  6. html5页面主题,HTML5页面开发笔记
  7. ElasticSearch关于映射mapping介绍
  8. 如何设计好分布式数据库,这个策略很重要
  9. (7)Zynq AXI_GP接口介绍
  10. select下拉框如何触发函数并传递参数
  11. 两个有序链表序列的交集_剑指offer第21天:合并两个有序链表
  12. 能源管理零代码开发工具
  13. 苹果绕id工具_绕ID教程(iOS13.313.3.1)
  14. vue2项目中给echarts地图设置背景图和打点
  15. 计算机显卡怎样安装方法,台式机显卡怎么安装?教您安装方法
  16. 腾讯云服务器无限流量,腾讯云服务器有流量限制吗,您看仔细了
  17. 正弦信号频谱分析实验
  18. rand函数和srand函数的用法和区别
  19. psid mysql_eclipse连接MYSQL,保存数据到mysql里,哪出错了?
  20. 77go论坛性能测试

热门文章

  1. ChatGPT 辅助生成PPT
  2. 什么是Java内存模型?为什么会引发线程安全问题?
  3. 融合通信技术趋势和演进方向
  4. 防丢器拆解对比,小小防丢器内部大有乾坤
  5. Labeled LDA(有监督)主题模型的理解、推理与编程
  6. python sklearn metrics_sklearn.metrics中的评估方法
  7. 注册公司的手续及程序
  8. 某查询企业信息平台的接口破解记录
  9. html+js仿百度搜索框,点击和回车跳转百度搜索
  10. isalpha()库函数