实现环境:要求可以在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 SourceForge.net

安装openoffice

1.安装linux的openoffice

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

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

1  tar -zxvf  对应的压缩包名字
2  cd 进入解压后的 /zh-cn/RPMS
3  yum localinstall *.rpm
4  cd desktop-integration
5  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 端口号

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

`tcp        0      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="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/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 &

用java实现,office文件转成pdf文件相关推荐

  1. java编程将HTML文件转换成PDF文件

    网上有好几种方法可以将将HTML文件转换成PDF文件但是有些对HTML文件格式要求比较严格,稍微错了一些就不能生成我们所要的PDF文件,这里我推荐一个 PD4ML,它可以解决HTML文件格式不正确的问 ...

  2. Java使用aspse实现Excel文件转换成PDF文件

    使用Java代码把Excel文件转换成PDF文件 需要引用aspose包,引入操作我写了一个博客,地址如下 https://blog.csdn.net/weixin_46713508/article/ ...

  3. 怎么把图片文件转换成PDF文件

    除了office文件外,我们最常用的就是PDF文件了.因为PDF文件格式可以将文字.字型.格式.颜色及独立于 设备和分辨率的图形图像等封装在一个文件中.该格式文件还可以包含超文本链接.声音和动态影像等 ...

  4. 把jpg文件转换成pdf文件

    把jpg文件转换成pdf文件 生涯中,人人常常会拍摄一些照片用来忖量,可是岁月长了,时时会由于照片多而杂乱而懒于翻看,那末你是否思虑做一个电子相册,或制造一本PDF花样的书本来翻看呢?业余的这款JPG ...

  5. 怎么把jpg文件转换成pdf文件

    怎么把jpg文件转换成pdf文件 PDF转换成Word文档对我们来讲并不生僻,假设文字是由一张张图片构成的,碰着这种状况怎么办,怎么将JPG转换成PDF?菜鸟损耗了不少工夫和肉体才找到一款好用的JPG ...

  6. 如何将Ai文件转换成PDF文件

    要将Ai文件转换成PDF文件,请按照以下步骤操作: 1. 打开客汇宝网站软件并打开要转换的文件. 2. 点击"文件"菜单并选择"另存为". 3. 在" ...

  7. CAJ文件转换成PDF文件:教你如何实现文件格式转换

    CAJ文件是中国知网常用的一种文献格式,但有时候我们需要将其转换成PDF格式,以方便阅读.打印.分享等用途.本文将教你如何实现CAJ文件转换成PDF文件. 方法一.使用CAJViewer软件 步骤1: ...

  8. 怎么将知网下载的CAJ文件转换成PDF文件

    我们熟知的CAJ文件必须使用中国知网的CAJ Viewer才能打开,但是如果想以PDF的格式查看论文那就需要将CAJ文件转换为pdf格式,那么怎么CAJ文件转换成PDF文件呢? 转换方法其实很简单,这 ...

  9. 怎么把caj文件转换成pdf文件

    我们在网上下载素材的时候,就有很大一部分是caj格式的文件,我们又想将caj文件整理成pdf文件,那么怎么把caj文件转换成pdf文件呢? 其实转换很简单,只需要一个CAJ转换器就能实现,下面介绍ca ...

  10. 如何将CAJ文件转换成PDF文件?教你一招搞定

    CAJ文件是中国知网的专用格式,主要用于存储学术文献等信息.由于这种格式并非常见格式,很多用户不知道如何打开或转换.如果您需要将CAJ文件转换成PDF文件,不必担心,您可以使用记灵在线工具来解决这个问 ...

最新文章

  1. numpy库中ndarray切片操作的参数意义
  2. Chrome 技术篇-常用web调试技巧清除缓存并硬性重新加载
  3. Linux 系统目录
  4. 属性 方法c语言,C语言如何实现C++中对象属性和方法
  5. if shell 条件语句简写_Shell if条件判断语句用法详解
  6. Form界面设置只读
  7. NeurIPS 2020 | Glance and Focus: 通用、高效的神经网络自适应推理框架
  8. 《NAT穿越(NAT-T)RFC3947文档》记录
  9. QCA6174A方案PCI-E接口双频蓝牙WiFi二合一模块8274B-PR
  10. 怎么对注册表中的垃圾文件进行清理?
  11. 高斯法计算矩阵的行列式
  12. 恒讯科技分析:海外云服务器的网络防火墙怎么设?
  13. macOS 网络已连接但无法使用的一种情况
  14. 什么是RPC?RPC好处?常用的RPC框架?
  15. 计算机视觉之三维重建——深入浅出SFM系统与SLAM系统的核心算法
  16. shell 抓取页面信息 ip168查询 IP归属地
  17. 苹果推出iPhone 12维修计划,解决无声音问题
  18. windows九大权限的分析与利用
  19. WebAR开发指南(1)---使用AR.js实现第一个WebAR demo
  20. java ocr 条型码_Tesseract.js (JavaScript OCR) 识别1D条形码下面的数字

热门文章

  1. Python中map与lambda的结合使用
  2. 快速整理统计数据必备技巧:EXcel【Vlookup+COLUMN】函数使用
  3. jmeter_socket(tcp取样器)
  4. linux系统导入导出mysql数据库数据
  5. 【云周刊】第133期:阿里云全球十四个节点评测分析及服务器地域选择攻略
  6. android 如何获得附近的wifi,Android 8.1推出新功能,一键帮你找到周围最快的WiFi
  7. 核弹剑仙 (拓扑排序+bitset或最短路)
  8. Centos7系统NS-3的安装与环境配置
  9. 如何设置省略号对其序号 html,html 用css实现table中超长字符串省略号表示 - 天天好心情 - 博客园...
  10. 黑苹果hd630显存7m_黑苹果显存只有5mb_动漫台