最近遇到一个项目需要把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
package org.artofsolving.jodconverter.sample.web;

import java.io.File;
import java.util.logging.Logger; import javax.servlet.ServletContext; import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.ManagedProcessOfficeManager;
import org.artofsolving.jodconverter.office.ManagedProcessOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeConnectionMode;
import org.artofsolving.jodconverter.office.OfficeManager; public class WebappContext { public static final String PARAMETER_OFFICE_PORT = "office.port";
public static final String PARAMETER_OFFICE_HOME = "office.home";
public static final String PARAMETER_OFFICE_PROFILE = "office.profile";
public static final String PARAMETER_FILEUPLOAD_FILE_SIZE_MAX = "fileupload.fileSizeMax"; private final Logger logger = Logger.getLogger(getClass().getName()); private static final String KEY = WebappContext.class.getName(); private final ServletFileUpload fileUpload; private final OfficeManager officeManager;
private final OfficeDocumentConverter documentConverter; public WebappContext(ServletContext servletContext) {
DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
String fileSizeMax = servletContext.getInitParameter(PARAMETER_FILEUPLOAD_FILE_SIZE_MAX);
fileUpload = new ServletFileUpload(fileItemFactory);
if (fileSizeMax != null) {
fileUpload.setFileSizeMax(Integer.parseInt(fileSizeMax));
logger.info("max file upload size set to " + fileSizeMax);
} else {
logger.warning("max file upload size not set");
} int officePort = 8100;
String officePortParam = servletContext.getInitParameter(PARAMETER_OFFICE_PORT);
if (officePortParam != null) {
officePort = Integer.parseInt(officePortParam);
}
OfficeConnectionMode connectionMode = OfficeConnectionMode.socket(officePort);
ManagedProcessOfficeManagerConfiguration configuration = new ManagedProcessOfficeManagerConfiguration(connectionMode);
String officeHomeParam = servletContext.getInitParameter(PARAMETER_OFFICE_HOME);
if (officeHomeParam != null) {
configuration.setOfficeHome(new File(officeHomeParam));
}
String officeProfileParam = servletContext.getInitParameter(PARAMETER_OFFICE_PROFILE);
if (officeProfileParam != null) {
configuration.setTemplateProfileDir(new File(officeProfileParam));
} officeManager = new ManagedProcessOfficeManager(configuration);
documentConverter = new OfficeDocumentConverter(officeManager);
} protected static void init(ServletContext servletContext) {
WebappContext instance = new WebappContext(servletContext);
servletContext.setAttribute(KEY, instance);
instance.officeManager.start();
} protected static void destroy(ServletContext servletContext) {
WebappContext instance = get(servletContext);
instance.officeManager.stop();
} public static WebappContext get(ServletContext servletContext) {
return (WebappContext) servletContext.getAttribute(KEY);
} public ServletFileUpload getFileUpload() {
return fileUpload;
} public OfficeManager getOfficeManager() {
return officeManager;
} public OfficeDocumentConverter getDocumentConverter() {
return documentConverter;
} }

在web应用启动时初始化:

package org.artofsolving.jodconverter.sample.web;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener; public class WebappContextListener implements ServletContextListener { public void contextInitialized(ServletContextEvent event) {
WebappContext.init(event.getServletContext());
} public void contextDestroyed(ServletContextEvent event) {
WebappContext.destroy(event.getServletContext());
} }

转换servlet

package org.artofsolving.jodconverter.sample.web;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.logging.Logger; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.artofsolving.jodconverter.DocumentFormat;
import org.artofsolving.jodconverter.OfficeDocumentConverter; public class ConverterServlet extends HttpServlet { private static final long serialVersionUID = -591469426224201748L; private final Logger logger = Logger.getLogger(getClass().getName()); @Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
if (!ServletFileUpload.isMultipartContent(request)) {
response.sendError(HttpServletResponse.SC_FORBIDDEN,
"only multipart requests are allowed");
return;
} WebappContext webappContext = WebappContext.get(getServletContext());
ServletFileUpload fileUpload = webappContext.getFileUpload();
OfficeDocumentConverter converter = webappContext
.getDocumentConverter(); String outputExtension = FilenameUtils.getExtension(request
.getRequestURI()); FileItem uploadedFile;
try {
uploadedFile = getUploadedFile(fileUpload, request);
} catch (FileUploadException fileUploadException) {
throw new ServletException(fileUploadException);
}
if (uploadedFile == null) {
throw new NullPointerException("uploaded file is null");
}
String inputExtension = FilenameUtils.getExtension(uploadedFile
.getName()); String baseName = FilenameUtils.getBaseName(uploadedFile.getName());
File inputFile = File.createTempFile(baseName, "." + inputExtension);
writeUploadedFile(uploadedFile, inputFile);
File outputFile = File.createTempFile(baseName, "." + outputExtension);
try {
DocumentFormat outputFormat = converter.getFormatRegistry()
.getFormatByExtension(outputExtension);
long startTime = System.currentTimeMillis();
converter.convert(inputFile, outputFile);
long conversionTime = System.currentTimeMillis() - startTime;
logger.info(String.format(
"successful conversion: %s [%db] to %s in %dms",
inputExtension, inputFile.length(), outputExtension,
conversionTime));
response.setContentType(outputFormat.getMediaType());
response.setHeader("Content-Disposition", "attachment; filename="
+ baseName + "." + outputExtension);
sendFile(outputFile, response);
} catch (Exception exception) {
logger.severe(String.format(
"failed conversion: %s [%db] to %s; %s; input file: %s",
inputExtension, inputFile.length(), outputExtension,
exception, inputFile.getName()));
throw new ServletException("conversion failed", exception);
} finally {
outputFile.delete();
inputFile.delete();
}
} private void sendFile(File file, HttpServletResponse response)
throws IOException {
response.setContentLength((int) file.length());
InputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
IOUtils.copy(inputStream, response.getOutputStream());
} finally {
IOUtils.closeQuietly(inputStream);
}
} private void writeUploadedFile(FileItem uploadedFile, File destinationFile)
throws ServletException {
try {
uploadedFile.write(destinationFile);
} catch (Exception exception) {
throw new ServletException("error writing uploaded file", exception);
}
uploadedFile.delete();
} private FileItem getUploadedFile(ServletFileUpload fileUpload,
HttpServletRequest request) throws FileUploadException {
@SuppressWarnings("unchecked")
List<FileItem> fileItems = fileUpload.parseRequest(request);
for (FileItem fileItem : fileItems) {
if (!fileItem.isFormField()) {
return fileItem;
}
}
return null;
} }

【转载】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. Android 性能测试初探(五)

    书接上文 Android 性能测试初探之 GPU(四) 前文说了的一些性能测试项大家可能都听说,接下来我们聊聊大家不常关注的测试项- 功耗 . 功耗测试主要从以下几个方面入手进行测试 测试手机安装目标 ...

  2. 微信小程序 PDF下载打印

    在开发微信小程序时,需要打印生成的PDF,实现思路是:后端生成相应的PDF,微信小程序下载并打开. 但是微信小程序并不可以打印,所以需要借助其他APP比如:WPS,但是发现微信小程序down的PDF在 ...

  3. Noip 2013 练习

    转圈游戏 传送门 Solution 快速幂 Code //By Menteur_Hxy #include <cstdio> #include <cstdlib> #includ ...

  4. ScrollReveal-元素随页面滚动产生动画的js插件

    简介 和 WOW.js 一样,scrollReveal.js 也是一款页面滚动显示动画的 JavaScript,能让页面更加有趣,更吸引用户眼球.不同的是 WOW.js 的动画只播放一次,而 scro ...

  5. openldap+openssh+jumpserver实现跳板机监控系统

    首先感谢 http://www.jumpserver.org/ 提供的优秀跳板机系统. 我们把跳板机系统经过二次开发主要是 弃用角色功能使用ldap自动登录. 添加登录后临时认证. 上传下载我们自己在 ...

  6. 使用requirejs模块化开发多页面一个入口js的使用方式

    描述 知道requirejs的都知道,每一个页面需要进行模块化开发都得有一个入口js文件进行模块配置.但是现在就有一个很尴尬的问题,如果页面很多的话,那么这个data-main对应的入口文件就会很多. ...

  7. JavaScript 事件代理绑定

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  8. HDU 2296

    很明显的DP状态了,设dp[i][j],设当前在状态点i,经过j步能得到的最大分值.也是从root直接扩展就可以了. 至于字符串,实在有点困难,开始想着记录路径,但后来发现路径从后往前回溯不一定是字典 ...

  9. WindowsclientC/C++编程规范“建议”——函数

    1 函数 1.1 代码行数控制在80行及以内 等级:[要求] 说明:每一个函数的代码行数控制应该控制在80行以内.假设超过这个限制函数内部逻辑一般能够拆分.假设试图超过这个标准.请列出理由. 但理由不 ...

  10. 新手git: ssh: connect to host localhost port 22: Connection refused

    由于gitlab上要git pull或者git clone,可是每次都出现这个问题.之前偶尔出现这个问题.可是仅仅是偶尔.这是为什么呢?然后就開始搜索网上的解决方式了. 这个问题搜索网上非常多答案.可 ...