背景
项目中需要在线预览文档,且文档格式有word、excel和ppt等多种Office格式的 所以需要一中能在linux上运行的在线转换工具,经过github的查找,发现LibreOffice的方式,以下介绍以下具体方法
准备环境
安装LibreOffice
yum install libreoffice
文件有点大,需要安装一段时间
安装字体
**
字体一定需要安装,否则会出现乱码问题
** 1、下载字体
yum groupinstall "fonts"
2、修改字符集
vim /etc/locale.conf
将LANG="en_US.UTF-8"修改成LANG="zh_CN.UTF-8"
3、重启
reboot
Java实现转换的Demo
代码
LibreOfficeCommandWordService.java
package top.flksweb;
import java.io.*;
public class LibreOfficeCommandWordService {
private final static String sofficeDir ="/usr/local/bin";
public void word2pdf(String inPath, String outPath) throws Exception {
if (!new File(inPath).exists()) {
throw new FileNotFoundException();
}
String command = String.format("%s/soffice --convert-to pdf:writer_pdf_Export %s --outdir %s", sofficeDir, inPath, outPath);
String output = this.executeCommand(command);
}
protected 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();
}
}
测试方法
import java.io.File;
public class Office2Pdf {
public static void main(String[] args) throws Exception {
LibreOfficeCommandWordService officeCommandWordService = new LibreOfficeCommandWordService();
File file = new File("/Users/franks/Documents/ESB技术选型报告.docx");
File outFile = new File("/Users/franks/Documents");
officeCommandWordService.word2pdf(file.getAbsolutePath(), outFile.getAbsolutePath());
}
}
至此,测试完成通过。
|