使用将Office文档转换PDF
Author:唐强
2015年4月14日下载安装文件
官网地址:/
根据操作系统下载相应版本,这里以windows为例。
安装
双击下载得到的exe文件,选择解压路径,这里解压到E:\setups\OpenOffice
双击解压得到的setup.exe,开始安装,值得注意的是:这里选择“自定义”安装,否则会默认安装到C盘,我将安装路径设为:D:\programs\OpenOffice
以服务的方式启动
1、先进入安装目录
cd D:\programs\OpenOffice\program
2、使用命令启动OpenOffice
soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" –nofirststartwizard
注:这里设置启动端口为8100
下载jodconverter
官网地址:/opensource/jodconverter
将jodconverter相关jar包导入项目
将下载的jodconverter-2.2.2.zip解压,jodconverter-2.2.2\lib下的jar包导入项目即可。
Java代码实现office文档转为pdf
public static void main(String[] args) {
//office文件存放目录
String officeFolder =
"D:\\pordata\\meetting\\officeFolder\\";
//pdf 文件输出目录
String pdfFolder = "D:\\pordata\\meetting\\pdfFolder\\";
OpenOfficeConnection connection = null;
try {
//连接服务,这里的localhost 是主机名,可为域名或IP地址
//8100为服务端口,与启动时设置的端口保持一致
//如果是本机,第一个参数可以不传,即:connection = new SocketOpenOfficeConnection(8100);
connection = new SocketOpenOfficeConnection("localhost", 8100);
connection.connect();
//要转换的文件名
String officeFileName = "云南移动会议资料分享APP.docx";
officeFileName = "mobile_enviroment.xlsx";
officeFileName = "工会团购.pptx";
//转换之后PDF的文件名
String pdfFileName = officeFileName.substring(0, stIndexOf("."))+".pdf";
File ofolder = new File(officeFolder);
if (!ofolder.exists()) {
ofolder.mkdirs();
}
File pfolder = new File(pdfFolder);
if (!pfolder.exists()) {
pfolder.mkdirs();
}
File officeFile = new File(officeFolder+officeFileName);
if (!officeFile.exists()) {
throw new Exception(officeFile.getAbsolutePath());
}
File pdfFile = new File(pdfFolder+pdfFileName);
//执行转换(大多数情况,这样就足够了)
DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
converter.convert(officeFile, pdfFile);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
} }。