需安装open office插件
package com.jeecms.common.office2pdf;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeManager;
/**
* 将Office文档转换为PDF文档
* @author BaiFL
*/
public class Office2PDF {
/**
* 环境变量下面的url.properties的绝对路径
*/
private static final String URL_PATH = Thread.currentThread()
.getContextClassLoader().getResource("").getPath().replace("%20", " ")
+ "com/jeecms/common/office2pdf/url.properties";
/**
* 将Office文档转换为PDF
* @param sourceFile 源文件绝对路径
* 包括.doc, .docx, .xls, .xlsx, .ppt, .pptx等
* @return result 目标文件绝对路径
*/
public static String office2PDF(String sourceFile) {
//返回值
String result = null;
try {
File inputFile = new File(sourceFile);
if (!inputFile.exists()) {
return null; //找不到源文件, 则返回-1
}
/**
* 目标文件为原文件路径及原文件名.pdf,如果目标路径不存在, 则新建该路径
* sourceFile:“source.doc”
* targetFile:“source.pdf”
*/
String targetFile = sourceFile.substring(0, sourceFile.lastIndexOf(".")) + ".pdf";
File outputFile = new File(targetFile);
if (!outputFile.getParentFile().exists()) {
outputFile.getParentFile().mkdirs();
}
//从url.properties文件中读取OpenOffice的安装根目录
Properties prop = new Properties();
// 属性文件输入流
FileInputStream fis = new FileInputStream(URL_PATH);
// 将属性文件流装载到Properties对象中
prop.load(fis);
// 关闭流
fis.close();
//OpenOffice在windows/linux系统下的安装路径
String OPENOFFICE_HOME = prop.getProperty("OPENOFFICE_HOME");
if (OPENOFFICE_HOME == null){
return null; //找不到安装路径
}
//检查安装路径是否以“/”结尾
if (OPENOFFICE_HOME.charAt(OPENOFFICE_HOME.length() - 1) != '/') {
OPENOFFICE_HOME += "/";
}
DefaultOfficeManagerConfiguration configuration = new DefaultOfficeManagerConfiguration();
configuration.setOfficeHome(new File(OPENOFFICE_HOME));// 设置OpenOffice.org安装目录
configuration.setPortNumbers(8100); // 设置转换端口,默认为8100
configuration.setTaskExecutionTimeout(1000 * 60 * 1L);// 设置任务执行超时为1分钟
configuration.setTaskQueueTimeout(1000 * 60 * 60 * 24L);// 设置任务队列超时为24小时
OfficeManager officeManager = configuration.buildOfficeManager();
//启动服务
officeManager.start();
OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
//执行转换
converter.convert(inputFile, outputFile);
if (officeManager != null) {
officeManager.stop();
}
result = targetFile;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
}
return result;
}
}