1.CentOS安装 LiberOffice
1.1 在线安装LiberOffice
yum install -y libreoffice
1.2查看版本号
libreoffice --version
1.3 查看软连接
which libreoffice
ll /usr/bin/ |grep libre
由输出结果可以看出,soffice指向了/usr/lib64/libreoffice/program/soffice
路径,所以下面执行启动命令的时候直接用soffice执行就可以。
1.4启动LibreOffice
soffice --headless --accept="socket,host=0.0.0.0,port=8100;urp;" --nofirststartwizard &
1.5 查看是否启动成功
ps -ef|grep libreoffice
1.6 安装字库
yum -y install fontconfig
yum -y install ttmkfdir
执行成功后,/usr/share
目录下会有fonts和fontconfig文件夹。
在在/usr/share/fonts
下创建chinese文件夹,并给chinese目录赋权限。
cd /usr/share/fonts
mkdir chinese
chmod 777 chinese
我们到自己的windows电脑上查找想要的字体,访问C:\Windows\Fonts,选择自己想要上传的字体,上传到chinese目录下。
执行以下命令,生成 TrueType 字体的字体度量
ttmkfdir -e /usr/share/X11/fonts/encodings/encodings.dir
编辑字体配置文件,配置刚才创建中文字体目录。
vi /etc/fonts/fonts.conf
执行命令,刷新字体缓存
fc-cache
2. Java代码实现word转pdf
2.1 maven依赖
<!-- word转pdf -->
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-local</artifactId>
<version>1.0.3</version>
</dependency>
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-transformer-msoffice-word</artifactId>
<version>1.0.3</version>
</dependency>
2.2 代码片段
/**
* word转换为pdf
* @param currentTimeMillis 当前时间时间戳
* @param outDocxPath 输出的word路径
* @return
*/
private String wordConvertToPDF(Long currentTimeMillis,String outDocxPath){
//转换后的pdf文件路径
String outFileName = currentTimeMillis+".pdf";
String pdfPath = DtapConfig.getOutPath()+ outFileName;
File inputWord = new File(outDocxPath);
File outputFile = new File(pdfPath);
String os = System.getProperty("os.name").toLowerCase();
if (os.contains("win")){
//windows系统
try {
InputStream docxInputStream = new FileInputStream(inputWord);
OutputStream outputStream = new FileOutputStream(outputFile);
IConverter converter = com.documents4j.job.LocalConverter.builder().build();
if (outDocxPath.split("\\.")[1].equals("doc")) {
converter.convert(docxInputStream).as(DocumentType.DOC).to(outputStream).as(DocumentType.PDF).execute();
} else {
converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
}
outputStream.close();
docxInputStream.close();
return pdfPath;
} catch (Exception e) {
System.out.println("PDF转换失败");
return null;
}
}else if(os.contains("nix") || os.contains("nux") || os.contains("mac")){
// Unix/Linux/Mac操作系统
// 获取源文件的绝对路径和目录路径
String absolutePath = inputWord.getAbsolutePath();
String parentPath = inputWord.getParent();
// 构建LibreOffice的命令行工具命令
String commands = "soffice --headless --convert-to pdf "
+ absolutePath + " --outdir " + parentPath;
// 执行转换命令
try {
// 执行命令行工具命令
Process process = Runtime.getRuntime().exec(commands);
process.waitFor();
// 转换成功,返回转换后的PDF文件
return pdfPath ;
}catch (Exception e){
System.out.println("==================转换失败==================");
e.printStackTrace();
}
}else {
// 未知操作系统
throw new RuntimeException("不支持当前操作系统转换文档");
}
return null;
}