当前位置:   article > 正文

用Java实现office(word,excel)转换为PDF文件(提供源码及一键部署)_.java中实现docx转pdf文件的方法

.java中实现docx转pdf文件的方法

用Java实现office文件转换为PDF。研究了一下主要有以下几种方式:

1.使用openoffice,这个可以再linux系统中使用。但是这个据说对于样式复杂的office文件,转换的效果并不好。(但是linux下仍然推荐使用这个)

2.使用POI技术+itext技术。这个样式设计比较繁琐,并且样式效果也不是太好。

3.jacob技术,也是本文要讲解的技术。这个的实现思路是通过Java代码控制Windows系统上的office软件,进行转换。(仅限Windows服务器)

前期的准备工作:

1.下载jacob的相关jar包。里面主要包含jacob.jar和jacob-1.18-x64.dll,jacob-1.18-x86.dll三个文件。先将jar包引入到工程中,然后启动工程会报错,根据提示的错误信息,将指定的dll文件,加到当前jdk/jre/bin目录下即可。查看当前jdk安装路径的方法:通过配置的环境变量去查看所在目录。(注意引入的文件名要与报错的信息保持一致)

下载地址: http://sourceforge.net/project/jacob-project(该地址可能不能用了,自行寻找吧)

2.excel转PDF的话,一般要安装savapdf的插件。去下载SaveAsPDFandXPS.exe并一步步安装。

3.Excel转PDF,还容易报缺少打印机的错误。去Windows的本地服务里开启print spooler服务

4.excel转PDF,还容易出现PDF显示不全的问题。解决的方法是,打开Excel,然后分页预览,将两条蓝色的边线,分别拉倒两侧,(当前文件有多宽,就设置多宽)然后保存。参考https://jingyan.baidu.com/article/48b558e3266ab17f38c09ac0.html

5.准备其他需要的jar包。有poi-ooxml-3.9.jar,poi-3.9.jar,ooxml-schemas-1.1.jar,dom4j-2.0.0-RC1.jar

准备工作做完了,就上代码了:

  1. import java.io.File;
  2. import org.apache.poi.POIXMLDocument;
  3. import org.apache.poi.xwpf.usermodel.XWPFDocument;
  4. import org.dom4j.Document;
  5. import org.dom4j.DocumentException;
  6. import org.dom4j.io.SAXReader;
  7. import com.jacob.activeX.ActiveXComponent;
  8. import com.jacob.com.ComThread;
  9. import com.jacob.com.Dispatch;
  10. import com.jacob.com.Variant;
  11. public class Office2pdf {
  12. static final int wdFormatPDF = 17;// PDF 格式
  13. /**
  14. * word转化为PDF
  15. * @param sfileName
  16. * @param toFileName
  17. * @return
  18. * @throws Exception
  19. * @author ygl
  20. */
  21. public static int word2Pdf(String sfileName,String toFileName) throws Exception{
  22. System.out.println("启动Word...");
  23. long start = System.currentTimeMillis();
  24. ActiveXComponent app = null;
  25. Dispatch doc = null;
  26. try {
  27. app = new ActiveXComponent("Word.Application");
  28. app.setProperty("Visible", new Variant(false));
  29. // 打开word文件
  30. Dispatch docs = app.getProperty("Documents").toDispatch();
  31. // doc = Dispatch.call(docs, "Open" , sourceFile).toDispatch();
  32. doc = Dispatch.invoke(docs,"Open",Dispatch.Method,new Object[] {
  33. sfileName, new Variant(false),new Variant(true) }, new int[1]).toDispatch();
  34. System.out.println("打开文档..." + sfileName);
  35. System.out.println("转换文档到PDF..." + toFileName);
  36. File tofile = new File(toFileName);
  37. // System.err.println(getDocPageSize(new File(sfileName)));
  38. if (tofile.exists()) {
  39. tofile.delete();
  40. }
  41. // Dispatch.call(doc, "SaveAs", destFile, 17);
  42. // 作为html格式保存到临时文件::new Variant(8)其中8表示word转html;7表示word转txt;44表示Excel转html;17表示word转成pdf。
  43. Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {
  44. toFileName, new Variant(17) }, new int[1]);
  45. long end = System.currentTimeMillis();
  46. System.out.println("转换完成..用时:" + (end - start) + "ms.");
  47. } catch (Exception e) {
  48. e.printStackTrace();
  49. System.out.println("========Error:文档转换失败:" + e.getMessage());
  50. }catch(Throwable t){
  51. t.printStackTrace();
  52. } finally {
  53. // 关闭word
  54. Dispatch.call(doc,"Close",false);
  55. System.out.println("关闭文档");
  56. if (app != null)
  57. app.invoke("Quit", new Variant[] {});
  58. }
  59. //如果没有这句winword.exe进程将不会关
  60. ComThread.Release();
  61. return 1;
  62. }
  63. private static Document read(File xmlFile) throws DocumentException {
  64. SAXReader saxReader = new SAXReader();
  65. return saxReader.read(xmlFile);
  66. }
  67. public int getDocPageSize(String filePath) throws Exception {
  68. XWPFDocument docx = new XWPFDocument(POIXMLDocument.openPackage(filePath));
  69. int pages = docx.getProperties().getExtendedProperties().getUnderlyingProperties().getPages();//总页
  70. int wordCount = docx.getProperties().getExtendedProperties().getUnderlyingProperties().getCharacters();// 忽略空格的字符另外还有getCharactersWithSpaces()方法获取带空格的总字数�?
  71. System.out.println ("pages=" + pages + " wordCount=" + wordCount);
  72. return pages;
  73. }
  74. /**
  75. * excle转PDF
  76. * @param els
  77. * @param pdf
  78. * @author ygl
  79. */
  80. public static void excel2Pdf(String inFilePath, String outFilePath) throws Exception {
  81. ActiveXComponent ax = null;
  82. Dispatch excel = null;
  83. try {
  84. ComThread.InitSTA();
  85. ax = new ActiveXComponent("Excel.Application");
  86. ax.setProperty("Visible", new Variant(false));
  87. ax.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏
  88. Dispatch excels = ax.getProperty("Workbooks").toDispatch();
  89. Object[] obj = new Object[]{
  90. inFilePath,
  91. new Variant(false),
  92. new Variant(false)
  93. };
  94. excel = Dispatch.invoke(excels, "Open", Dispatch.Method, obj, new int[9]).toDispatch();
  95. File tofile = new File(outFilePath);
  96. // System.err.println(getDocPageSize(new File(sfileName)));
  97. if (tofile.exists()) {
  98. tofile.delete();
  99. }
  100. // 转换格式
  101. Object[] obj2 = new Object[]{
  102. new Variant(0), // PDF格式=0
  103. outFilePath,
  104. new Variant(0) //0=标准 (生成的PDF图片不会变模糊) ; 1=最小文件
  105. };
  106. Dispatch.invoke(excel, "ExportAsFixedFormat", Dispatch.Method,obj2, new int[1]);
  107. System.out.println("转换完毕!");
  108. } catch (Exception es) {
  109. es.printStackTrace();
  110. throw es;
  111. } finally {
  112. if (excel != null) {
  113. Dispatch.call(excel, "Close", new Variant(false));
  114. }
  115. if (ax != null) {
  116. ax.invoke("Quit", new Variant[] {});
  117. ax = null;
  118. }
  119. ComThread.Release();
  120. }
  121. }
  122. public static void main(String[] args) throws Exception {
  123. word2Pdf("d:\\222.docx", "d:\\222.pdf");
  124. excel2Pdf("d:\\44.xlsx", "d:\\44.pdf");
  125. }
  126. }

注意:Excel转换为PDF只能转换第一个sheet。

另附,我自己写的现成的工程,及bat文件。一键启动,无需更改,方便快捷。https://download.csdn.net/download/qq_29281307/10668558

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/人工智能uu/article/detail/743039
推荐阅读
相关标签
  

闽ICP备14008679号