相关博文来源:

简书:java通过openOffice实现word,excel,ppt转成pdf实现在线预览

博客园:java 如何将 word,excel,ppt如何转pdf --openoffice (1)

博客园:Java使用Openoffice将word、ppt转换为PDF

博客园:linux环境下安装 openOffice 并启动服务

一、OpenOffice

OpenOffice.org 是一套跨平台的办公室软件套件,能在 Windows、Linux、MacOS X (X11)、和 Solaris 等操作系统上执行。它与各个主要的办公室软件套件兼容。OpenOffice.org 是自由软件,任何人都可以免费下载、使用、及推广它。

1.1 下载地址

http://www.openoffice.org/

1.2 JodConverter

jodconverter-2.2.2.zip 下载地址:

http://sourceforge.net/projects/jodconverter/files/JODConverter/

下载openOffce软件,安装相应系统版本,这里以windows为例

添加maven依赖:

<dependency>
<groupId>com.artofsolving</groupId>
<artifactId>jodconverter</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>org.artofsolving.jodconverter</groupId>
<artifactId>jodconverter-core</artifactId>
<version>3.0-beta-4-jahia2</version>
</dependency>

第二个jar包可能有些资源库没有,下载后,直接放在项目中,直接在pom中加载项目内部jar包即可。

 <dependency>
<groupId>org.artofsolving.jodconverter</groupId>
<artifactId>jodconverter-core</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>${basedir}/src/main/resources/lib/jodconverter-core.jar</systemPath>
</dependency>

1.3 新建实体类PDFDemo

import java.io.File;
import java.net.ConnectException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date; import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeManager; import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.StreamOpenOfficeDocumentConverter; public class PDFDemo { public static boolean officeToPDF(String sourceFile, String destFile) {
try { File inputFile = new File(sourceFile);
if (!inputFile.exists()) {
// 找不到源文件, 则返回false
return false;
}
// 如果目标路径不存在, 则新建该路径
File outputFile = new File(destFile);
if (!outputFile.getParentFile().exists()) {
outputFile.getParentFile().mkdirs();
}
//如果目标文件存在,则删除
if (outputFile.exists()) {
outputFile.delete();
}
// DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm"); DefaultOfficeManagerConfiguration config = new DefaultOfficeManagerConfiguration();
// OpenOffice安装在本地环境的目录
String officeHome = "D:\\profiles\\openOfice4";
config.setOfficeHome(officeHome);
config.setPortNumber(8100);
config.setTaskExecutionTimeout(1000 * 60 * 5);// 设置任务执行超时为5分钟
config.setTaskQueueTimeout(1000 * 60 * 60 * 24);// 设置任务队列超时为24小时 OfficeManager officeManager = config.buildOfficeManager();
officeManager.start(); OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
if (inputFile.exists()) {
// 进行PDF格式的转换
converter.convert(inputFile, outputFile);
} officeManager.stop(); return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
} public static void main(String[] args) {
boolean flag = officeToPDF("D:\\testE.xls", "D:\\test3.pdf");
System.out.println(flag);
}
}

上面officceToPDF方法的第一个参数是原文件路径,第二个参数是输出文件路径,后缀名改成html就转成html,后缀名是pdf就转成pdf

上面的方法比较浪费性能 每次都要打开关闭,可以在服务器端开启soffice服务的方式直接调用连接会比较可行;

去到安装目录的program文件夹 cmd打开,运行

soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;"-nofirststartwizard

可以上图看到进程已开启

以下代码可调用:

public static boolean officeToPDF(String sourceFilePath, String destFilePath) {

        boolean flag = false;
//try {
File inputFile = new File(sourceFilePath);
if (!inputFile.exists()) {
// 找不到源文件, 则返回false
return flag;
}
// 如果目标路径不存在, 则新建该路径
File outputFile = new File(destFilePath);
if (!outputFile.getParentFile().exists()) {
outputFile.getParentFile().mkdirs();
}
// 如果目标文件存在,则删除
if (outputFile.exists()) {
outputFile.delete();
}
// DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
try {
OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
connection.connect();
DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
if (inputFile.exists()) {
// 进行PDF格式的转换
converter.convert(inputFile, outputFile);
}
connection.disconnect();
flag = true;
} catch (Exception e) {
flag = false;
e.printStackTrace();
} return flag;
}

二、实践代码二

package indi.johnny.convert;

import java.io.File;
import java.io.FileNotFoundException; import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeManager; //转换文档为pdf
public class OpenOfficePdfConvert { /**
* @param args
*/
private static OfficeManager officeManager;
private static String OFFICE_HOME = "D:/software/OpenOffice 4/";
private static int port[] = { 8100 }; public void convert2PDF(String inputFile, String outputFile) throws FileNotFoundException { startService();
System.out.println("进行文档转换转换:" + inputFile + " --> " + outputFile); OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
converter.convert(new File(inputFile), new File(outputFile)); stopService();
System.out.println(); } // 打开服务器
public static void startService() {
DefaultOfficeManagerConfiguration configuration = new DefaultOfficeManagerConfiguration();
try {
System.out.println("准备启动服务....");
configuration.setOfficeHome(OFFICE_HOME);// 设置OpenOffice.org安装目录
configuration.setPortNumbers(port); // 设置转换端口,默认为8100
configuration.setTaskExecutionTimeout(1000 * 60 * 5L);// 设置任务执行超时为5分钟
configuration.setTaskQueueTimeout(1000 * 60 * 60 * 24L);// 设置任务队列超时为24小时 officeManager = configuration.buildOfficeManager();
officeManager.start(); // 启动服务
System.out.println("office转换服务启动成功!");
} catch (Exception ce) {
System.out.println("office转换服务启动失败!详细信息:" + ce);
}
} // 关闭服务器
public static void stopService() {
System.out.println("关闭office转换服务....");
if (officeManager != null) {
officeManager.stop();
}
System.out.println("关闭office转换成功!");
} public static void main(String[] args) throws Exception {
String path = "C:/Users/johnny/Desktop/文档/20170420/test/001/";
OpenOfficePdfConvert opc = new OpenOfficePdfConvert();
opc.convert2PDF(path+"1.docx", path+"1.pdf");
} }

将代码中的 OFFICE_HOME换成自己的openoffice的安装路径,端口8100不用动。

三、linux环境下安装 openOffice 并启动服务

  1. .http://www.openoffice.org/zh-cn/download/ 去官网链接下载linux版本的openOffice 以4.1.5 版本为例。
  2. 将压缩包上传至服务器上,并进行解压安装。
1  tar -zxvf  对应的压缩包名字
2 cd 进入解压后的 /zh-cn/RPMS
3 yum localinstall *.rpm
4 cd desktop-integration
5 rpm -ivh openoffice4.1.5-redhat-menus-4.1.5-9789.noarch.rpm

默认会安装在/opt目录下。

1 /opt/openoffice4/program/soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard  临时启动
2 nohup /opt/openoffice4/program/soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard & 后台启动

四、Java使用Openoffice将word、ppt转换为PDF

4.1 Word转换

启动OpenOffice的服务

进入openoffice安装目录,通过cmd启动一个soffice服务,启动的命令是

soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;"。

如果觉得后台运行OpenOffice服务比较麻烦,可以通过

4.2 运行代码

public class PDFDemo {

    public static boolean officeToPDF(String sourceFile, String destFile) {
try { File inputFile = new File(sourceFile);
if (!inputFile.exists()) {
// 找不到源文件, 则返回false
return false;
}
// 如果目标路径不存在, 则新建该路径
File outputFile = new File(destFile);
if (!outputFile.getParentFile().exists()) {
outputFile.getParentFile().mkdirs();
}
//如果目标文件存在,则删除
if (outputFile.exists()) {
outputFile.delete();
}
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
OpenOfficeConnection connection = new SocketOpenOfficeConnection("127.0.0.1", 8100);
connection.connect();
//用于测试openOffice连接时间
System.out.println("连接时间:" + df.format(new Date()));
DocumentConverter converter = new StreamOpenOfficeDocumentConverter(
connection);
converter.convert(inputFile, outputFile);
//测试word转PDF的转换时间
System.out.println("转换时间:" + df.format(new Date()));
connection.disconnect();
return true;
} catch (ConnectException e) {
e.printStackTrace();
System.err.println("openOffice连接失败!请检查IP,端口");
} catch (Exception e) {
e.printStackTrace();
}
return false;
} public static void main(String[] args) {
officeToPDF("E:\\test.docx", "E:\\test.pdf");
}
}

4.3 Word、ppt转Html

只需要将后缀名从.pdf改为.html即可。

public static void main(String[] args) {
officeToPDF("E:\\test.docx", "E:\\test.html");
}

4.4 Maven配置

Maven依赖

<dependency>
<groupId>com.artofsolving</groupId>
<artifactId>jodconverter</artifactId>
<version>2.2.1</version>
</dependency>
<dependency>
<groupId>org.openoffice</groupId>
<artifactId>jurt</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.openoffice</groupId>
<artifactId>ridl</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.openoffice</groupId>
<artifactId>juh</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.openoffice</groupId>
<artifactId>unoil</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk14</artifactId>
<version>1.4.3</version>
</dependency>

Maven只有 2.2.1版本,2.2.1版本有一个问题,那就是不兼容docx和pptx,如果你们不使用jodconverter-2.2.2 中lib,而想要使用2.2.1版本,需要修改一下 BasicDocumentFormatRegistry 类中的 getFormatByFileExtension方法:

新建包 com.artofsolving.jodconverter

新建类BasicDocumentFormatRegistry,复制下面代码

package com.artofsolving.jodconverter;

/**
* @author 李文浩
* @date 2017/12/25
*/ import java.util.ArrayList;
import java.util.Iterator;
import java.util.List; public class BasicDocumentFormatRegistry implements DocumentFormatRegistry {
private List documentFormats = new ArrayList(); public BasicDocumentFormatRegistry() {
} public void addDocumentFormat(DocumentFormat documentFormat) {
this.documentFormats.add(documentFormat);
} protected List getDocumentFormats() {
return this.documentFormats;
} public DocumentFormat getFormatByFileExtension(String extension) {
if (extension == null) {
return null;
} else {
if (extension.indexOf("doc") >= 0) {
extension = "doc";
}
if (extension.indexOf("ppt") >= 0) {
extension = "ppt";
}
if (extension.indexOf("xls") >= 0) {
extension = "xls";
}
String lowerExtension = extension.toLowerCase();
Iterator it = this.documentFormats.iterator(); DocumentFormat format;
do {
if (!it.hasNext()) {
return null;
} format = (DocumentFormat)it.next();
} while(!format.getFileExtension().equals(lowerExtension)); return format;
}
} public DocumentFormat getFormatByMimeType(String mimeType) {
Iterator it = this.documentFormats.iterator(); DocumentFormat format;
do {
if (!it.hasNext()) {
return null;
} format = (DocumentFormat)it.next();
} while(!format.getMimeType().equals(mimeType)); return format;
}
}

下面是增加的部分,仅仅增加了将docx按照doc的处理方式处理。而2.2.2版本已经默认增加了。

if (extension.indexOf("doc") >= 0) {
extension = "doc";
}
if (extension.indexOf("ppt") >= 0) {
extension = "ppt";
}
if (extension.indexOf("xls") >= 0) {
extension = "xls";
}

Java通过openOffice实现word,excel,ppt转成pdf实现在线预览的更多相关文章

  1. java 如何将 word,excel,ppt如何转pdf --openoffice (1)

    承上启下,可折叠 上一篇说的是:服务器是windows server时,用jacob将msoffice(指的是word,excel,ppt)转换成pdf. 若被部署项目的服务器是centOS等linu ...

  2. Java使用Openoffice将word、ppt转换为PDF

    最近项目中要实现WORD的文件预览功能,我们可以通过将WORD转换成PDF或者HTML,然后通过浏览器预览. OpenOffice OpenOffice.org 是一套跨平台的办公室软件套件,能在 W ...

  3. 用java将简单的word文档换成pdf文档

    用java将简单的word文档换成pdf文档的方式很多,因为很多都没有实际测试过,所以这里就先泛泛的说一下 整体上来看分两种: 1.纯java代码实现,有很多优秀的开源软件可以用,比如poi,itex ...

  4. word,excel,ppt,txt转换为 PDF

    /// <summary> /// 将word文档转换成PDF格式 /// </summary> /// <param name="sourcePath&quo ...

  5. 在线预览文档(支持word、excel、ppt、pdf)+在线预览文档html版(转)

    1.首先上网搜索一下有什么解决方案 (1).将文档转换为html,只支持支持office文档 (2).将文档转换为flash,实现类似百度文库的效果,除支持office文档外还支持pdf (1) a. ...

  6. JSP实现word文档的上传,在线预览,下载

    前两天帮同学实现在线预览word文档中的内容,而且需要提供可以下载的链接!在网上找了好久,都没有什么可行的方法,只得用最笨的方法来实现了.希望得到各位大神的指教.下面我就具体谈谈自己的实现过程,总结一 ...

  7. pc或者微信上用pdf.js在线预览pdf和word

    最近项目要求pdf和word可以在线预览功能,pc端还好解决,但是微信端就有点坑了,pc端原来的思路是将文件转成base64,然后用html格式显示 ,但是微信端不支持, 这种方式就pass掉了,谷歌 ...

  8. java将office文档pdf文档转换成swf文件在线预览

    第一步,安装openoffice.org openoffice.org是一套sun的开源office办公套件,能在widows,linux,solaris等操作系统上执行. 主要模块有writer(文 ...

  9. windows环境下 php 将office文件(word/excel/ppt)转化为pdf(转)

    将office文件转化为pdf的方法有 1.利用openoffice提供的服务 (比较简单,但是转化的效果不太好) 2.使用office提供的服务 (注:这在windows服务器上,并且服务器上面安装 ...

随机推荐

  1. JAVA_JNI字段描述符“([Ljava/lang/String;)V”(Android)

    JNI字段描述符"([Ljava/lang/String;)V "([Ljava/lang/String;)V" 它是一种对函数返回值和参数的编码.这种编码叫做JNI字段 ...

  2. Qt学习笔记-制作一个文本编辑器

    创建一个MainWindow工程.添加一个TextEdit.垂直布局. 在menu上面创建新的action. 在新建的时候判断文本有没有被修改. 下面,将某个文件打开读入到TextEdit中. 保存文 ...

  3. python之shelve、xml、configparser模块

    一.shelve模块 shelve模块比pickle模块简单,只有一个open函数,返回类似字典的对象,可读可写;key必须为字符串,而值可以是python所支持的数据类型 import shelve ...

  4. 《Go 语言并发之道》读后感 - 第一章

    <Go 语言并发之道>读后感 - 第一章 前言 人生路漫漫,总有一本书帮助你在某条道路上打通任督二脉,<Go 语言并发之道>就是我作为一个 Gopher 道路上的一本打通任督二 ...

  5. OpenWRT19.07_命令行_重拨wan_重启路由

    OpenWRT19.07_命令行_重拨wan_重启路由 转载注明来源: 本文链接 来自osnosn的博客,写于 2020-10-19. 写OpenWRT的脚本时,需要用到一些重启命令 以下的命令中的参 ...

  6. Debian10_Centos8_fail2ban

    Debian10_Centos8_fail2ban 转载注明来源: 本文链接 来自osnosn的博客,写于 2020-11-7. Debian-10 的 fail2ban 支持 ipv6.防火墙内核是 ...

  7. PAT天梯赛练习 L3-004 肿瘤诊断 (30分) 三维BFS

    题目分析: 可能是我的理解能力比较差,在读题的时候一直以为所有的切片是可以排列组合的,并不是按照输入顺序就定死的,那么这题就变得十分的复杂啦~~~~~,查看的题解之后发现所有的切片并没有所谓的自由组合 ...

  8. HarmonyOS三方件开发指南(5)——Photoview组件

    PhotoView使用说明 1.  PhotoView功能介绍1.1 组件介绍:        PhotoView是一个继承自Image的组件,不同之处在于:它可以进行图击放大功能,手势缩放功能(暂无 ...

  9. kubernets之服务资源

    一  服务集群内部或者客户端与pod的通信桥梁   kubernets集群的内部pod访问为啥不能使用传统的IP:PORT的形式? pod是短暂的,它们会随时启动或者关闭,原因可能是pod所在的节点下 ...

  10. LeetCode700. 二叉搜索树中的搜索

    题目 简单递归 1 class Solution { 2 public: 3 TreeNode* searchBST(TreeNode* root, int val) { 4 if(!root) re ...