java实现word转pdf在线预览格式
前段时间的项目里涉及了此功能,调研过一些方案,踩过一些坑,一一总结在此。
java转pdf的方案很多,但是很多都要收费,转pdf也有一些格式方面的问题。
方案对比:
poi格式错乱
aspose-words linux环境无法使用
documents4j linux环境无法使用
jacob 需要window环境 需要安装office
Free Spire.Doc for Java只能转3页 剩的需要付费
page office 付费
open office 需要安装服务,上传字体,部署停机有顺序 需要安装字体
方案一 使用xdocreport
即Apache的wordConverterToPdf方式进行转换
优点:效率高
缺点:样式支持不好,部分中文字体不支持,需要office2007以上版本
步骤:
1.在pom文件中加入依赖
<!--apache poi-->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>4.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>ooxml-schemas</artifactId>
<version>1.4</version>
</dependency>
<!--生成复杂word 解决itext报错-->
<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
<version>2.1.7</version>
</dependency>
<!--xdocreport文档转换-->
<dependency>
<groupId>fr.opensagres.xdocreport</groupId>
<artifactId>xdocreport</artifactId>
<version>2.0.2</version>
</dependency>
2.核心代码
/**
*
* @param inputStream docx文档输入流
* @param outputStream pdf输出流
*/
public static void wordToPdf(InputStream inputStream, OutputStream outputStream) {
try {
XWPFDocument docxDocument = new XWPFDocument(inputStream);
PdfOptions pdfOptions = PdfOptions.create();
PdfConverter.getInstance().convert(docxDocument, outputStream, pdfOptions);
} catch (Exception e) {
e.printStackTrace();
}
}
3.测试
public static void main(String[] args) {
InputStream inputStream = null;
OutputStream outputStream = null;
try {
String filepath = "C:\\Users\\luban\\Desktop\\siPrvUqIyVIwZTOx.docx";
String outpath = "C:\\Users\\luban\\Desktop\\test.pdf";
inputStream = new FileInputStream(filepath);
outputStream = new FileOutputStream(outpath);
wordToPdf(inputStream, outputStream);
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
方案二 使用dom4j
由于只支持windows环境,此处不过多介绍
方案三JobConverter + OpenOffice
步骤:
优点:效率高
缺点:需要安装服务器字体支持
1.安装并启动openoffice
https://blog.csdn.net/lx_nhs/article/details/99305227
2.项目工程pom文件引入JobConverter依赖
<!--open office-->
<dependency>
<groupId>org.jodconverter</groupId>
<artifactId>jodconverter-core</artifactId>
<version>4.2.2</version>
</dependency>
<dependency>
<groupId>org.jodconverter</groupId>
<artifactId>jodconverter-spring-boot-starter</artifactId>
<version>4.2.2</version>
</dependency>
<dependency>
<groupId>org.jodconverter</groupId>
<artifactId>jodconverter-local</artifactId>
<version>4.2.2</version>
</dependency>
3.核心代码
public static void covert2Pdf(InputStream inputStream, OutputStream outputStream) {
//web项目中,端口、安装路径可以放在application文件里
OfficeManager officeManager =
LocalOfficeManager.builder()
.portNumbers(8100)
.officeHome("C:/Program Files (x86)/OpenOffice 4")
.build();
try {
officeManager.start();
LocalConverter.make(officeManager)
.convert(inputStream)
.as(DefaultDocumentFormatRegistry.DOCX)
.to(outputStream)
.as(DefaultDocumentFormatRegistry.PDF)
.execute();
} catch (Exception e) {
e.printStackTrace();
} finally {
OfficeUtils.stopQuietly(officeManager);
}
}
4.测试
public static void main(String[] args) {
InputStream inputStream = null;
OutputStream outputStream = null;
try {
String filepath = "C:\\Users\\luban\\Desktop\\test.docx";
String outpath = "C:\\Users\\luban\\Desktop\\test.pdf";
inputStream = new FileInputStream(filepath);
outputStream = new FileOutputStream(outpath);
covert2Pdf(inputStream, outputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
5.打印日志信息如下
14:56:26.359 [main] INFO org.jodconverter.office.OfficeProcessManager - Submitting task ‘Start’ and waiting…
14:56:28.575 [OfficeProcessThread-0] INFO org.jodconverter.office.OfficeDescriptor - soffice info (from exec path): Product: OpenOffice - Version: ??? - useLongOptionNameGnuStyle: false
14:56:28.575 [OfficeProcessThread-0] INFO org.jodconverter.office.OfficeProcess - Starting process with acceptString ‘socket,host=127.0.0.1,port=8100,tcpNoDelay=1;urp;StarOffice.ServiceManager’ and profileDir ‘C:\Users\luban\AppData\Local\Temp.jodconverter_socket_host-127.0.0.1_port-8100_tcpNoDelay-1’
14:56:28.720 [OfficeProcessThread-0] DEBUG org.jodconverter.process.AbstractProcessManager - Command line matches! Returning pid: 17700
14:56:28.720 [OfficeProcessThread-0] INFO org.jodconverter.office.OfficeProcess - Started process; pid = 17700
14:56:28.721 [OfficeProcessThread-0] DEBUG org.jodconverter.office.OfficeConnection - Connecting with connectString ‘socket,host=127.0.0.1,port=8100,tcpNoDelay=1’
14:56:29.841 [OfficeProcessThread-0] INFO org.jodconverter.office.OfficeConnection - Connected: ‘socket,host=127.0.0.1,port=8100,tcpNoDelay=1’
14:56:29.842 [main] DEBUG org.jodconverter.office.OfficeProcessManager - Task ‘Start’ executed successfully
14:56:30.025 [main] DEBUG org.jodconverter.office.AbstractOfficeManagerPoolEntry - Waiting for task to complete…
14:56:30.026 [OfficeManagerPoolEntry-1] INFO org.jodconverter.task.LocalConversionTask - Executing local conversion task…
14:56:30.650 [OfficeManagerPoolEntry-1] DEBUG org.jodconverter.filter.RefreshFilter - Applying the RefreshFilter
14:56:32.328 [main] DEBUG org.jodconverter.office.AbstractOfficeManagerPoolEntry - Task executed successfully
14:56:32.328 [main] INFO org.jodconverter.office.AbstractOfficeManagerPool - Stopping the office manager pool…
14:56:32.329 [main] INFO org.jodconverter.office.OfficeProcessManager - Submitting task ‘Stop’ and waiting…
14:56:32.333 [OfficeProcessThread-0] DEBUG org.jodconverter.office.OfficeProcessManager - The Office Process has been terminated
14:56:32.336 [MessageDispatcher] INFO org.jodconverter.office.OfficeConnection - Disconnected: ‘socket,host=127.0.0.1,port=8100,tcpNoDelay=1’
14:56:32.586 [OfficeProcessThread-0] INFO org.jodconverter.office.OfficeProcessManager - process exited with code 0
14:56:32.586 [OfficeProcessThread-0] DEBUG org.jodconverter.office.OfficeProcess - Deleting instance profile directory ‘C:\Users\luban\AppData\Local\Temp.jodconverter_socket_host-127.0.0.1_port-8100_tcpNoDelay-1’
14:56:32.653 [main] DEBUG org.jodconverter.office.OfficeProcessManager - Task ‘Stop’ executed successfully
14:56:32.653 [main] INFO org.jodconverter.office.AbstractOfficeManagerPool - Office manager stopped
14:56:32.653 [main] DEBUG org.jodconverter.office.AbstractOfficeManager - Deleting temporary directory ‘C:\Users\luban\AppData\Local\Temp\jodconverter_b4669034-2ae2-4d83-9b24-0401e9d114b5’
Process finished with exit code 0
方案四 onlyoffice
onlyoffice是一款即可以实现在线编辑也可以实现文档转换的工具,此处只介绍其文档转换功能
步骤:
1.安装onlyoffice
https://www.jianshu.com/p/50a0e7530373
2.在项目里调用api
使用http客户端按照文档调用即可
api参考地址:https://api.onlyoffice.com/editors/conversionapi
3.示例
public class OnlyOfficeClient {
private static final Logger log = LoggerFactory.getLogger(OnlyOfficeClient.class);
private String url;
public OnlyOfficeClient() {
}
public OnlyOfficeClient(String url) {
this.url = url;
}
public String sendPOST(String fileUrl, String targetSuffix) {
try {
HttpPost post = new HttpPost(this.url);
String s = String.valueOf(System.currentTimeMillis());
String suffix = fileUrl.substring(fileUrl.lastIndexOf(".") + 1).toLowerCase();
JsonObject json = new JsonObject();
json.addProperty("async", false);
json.addProperty("filetype", suffix);
json.addProperty("key", s);
json.addProperty("outputtype", targetSuffix);
json.addProperty("title", s + "." + suffix);
json.addProperty("url", fileUrl);
post.setEntity(new StringEntity(json.toString()));
post.setHeader("Content-Type", "application/json");
post.setHeader("Accept", "application/json");
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(post);
JSONObject jsonObject = JSONObject.parseObject(EntityUtils.toString(response.getEntity()));
return jsonObject.getString("fileUrl");
} catch (Exception e) {
log.info("发送http请求发生异常<{}>", e.getMessage());
return null;
}
}
}
@Service
public class OnlyOfficeService {
@Value("${onlyoffice.url}")
private String ONLY_URL;
private OnlyOfficeClient onlyOfficeClient;
private static final Logger log = LoggerFactory.getLogger(OnlyOfficeService.class);
@PostConstruct
public void init() {
onlyOfficeClient = new OnlyOfficeClient(ONLY_URL);
}
public String convert(String fileUrl, String targetSuffix) {
return onlyOfficeClient.sendPOST(fileUrl, targetSuffix);
}
}
源码地址
https://github.com/lubanjune/office2pdf
参考博客:
java通过POI和jacob实现word文档的在线预览和下载
https://blog.csdn.net/aouixh/article/details/81119742
https://blog.csdn.net/qwert678000/article/details/72770109
https://blog.csdn.net/weixin_38287471/article/details/78707387
https://blog.csdn.net/qq_38830964/article/details/112802496
openoffice博文
https://blog.csdn.net/qingtian_1993/article/details/79901843
https://blog.csdn.net/mufeng633/article/details/83343191
https://blog.csdn.net/weixin_40162216/article/details/82387621
https://blog.csdn.net/u012385190/article/details/100545682
https://blog.csdn.net/qq_43679903/article/details/86657084
https://blog.csdn.net/shipfei_csdn/article/details/105141487
https://blog.csdn.net/qq_39994174/article/details/105809332
https://blog.csdn.net/weixin_39468112/article/details/89203815
https://blog.csdn.net/qq_42944520/article/details/90607328
https://blog.csdn.net/ljlj8888/article/details/104355670
https://blog.csdn.net/Hpluvalbe/article/details/108615750