最近遇到一个项目需要把word转成pdf,GOOGLE了一下网上的方案有很多,比如虚拟打印、给word装扩展插件等,这些方案都依赖于ms word程序,在java代码中也得使用诸如jacob或jcom这类Java COM Bridge,使得服务器受限于win平台,而且部署起来也很麻烦。后来在某外文论坛看到了一个openoffice+jodconverter的转换方案,可以用纯的java代码完成转换工作,服务器端需要安装openoffice,但是需求一步额外的操作--需要在服务器上的某个端口提供一个openoffice服务,这对部署起来显得麻烦了点。

偶然机会发现了google code上有一个jodconverter 3,此版完全把2给重构了,它可以帮你创建oo服务监听在指定端口.

以下为官网介绍:

JODConverter automates conversions between office document formats using OpenOffice.org or LibreOffice.

Supported formats include OpenDocument, PDF, RTF, HTML, Word, Excel, PowerPoint, and Flash.

It can be used as a Java library, a command line tool, or a web application.

JODConverter 3.0 requires:

  • Java 1.5 or later
  • OpenOffice.org 3.0.0 or later
  1. package org.artofsolving.jodconverter.sample.web;
  2.  
  3. import java.io.File;
  4. import java.util.logging.Logger;
  5.  
  6. import javax.servlet.ServletContext;
  7.  
  8. import org.apache.commons.fileupload.disk.DiskFileItemFactory;
  9. import org.apache.commons.fileupload.servlet.ServletFileUpload;
  10. import org.artofsolving.jodconverter.OfficeDocumentConverter;
  11. import org.artofsolving.jodconverter.office.ManagedProcessOfficeManager;
  12. import org.artofsolving.jodconverter.office.ManagedProcessOfficeManagerConfiguration;
  13. import org.artofsolving.jodconverter.office.OfficeConnectionMode;
  14. import org.artofsolving.jodconverter.office.OfficeManager;
  15.  
  16. public class WebappContext {
  17.  
  18. public static final String PARAMETER_OFFICE_PORT = "office.port";
  19. public static final String PARAMETER_OFFICE_HOME = "office.home";
  20. public static final String PARAMETER_OFFICE_PROFILE = "office.profile";
  21. public static final String PARAMETER_FILEUPLOAD_FILE_SIZE_MAX = "fileupload.fileSizeMax";
  22.  
  23. private final Logger logger = Logger.getLogger(getClass().getName());
  24.  
  25. private static final String KEY = WebappContext.class.getName();
  26.  
  27. private final ServletFileUpload fileUpload;
  28.  
  29. private final OfficeManager officeManager;
  30. private final OfficeDocumentConverter documentConverter;
  31.  
  32. public WebappContext(ServletContext servletContext) {
  33. DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
  34. String fileSizeMax = servletContext.getInitParameter(PARAMETER_FILEUPLOAD_FILE_SIZE_MAX);
  35. fileUpload = new ServletFileUpload(fileItemFactory);
  36. if (fileSizeMax != null) {
  37. fileUpload.setFileSizeMax(Integer.parseInt(fileSizeMax));
  38. logger.info("max file upload size set to " + fileSizeMax);
  39. } else {
  40. logger.warning("max file upload size not set");
  41. }
  42.  
  43. int officePort = 8100;
  44. String officePortParam = servletContext.getInitParameter(PARAMETER_OFFICE_PORT);
  45. if (officePortParam != null) {
  46. officePort = Integer.parseInt(officePortParam);
  47. }
  48. OfficeConnectionMode connectionMode = OfficeConnectionMode.socket(officePort);
  49. ManagedProcessOfficeManagerConfiguration configuration = new ManagedProcessOfficeManagerConfiguration(connectionMode);
  50. String officeHomeParam = servletContext.getInitParameter(PARAMETER_OFFICE_HOME);
  51. if (officeHomeParam != null) {
  52. configuration.setOfficeHome(new File(officeHomeParam));
  53. }
  54. String officeProfileParam = servletContext.getInitParameter(PARAMETER_OFFICE_PROFILE);
  55. if (officeProfileParam != null) {
  56. configuration.setTemplateProfileDir(new File(officeProfileParam));
  57. }
  58.  
  59. officeManager = new ManagedProcessOfficeManager(configuration);
  60. documentConverter = new OfficeDocumentConverter(officeManager);
  61. }
  62.  
  63. protected static void init(ServletContext servletContext) {
  64. WebappContext instance = new WebappContext(servletContext);
  65. servletContext.setAttribute(KEY, instance);
  66. instance.officeManager.start();
  67. }
  68.  
  69. protected static void destroy(ServletContext servletContext) {
  70. WebappContext instance = get(servletContext);
  71. instance.officeManager.stop();
  72. }
  73.  
  74. public static WebappContext get(ServletContext servletContext) {
  75. return (WebappContext) servletContext.getAttribute(KEY);
  76. }
  77.  
  78. public ServletFileUpload getFileUpload() {
  79. return fileUpload;
  80. }
  81.  
  82. public OfficeManager getOfficeManager() {
  83. return officeManager;
  84. }
  85.  
  86. public OfficeDocumentConverter getDocumentConverter() {
  87. return documentConverter;
  88. }
  89.  
  90. }

在web应用启动时初始化:

  1. package org.artofsolving.jodconverter.sample.web;
  2.  
  3. import javax.servlet.ServletContextEvent;
  4. import javax.servlet.ServletContextListener;
  5.  
  6. public class WebappContextListener implements ServletContextListener {
  7.  
  8. public void contextInitialized(ServletContextEvent event) {
  9. WebappContext.init(event.getServletContext());
  10. }
  11.  
  12. public void contextDestroyed(ServletContextEvent event) {
  13. WebappContext.destroy(event.getServletContext());
  14. }
  15.  
  16. }

转换servlet

  1. package org.artofsolving.jodconverter.sample.web;
  2.  
  3. import java.io.File;
  4. import java.io.FileInputStream;
  5. import java.io.IOException;
  6. import java.io.InputStream;
  7. import java.util.List;
  8. import java.util.logging.Logger;
  9.  
  10. import javax.servlet.ServletException;
  11. import javax.servlet.http.HttpServlet;
  12. import javax.servlet.http.HttpServletRequest;
  13. import javax.servlet.http.HttpServletResponse;
  14.  
  15. import org.apache.commons.fileupload.FileItem;
  16. import org.apache.commons.fileupload.FileUploadException;
  17. import org.apache.commons.fileupload.servlet.ServletFileUpload;
  18. import org.apache.commons.io.FilenameUtils;
  19. import org.apache.commons.io.IOUtils;
  20. import org.artofsolving.jodconverter.DocumentFormat;
  21. import org.artofsolving.jodconverter.OfficeDocumentConverter;
  22.  
  23. public class ConverterServlet extends HttpServlet {
  24.  
  25. private static final long serialVersionUID = -591469426224201748L;
  26.  
  27. private final Logger logger = Logger.getLogger(getClass().getName());
  28.  
  29. @Override
  30. protected void doPost(HttpServletRequest request,
  31. HttpServletResponse response) throws ServletException, IOException {
  32. if (!ServletFileUpload.isMultipartContent(request)) {
  33. response.sendError(HttpServletResponse.SC_FORBIDDEN,
  34. "only multipart requests are allowed");
  35. return;
  36. }
  37.  
  38. WebappContext webappContext = WebappContext.get(getServletContext());
  39. ServletFileUpload fileUpload = webappContext.getFileUpload();
  40. OfficeDocumentConverter converter = webappContext
  41. .getDocumentConverter();
  42.  
  43. String outputExtension = FilenameUtils.getExtension(request
  44. .getRequestURI());
  45.  
  46. FileItem uploadedFile;
  47. try {
  48. uploadedFile = getUploadedFile(fileUpload, request);
  49. } catch (FileUploadException fileUploadException) {
  50. throw new ServletException(fileUploadException);
  51. }
  52. if (uploadedFile == null) {
  53. throw new NullPointerException("uploaded file is null");
  54. }
  55. String inputExtension = FilenameUtils.getExtension(uploadedFile
  56. .getName());
  57.  
  58. String baseName = FilenameUtils.getBaseName(uploadedFile.getName());
  59. File inputFile = File.createTempFile(baseName, "." + inputExtension);
  60. writeUploadedFile(uploadedFile, inputFile);
  61. File outputFile = File.createTempFile(baseName, "." + outputExtension);
  62. try {
  63. DocumentFormat outputFormat = converter.getFormatRegistry()
  64. .getFormatByExtension(outputExtension);
  65. long startTime = System.currentTimeMillis();
  66. converter.convert(inputFile, outputFile);
  67. long conversionTime = System.currentTimeMillis() - startTime;
  68. logger.info(String.format(
  69. "successful conversion: %s [%db] to %s in %dms",
  70. inputExtension, inputFile.length(), outputExtension,
  71. conversionTime));
  72. response.setContentType(outputFormat.getMediaType());
  73. response.setHeader("Content-Disposition", "attachment; filename="
  74. + baseName + "." + outputExtension);
  75. sendFile(outputFile, response);
  76. } catch (Exception exception) {
  77. logger.severe(String.format(
  78. "failed conversion: %s [%db] to %s; %s; input file: %s",
  79. inputExtension, inputFile.length(), outputExtension,
  80. exception, inputFile.getName()));
  81. throw new ServletException("conversion failed", exception);
  82. } finally {
  83. outputFile.delete();
  84. inputFile.delete();
  85. }
  86. }
  87.  
  88. private void sendFile(File file, HttpServletResponse response)
  89. throws IOException {
  90. response.setContentLength((int) file.length());
  91. InputStream inputStream = null;
  92. try {
  93. inputStream = new FileInputStream(file);
  94. IOUtils.copy(inputStream, response.getOutputStream());
  95. } finally {
  96. IOUtils.closeQuietly(inputStream);
  97. }
  98. }
  99.  
  100. private void writeUploadedFile(FileItem uploadedFile, File destinationFile)
  101. throws ServletException {
  102. try {
  103. uploadedFile.write(destinationFile);
  104. } catch (Exception exception) {
  105. throw new ServletException("error writing uploaded file", exception);
  106. }
  107. uploadedFile.delete();
  108. }
  109.  
  110. private FileItem getUploadedFile(ServletFileUpload fileUpload,
  111. HttpServletRequest request) throws FileUploadException {
  112. @SuppressWarnings("unchecked")
  113. List<FileItem> fileItems = fileUpload.parseRequest(request);
  114. for (FileItem fileItem : fileItems) {
  115. if (!fileItem.isFormField()) {
  116. return fileItem;
  117. }
  118. }
  119. return null;
  120. }
  121.  
  122. }

【转载】Java实现word转pdf的更多相关文章

  1. [转载]java实现word转pdf

    最近遇到一个项目需要把word 转成pdf,百度了一下网上的方案有很多,比如虚拟打印.给word 装扩展插件等,这些方案都依赖于ms word 程序,在java代码中也得使用诸如jacob或jcom这 ...

  2. 利用aspose-words 实现 java中word转pdf文件

    利用aspose-words  实现 java中word转pdf文件 首先下载aspose-words-15.8.0-jdk16.jar包 引入jar包,编写Java代码 package test; ...

  3. java 实现word 转 pdf

    java 实现word  转 pdf 不知道网上为啥道友们写的这么复杂  ,自己看到过一篇还不错的  , 自己动手改了改 ,测试一下可以用  , 希望大家可以参考一下 , 对大家有帮助 1.引入jar ...

  4. Linux系统下Java 转换Word到PDF时,结果文档内容乱码的解决方法

    本文分享在Linux系统下,通过Java 程序代码将Word转为PDF文档时,结果文档内容出现乱码该如何解决.具体可参考如下内容: 1.问题出现的背景 在Windows系统中,使用Spire.Doc ...

  5. java实现word转pdf在线预览(前端使用PDF.js;后端使用openoffice、aspose)

    背景 之前一直是用户点击下载word文件到本地,然后使用office或者wps打开.需求优化,要实现可以直接在线预览,无需下载到本地然后再打开. 随后开始上网找资料,网上资料一大堆,方案也各有不同,大 ...

  6. Java 将Word转为PDF、PNG、SVG、RTF、XPS、TXT、XML

    同一文档在不同的编译或阅读环境中,需要使用特定的文档格式来打开,通常需要通过转换文档格式的方式来实现.下面将介绍在Java程序中如何来转换Word文档为其他几种常见文档格式,如PDF.图片png.sv ...

  7. [java,2019-01-15] word转pdf

    word转pdf jar包 <dependency> <groupId>org.docx4j</groupId> <artifactId>docx4j& ...

  8. Java 将word转为pdf jacob方式

    package com.doctopdf; import java.io.File; import com.jacob.activeX.ActiveXComponent; import com.jac ...

  9. [原创]java实现word转pdf

    最近遇到一个项目需要把word 转成pdf,百度了一下网上的方案有很多,比如虚拟打印.给word 装扩展插件等,这些方案都依赖于ms word 程序,在java代码中也得使用诸如jacob或jcom这 ...

  10. java 将word转为PDF (100%与word软件转换一样)

    jdk环境:jdk_8.0.1310.11_64    (64位) 1.引入pom文件 <!-- word转pdf(依赖windows本地的wps) --> <dependency& ...

随机推荐

  1. 关于如何利用js判断IE浏览器各种版本问题

    <!--[if IE 6]> IE 浏览器版本 6 <![endif]-->   <!--[if IE 7]> IE 浏览器版本 7 <![endif]--& ...

  2. 30.es增删改内部分发原理

    当客户端发送一次请求时,大致会经过以下几个步骤     (1)客户端发送一个请求过去,es的一个node接收到这个请求(随机的),这个node就被es内部分配成coordinating node(协调 ...

  3. sqlalchemy带条件查询相关应用

    sqlalchemy带条件查询 filter_by与filter filter_by 与filter的区别: 1. filter_by只能取值= filter可以==,!=,>=,<=等多 ...

  4. Python 实现把 .cvs 文件保存为 Excel 文件

    # 导入可以把 CVS 转换为 Excel 的外部模块 import pandas as pd # 读出 csv 文件的内容 csv = pd.read_csv('Data.csv', encodin ...

  5. Request中通过文件流获取文件

    第一次写博客,希望能帮到以后接触到这里的同学,废话不多说,面对疾风吧. /** * 获取文件相信信息 * @param request HttpServletRequest实例 * @param im ...

  6. 如何实现网卡bond

    https://jingyan.baidu.com/article/375c8e19da666325f2a229f7.html

  7. ROA与SOA概念

    SOA:面向服务的架构,可以理解为从客户的角度,将软件设计为模块式结构,可以根据用户的需要自由添加.定制模块,偏重于向用户靠拢 ROA:面向资源的架构,从资源的角度,严格按照计算机规范设计软件,偏重科 ...

  8. J - Assign the task

    J - Assign the task HDU - 3974 思路:一眼秒思路<(* ̄▽ ̄*)/ dfs序+线段树. 通过dfs序把树上问题转化成线段上的问题.然后用线段树解决.    错因:都 ...

  9. Java 代理学习笔记

    http://blog.csdn.net/mr_seaturtle_/article/details/52686516

  10. LAS文件转TXT文件

    LAS文件转TXT文件 https://www.liblas.org/start.html