一.资源准备
openOffice 下载地址:http://www.openoffice.org/download/index.html
jobConverter 相关jar包下载地址:https://download.youkuaiyun.com/download/mufeng633/10741295
二. 安装openOffice
window安装,直接傻瓜式安装即可。
Linux安装,可参考博文:https://www.cnblogs.com/goodcheap/p/7929986.html
- 如何启动openOffice服务
window安装好之后,开启服务并不在你安装的地址中,而是会在你的C盘创建启动符。
我本机安装地址:E:\OpenOffice
CMD 中 进入 盘符 C:\Program Files (x86)\OpenOffice 4\program 之后执行命令:
soffice -headless -accept=“socket,host=127.0.0.1,port=8100;urp;” -nofirststartwizard
查看是否安装成功:
a.查看端口对应的pid
netstat -ano|findstr “8100”
b.查看pid对应的服务程序名
tasklist|findstr “ipd值”
c. netstat -avn 查看8100端口号是否启用。 出现很多字符,则代表启动成功
出现上述,则代表服务启动。
三.代码Demo
public class OpenDemo {
// 将word格式的文件转换为pdf格式
public static void Word2Pdf(String srcPath, String desPath) throws IOException {
// 源文件目录
File inputFile = new File(srcPath);
if (!inputFile.exists()) {
System.out.println("源文件不存在!");
return;
}
// 输出文件目录
File outputFile = new File(desPath);
if (!outputFile.getParentFile().exists()) {
outputFile.getParentFile().exists();
}
System.out.println(outputFile);
// window 使用 调用openoffice服务线程 本机C盘!!!
String command = "C:\\Program Files (x86)\\OpenOffice 4\\program\\soffice -headless -accept=\"socket,host=127.0.0.1,port=8100;urp; -nofirststartwizard\"";
//Linux使用
// String command = "/opt/openoffice4/program/soffice -headless -accept=\"socket,host=127.0.0.1,port=8100;urp; -nofirststartwizard\"";
Process p = Runtime.getRuntime().exec(command);
// 连接openoffice服务
OpenOfficeConnection connection = new SocketOpenOfficeConnection(
"127.0.0.1", 8100);
connection.connect();
// 转换word到pdf
DocumentConverter converter = new OpenOfficeDocumentConverter(
connection);
converter.convert(inputFile, outputFile);
// 关闭连接
connection.disconnect();
// 关闭进程
p.destroy();
System.out.println("转换完成!");
}
public static void main(String[] args) throws IOException {
String srcPath = "E:\\A测试流\\档案信息化管理平台利用处完善建议20180831.docx";
String desPath = "E:\\\\A测试流\\转换323.pdf";
OpenDemo.Word2Pdf(srcPath, desPath);
}
到此已经完成,自己亲测可用。
这个Demo是参考该博文:https://www.cnblogs.com/warrior4236/p/5858755.html 感谢前辈大佬。