0x01 背景
最近遇到了一个需求,需要将word文档的前5页截取出来,生成新的文档(类型不限)。
0x02 方案
截取word
经过对Java中word相关的三方库的调研,word文档是一种较为复杂的文档,有doc、docx两种类型,里面可以包含文字、图片、表格等信息,并且word文档中通常是没有明确的分页标识的。直接对word进行截取,是无法准确的将前5页文档截取出来的。此方案行不通。
word转pdf
将word转为pdf后,pdf的截取是很简单的。现在的难点在于怎么将word转为pdf。经过调研,目前能支持次功能的三方库各有优缺点。
- aspose-words 收费,效果很好,耗时很短,非常占内存,网上可以找到license(但是侵权)
- spire.doc 国产收费,网上说效果很好,没具体使用过,免费版的有水印,并且对文档大小有限制
- apache-poi 开源免费,效果一般,依赖比较多,并且依赖之间不同版本可能不兼容,转换时会出现乱码、页数不一致等问题
- libreoffice 开源免费,比较占cpu,耗时长
小结
上面介绍的4个工具,除了spire.doc,其他的都试过了,以1核(逻辑)cpu的机器,20MB的word转换pdf来看,小结一下。
aspose-words使用网上的license会有侵权问题,大文档的转换非常占内存,不停的产生新对象导致GC,GC频繁会导致cpu升高,总体来说效果不错,耗时在15s左右。
apache-poi针对doc支持的不好,并且转换时会出现乱码问题,直接放弃了。
libreoffice需要从官网下载对应版本,安装后可使用,但是转换时耗时较长大约1分钟,cpu升高较明显,并且只能串行(同一时间只能转换一个文档)。
0x03 libreoffice下载
经过对比,不考虑侵权问题,直接使用aspose-words即可(网上资料很多),这里我就介绍linux libreoffice的使用。
使用前需要下载对应的libreoffice,LibreOffice_7.5.5_Linux_x86-64_rpm.tar.gz 、LibreOffice_7.5.5_Linux_x86-64_rpm_langpack_zh-CN.tar.gz
下载地址:http://mirrors.ustc.edu.cn/tdf/libreoffice/stable/7.5.5/rpm/x86_64/
当然去官网下载也可,但是官网中好像没有langpack_zh-CN这个包
另外需要准备字体,防止出现乱码,字体可以在C:\Windows\Fonts中复制,也可以在libreoffice官网去下载。
0x04 libreoffice镜像制作
按照下面的命令编写Dockerfile,制作镜像,我使用的是centos:centos7.9.2009作为基础镜像
# libreoffice
一个开源免费的word转pdf工具,用法参考Example.java
使用方需要在Dockerfile中添加如下命令
# 安装libreoffice core (LibreOffice_7.5.5_Linux_x86-64_rpm.tar.gz解压获得rpm包)
RUN yum install ./core/*.rpm -y
# 安装libreoffice langpack, 支持中文(LibreOffice_7.5.5_Linux_x86-64_rpm_langpack_zh-CN.tar.gz解压获得rpm包)
RUN yum install ./langpack_zh-CN -y
# 安装库文件
RUN yum install libXinerama -y; yum install cairo -y; yum install cups -y
# 添加win字体,防止中文、日语等语言出现乱码问题(字体可以从windows系统中C:\Windows\Fonts复制,也可以去libreoffice官网中下载)
ADD ./win-fonts /usr/share/fonts/win
RUN cd /usr/share/fonts/win; mkfontscale; mkfontdir; fc-cache
0x05 word转pdf
public class Example{
private static String sofficeDir = "/opt/libreoffice7.5/program";
private static final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor
(1, 1, 30, TimeUnit.SECONDS, new ArrayBlockingQueue<>(100));
public static void main(String[] args) throws Exception {
String wordPath = "/tmp/a.docx";
// libreoffice只能单进程处理任务,此处通过线程池任务队列来控制libreoffice单进程
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> convertWordToPdf(tmpSaveFilePath), threadPoolExecutor);
future.get(10 * 60, TimeUnit.SECONDS);
}
public static String convertWordToPdf(String wordPath) {
String result = null;
try {
long old = System.currentTimeMillis();
if (!new File(wordPath).exists()) {
throw new FileNotFoundException();
}
String command = String.format("%s/soffice --invisible --headless --convert-to pdf:writer_pdf_Export %s --outdir /tmp/ &", sofficeDir, wordPath);
result = executeCommand(command);
long now = System.currentTimeMillis();
logger.info("word转pdf,共耗时:" + ((now - old) / 1000.0) + "秒, result:" + result);
} catch (Exception e) {
logger.error("convert word to pdf failed, word path:" + wordPath, e);
}
return result;
}
private static String executeCommand(String command) throws IOException, InterruptedException {
StringBuffer output = new StringBuffer();
Process p;
p = Runtime.getRuntime().exec(command);
p.waitFor();
try (
InputStreamReader inputStreamReader = new InputStreamReader(p.getInputStream(), "UTF-8");
BufferedReader reader = new BufferedReader(inputStreamReader)
) {
String line = "";
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
}
p.destroy();
return output.toString();
}
}
上述为linux版本的libreoffice使用方法,windows版本的更简单,只需要去官网下载windows版本的libreoffice,Java代码中的command中的/opt/libreoffice7.5/program/soffice替换为D:\Program Files\LibreOffice\program\soffice.exe即可。