遭遇
最近遇到一个需求,根据word文档外链url获取到文件并转成pdf文件流返回。
百度找到了一个工具document4j,大晚上感觉像是握住了稻草,看了下demo搞了一会。
尝试
maven依赖
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-local</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-transformer-msoffice-word</artifactId>
<version>1.1.1</version>
</dependency>
转换核心代码
docxInputStream:word文档的输入流
outputStream:转化后的pdf输出流
IConverter converter = LocalConverter.builder().build();
converter.convert(docxInputStream).as(DocumentType.DOC).to(outputStream).as(DocumentType.PDF).execute();
converter.kill();
写个接口就可以获取了,这里我用本地文件测试了一下
@GetMapping("/file")
public void file(HttpServletResponse httpServletResponse) throws IOException {
File file = new File("C:\\Users\\Administrator\\Desktop\\luowei\\learn\\demo-test\\补天.docx");
FileInputStream fileInputStream = new FileInputStream(file);
fileTypeConvert.wordInputStreamToPdfoutputStream(fileInputStream, httpServletResponse.getOutputStream(), "docx");
httpServletResponse.setStatus(200);
inputStream.close();
}
成功鼓掌
优化
在使用过程中,发现简单一页word转换竟然要2s,难以想象如果十几页几十页会咋样,百度了一会,说是创建连接的时间长也就是build转换器的时间长,看了一下确实如此,并且与硬件设施有关,我用公司电脑跑了一下耗时4s。。。。
哎,灵机一动,直接把convert注入bean容器好了,这样在IOC初始化的时候就创建连接了
坑来了
就当我美滋滋睡觉醒来,准备继续优化测试的时候,第一次读取成功,再一次转换,报错了,convert lost connect。
去看了一眼文档,一旦关闭连接就彻底关了,我转换之后加的一行kill()导致的第一转换完成断开了转换器联接。。。。
部署
完事具备,我美滋滋去部署了,结果。。。。。failed,又去看文档(微笑.gif)
想用除非我去给Linux装个MS word
这玩意实际上是调用word去转换。。。。所以写个脚本批量转转文件方便,做项目有点太拉了。。。。。。