由于目前的工作跟office打交道比较多,所以才有了此篇blog,需求是实现word转换pdf方便页面展示。之前lz采用的是jacob(仅支持windows)进行转换的,但是现在服务器改成linux显然不能用了,于是网上搜罗一圈,最终决定采用LibreOffice。(前提:需要安装jdk环境)
LibreOffice中文官网:
https://zh-cn.libreoffice.org/
下载合适的版本,本文下载的是6.1.6
一:windows下实现office转pdf
安装:直接一键默认安装
环境变量:在path前加入libreoffice安装路径(如:D:\Program Files\LibreOffice\program)
进入dos窗口输入soffice 如果弹出libreoffice界面则表示安装成功
java程序实现转换操作(原理通过cmd调用libreoffice指令)
public
static
boolean
convertOffice2PDF(String inputFile, String pdfFile){
long
start = System.currentTimeMillis();
String command;
boolean
flag;
String osName = System.getProperty(
"os.name"
);
if
(osName.contains(
"Windows"
)) {
command =
"cmd /c start soffice --headless --invisible --convert-to pdf:writer_pdf_Export "
+ inputFile +
" --outdir "
+ pdfFile;
}
else
{
command =
"libreoffice --headless --invisible --convert-to pdf:writer_pdf_Export "
+ inputFile +
" --outdir "
+ pdfFile;
flag = executeLibreOfficeCommand(command);
long
end = System.currentTimeMillis();
logger.debug(
"用时:{} ms"
, end - start);
return
flag;
* 执行command指令
* @param command
* @return
public
static
boolean
executeLibreOfficeCommand(String command) {
logger.info(
"开始进行转化......."
);
Process process;
try
{
logger.debug(
"convertOffice2PDF cmd : {}"
, command);
process = Runtime.getRuntime().exec(command);
}
catch
(IOException e) {
logger.error(
" convertOffice2PDF {} error"
, command, e);
return
false
;
int
exitStatus =
0
;
try
{
exitStatus = process.waitFor();
int
i = process.exitValue();
logger.debug(
"i----"
+ i);
}
catch
(InterruptedException e) {
logger.error(
"InterruptedException convertOffice2PDF {}"
, command, e);
return
false
;
if
(exitStatus !=
0
) {
logger.error(
"convertOffice2PDF cmd exitStatus {}"
, exitStatus);
}
else
{
logger.debug(
"convertOffice2PDF cmd exitStatus {}"
, exitStatus);
process.destroy();
logger.info(
"转化结束......."
);
return
true
;
二:Linux下实现office转pdf
安装:把下载下来的三个安装包上传到linux,采用 tar -xvf xxxxxx.tar.gz解压即可
然后进入RPMS包下,采用yum localinstall *.rpm安装rpm文件
测试是否安装成功:libreoffice6.1 -help
为了使用libreoffice创建别名
alias egrep=
'egrep --color=auto'
alias fgrep=
'fgrep --color=auto'
alias grep=
'grep --color=auto'
alias l.=
'ls -d .* --color=auto'
alias libreoffice=
'libreoffice6.0'
alias ll=
'ls -l --color=auto'
alias ls=
'ls --color=auto'
linux下面命令行测试word转pdf(其参数与windows下的参数大体相同)
命令:libreoffice –convert-to pdf:writer_pdf_Export /usr/lib/files/白头拟稿纸.doc –outdir /usr/lib/files/
关于word转pdf中文乱码问题处理
1:查看fonts目录:cat /etc/fonts/fonts.conf | grep fon
得知字体存放位置:/usr/share/fonts
2: 把Windows下的字体C:\Windows\Fonts下的宋体,即simsun.ttc上传到linux服务器
在fonts下新建Fonts文件 把字体上传到该路径下即可
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。