个人不建议用你这种方式实现office转pdf,因为你这需要加载dll文件。而且只能在window平台运行,Linux上面就不可以了。
推荐使用OppenOffice进行office转pdf,我可以把源码给你:
public static File office2PDF_File(String sourceFile) {
File file = null;
//OppenOffice的根路径
String OpenOffice_HOME = "C:\Program Files (x86)\OpenOffice 4";
if (OpenOffice_HOME.charAt(OpenOffice_HOME.length() - 1) != '/') {
OpenOffice_HOME += "/";
}
Process pro = null;
try {
String command = OpenOffice_HOME
+ "program/soffice -headless -accept=\"socket,host=127.0.0.1,port=8100;urp;\"\"-nofirststartwizard\"";
//OppenOffice连接失败 pro 会报空指针
pro = Runtime.getRuntime().exec(command);
OpenOfficeConnection connection = new SocketOpenOfficeConnection("127.0.0.1", 8100);
connection.connect();
String outputFilePath = generateDefaultOutputFilePath(sourceFile);
File inputFile = new File(sourceFile);
if (inputFile.exists()) {
File outputFile = new File(outputFilePath);
if (!outputFile.getParentFile().exists()) {
outputFile.getParentFile().mkdirs();
}
DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
converter.convert(inputFile, outputFile);
}
connection.disconnect();
pro.destroy();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
pro.destroy();
}
return outputFilePath ;
}
/**
* 如果未设置输出文件路径则按照源文件路径和文件名生成输出文件地址。例,输入为 D:/fee.xlsx 则输出为D:/fee.pdf
*/
public static String generateDefaultOutputFilePath(String inputFilePath) {
String outputFilePath = inputFilePath.replaceAll("." + getPostfix(inputFilePath), ".pdf");
return outputFilePath;
}
/**
* 获取inputFilePath的后缀名,如:"e:/test.pptx"的后缀名为:"pptx"
*/
public static String getPostfix(String inputFilePath) {
String[] p = inputFilePath.split("\\.");
if (p.length > 0) {
return p[p.length - 1];
} else {
return null;
}
}
你需要先下载OppenOffice软件装在电脑上。
对于你说的从数据库中查出来的不行,那肯定是你数据库中的文件地址就不对,自己好好检查一下
取消
评论