1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > 用java实现 office文件转成pdf文件

用java实现 office文件转成pdf文件

时间:2023-11-25 16:44:34

相关推荐

用java实现 office文件转成pdf文件

实现环境:要求可以在linux环境下运行,开源插件 , 跨平台

以下有五种方法:

结论:

office不支持跨平台,

aspose收费,

基于pio+itext转换后会严重失真,

基于libreOffice不支持插入图形,否则会造成文本发生走样

而openOffice各种效果,效率……都是未测的。。。。

总结:目前仅考虑openOffice和libreOffice

openOffice实战

原理:

通过第三方工具openOffice,将word、excel、ppt、txt等文件转换为pdf文件

先安装openOffice软件(Windows或Linux有提供软件)

使用JODConverter的Java的OpenDocument 文件转换器API操作Office系列文件转换为PDF文件

优点:

转换效果比较好。是比较主流的做法

缺点:

服务器需要安装openOffice,比较负重。启动服务时效率不是很高

具体实现:

1.下载安装软件

1)Openoffice:Apache下的一个开放免费的文字处理软件

下载地址:Apache OpenOffice - 下载

2)JODConverter一个Java的OpenDocument 文件转换器,只用到它的jar包

下载地址:JODConverter - Browse /JODConverter at

安装openoffice

1.安装linux的openoffice

1.Apache OpenOffice - 下载 去官网链接下载linux版本的openOffice 以4.1.2 版本为例。

2.将压缩包上传至服务器上,并进行解压安装。

1 tar -zxvf 对应的压缩包名字2 cd 进入解压后的 /zh-cn/RPMS3 yum localinstall *.rpm4 cd desktop-integration5 rpm -ivh 含redhat的

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

3.启动服务

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 & 后台启动

端口号根据自己项目实际来确定。

后台启动会一直占用内存,据各路大神说 大概100M,我自己没测过具体值不清楚。

有的程序是需要预先启动openOffice 服务的,有的则在代码里自己启动服务。

4.查看进程

netstat -lnp |grep 端口号

大概显示成这样就算启动完了。

`tcp0 0 127.0.0.1:8100 0.0.0.0:*LISTEN 14362``/soffice``.bin`

2.安装window的openoffice

比linux的更简单,安装好后,只需要在C:\Program Files (x86)\OpenOffice 4\program执行下面的命令就可以了// soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststa

linux开机,重启openoffice服务(linux下openoffice启动和自动启动设置(centos)_resolute123的博客-CSDN博客_linux openoffice重启)

编辑vi /etc/rc.local

添加如下命令

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

重启linux,命令reboot netstat -lnp |grep 8100 - - - 查看是否会出现以下信息,表示成功 tcp 0 0 127.0.0.1:8100 0.0.0.0:* LISTEN 8220/soffice.bin

2.Java实现

依赖

<?xml version="1.0" encoding="UTF-8"?><project xmlns="/POM/4.0.0" xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/POM/4.0.0 /xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.5.4</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.officetopdf</groupId><artifactId>officetopdf</artifactId><version>0.0.1-SNAPSHOT</version><name>officetopdf</name><packaging>war</packaging><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency>​<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>​<dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId><version>2.8.5</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.60</version></dependency>​<!--office转pdf需要的依赖--><dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.5.0</version></dependency>​<dependency><groupId>com.itextpdf</groupId><artifactId>itext-pdfa</artifactId><version>5.5.0</version></dependency>​<dependency><groupId>com.itextpdf</groupId><artifactId>itext-asian</artifactId><version>5.2.0</version></dependency>​<dependency><groupId>com.itextpdf.tool</groupId><artifactId>xmlworker</artifactId><version>5.5.0</version></dependency>​​<dependency><groupId>org.jodconverter</groupId><artifactId>jodconverter-local</artifactId><version>4.1.0</version></dependency>​<dependency><groupId>org.xhtmlrenderer</groupId><artifactId>flying-saucer-pdf</artifactId><version>9.0.7</version></dependency>​<dependency><groupId>com.artofsolving</groupId><artifactId>jodconverter</artifactId><version>2.2.1</version></dependency>​<dependency><groupId>com.github.livesense</groupId><artifactId>jodconverter-core</artifactId><version>1.0.5</version></dependency>​<dependency><groupId>org.jodconverter</groupId><artifactId>jodconverter-core</artifactId><version>4.1.0</version></dependency><dependency><groupId>org.jodconverter</groupId><artifactId>jodconverter-local</artifactId><version>4.1.0</version></dependency><dependency><groupId>org.jodconverter</groupId><artifactId>jodconverter-spring-boot-starter</artifactId><version>4.1.0</version></dependency><dependency><groupId>org.libreoffice</groupId><artifactId>juh</artifactId><version>5.4.2</version></dependency><dependency><groupId>org.libreoffice</groupId><artifactId>jurt</artifactId><version>5.4.2</version></dependency><dependency><groupId>org.libreoffice</groupId><artifactId>ridl</artifactId><version>5.4.2</version></dependency><dependency><groupId>org.libreoffice</groupId><artifactId>unoil</artifactId><version>5.4.2</version></dependency>​<dependency><groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>5.3.9</version></dependency>​<dependency><groupId>org.libreoffice</groupId><artifactId>officebean</artifactId><version>6.4.2</version></dependency>​<!--使用HttpClient远程发送请求 --><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId></dependency>​<dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.11.0</version></dependency>​<dependency><groupId>javax.servlet</groupId><artifactId>jstl</artifactId></dependency><dependency><groupId>org.apache.tomcat.embed</groupId><artifactId>tomcat-embed-jasper</artifactId><scope>provided</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-tomcat</artifactId><scope>provided</scope></dependency><dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><scope>provided</scope></dependency>​<dependency><groupId>org.apache.tomcat.embed</groupId><artifactId>tomcat-embed-jasper</artifactId><scope>provided</scope></dependency>​​​</dependencies>​<build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>​</project>​

转换代码

package com.officetopdf.officetopdf.transform;​import java.io.*;import java.text.DateFormat;import java.text.SimpleDateFormat;import java.util.Date;import java.util.HashMap;import java.util.Map;​import com.google.gson.Gson;import com.officetopdf.officetopdf.utils.HttpClientUtils;import com.officetopdf.officetopdf.utils.ResultUtils;​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;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.bind.annotation.RestController;​​/*** office文件转pdf文件的方法*/@RestController@ResponseBody@RequestMapping("/start")public class PDFDemo {​​@RequestMapping("/topdf")public static ResultUtils officeToPDF(@RequestBody Map<String, Object> map) {/*** 从map里面接收参数*/String sourceFile = (String) map.get("sourceFile");//源文件,officeString targetFile = (String) map.get("targetFile");//pdf文件String successCallback = (String) map.get("successCallback");//转换成功,回调的接口String failCallback = (String) map.get("failCallback");//转换失败,回调的接口String id = (String) map.get("id");String token = (String) map.get("token");​​try {//对sourceFile,targetFile进行处理File inputFile = new File(sourceFile);if (!inputFile.exists()) { // 找不到源文件, 则返回falsereturn ResultUtils.error("找不到源文件");}​​File outputFile = new File(targetFile);if (!outputFile.getParentFile().exists()) {//如果目标路径不存在,则创建outputFile.getParentFile().mkdirs();}​​if (outputFile.exists()) {//如果目标文件存在,则删除outputFile.delete();}​​​​/*** 开启线程,进行连接,转换,断开并且返回相应的数据*/new Thread(new Runnable() {@Overridepublic void run() {DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");OpenOfficeConnection connection = new SocketOpenOfficeConnection();//如果在此处报错,可能需要启动openoffice服务// windows启动命令//cd C:\Program Files (x86)\OpenOffice 4\program//执行命令: soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststa// linux启动命令// /opt/openoffice4/program/soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard 临时启动// nohup /opt/openoffice4/program/soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard & 后台启动try {connection.connect();​//用于测试openOffice连接时间Date time1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(df.format(new Date()));System.out.println("连接时间:" + time1);DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection);​converter.convert(inputFile, outputFile);​//测试word转PDF的转换时间Date time2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(df.format(new Date()));System.out.println("转换时间:" + time2);​long time = time2.getTime() - time1.getTime();System.out.println("totalTime:" + time + "ms");connection.disconnect();​/*** 操作结束之后,返回数据*///转换成功返回的数据PostEntity postEntity=new PostEntity();postEntity.setId(id);postEntity.setSuccessCallback(successCallback);postEntity.setSourceFile(sourceFile);postEntity.setTargetFile(targetFile);postEntity.setToken(token);​/* Map<String, String> params1 = new HashMap<>();params1.put("id", id);params1.put("sourceFile", sourceFile);params1.put("targetFile", targetFile);params1.put("token", token);params1.put("successCallback", successCallback);*/HttpClientUtils.doPost(successCallback, new Gson().toJson(postEntity), token);​} catch (Exception e) {e.printStackTrace();System.err.println("openOffice连接失败!请检查IP,端口");//转换失败返回的数据Map<String, String> params2 = new HashMap<>();params2.put("id", id);params2.put("sourceFile", sourceFile);params2.put("targetFile", targetFile);params2.put("token", token);params2.put("failCallback", failCallback);// HttpClientUtils.doPost(failCallback, params2, token);}}}).start();​​return ResultUtils.success("success");​} catch (Exception e) {e.printStackTrace();}return ResultUtils.error("转换失败");}​​​​​// @RequestMapping("/topdf2")// public static ResultUtils officeToPDF2(@RequestBody Map<String, Object> map) {//System.out.println(map);//return ResultUtils.success("success");// }​}​

转换问题--不兼容docx和pptx

我这里使用的jodconverter是2.2.1的,不兼容docx和pptx,而jodconverter-2.2.2是兼容的。想要使用2.2.1版本,需要修改一下 BasicDocumentFormatRegistry 类中的 getFormatByFileExtension方法:

新建包 com.artofsolving.jodconverter 新建类BasicDocumentFormatRegistry,复制下面代码

​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;}}​

运行

此代码在linux和window都可以运行

1.linux,将该项目,clear -> package后,将jar上传到linux,然后再使用java -jar xxx.jar,然后在浏览器访问项目的转换路径,就可以实现转换了

2.window,可以在浏览器访问该转换路径。但建议使用postman进行接口测试访问

postman进行接口测试访问

巩固Linux常用命令

cd / - - - 返回根目录

cd .. - - - 返回上一级

cd 某文件夹 - - - 进入某文件夹

rm -rf - - - 删除某文件夹或文件

rz - - - 从window系统上传文件到linux

sz - - - 从linux系统上传文件到window

3、openoffice乱码问题解决方法

步骤1 cd /usr/share/fonts 在这个目录下新建一个chinese文件夹 mkdir chinese

步骤2 把自己电脑的字体打包上传到这个文件夹

步骤3 执行下面几条命令 mkfontscale mkfontdir fc-cache -fv

步骤4 ps -ef|grep openoffice 查看当前office进程,杀死进程,kill -9 进程id

步骤5 重新启动 office nohup /opt/openoffice4/program/soffice -headless - accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard &

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。