- docx4j
依赖:
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j-export-fo</artifactId>
<version>6.1.0</version>
</dependency>
/**
* docx4j
* @param docxPath
* @return
*/
public static String docxToPdf(String docxPath) {
OutputStream outputStream = null;
String pdfPath = docxPath.replace(".doc", ".pdf");
try {
WordprocessingMLPackage mlPackage = WordprocessingMLPackage.load(new File(docxPath));
mlPackage.setFontMapper(fontMapper);
outputStream = new BufferedOutputStream(new FileOutputStream(pdfPath));
FOSettings foSettings = Docx4J.createFOSettings();
foSettings.setWmlPackage(mlPackage);
Docx4J.toFO(foSettings, outputStream, Docx4J.FLAG_EXPORT_PREFER_XSL);
} catch (Exception ex) {
log.error("docx转PDF失败!", ex);
pdfPath = null;
} finally {
IOUtils.closeQuietly(outputStream);
}
return pdfPath;
}
- commons-io
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
/**
* commons-io
* @return
* 需要安装 libreoffice应用
* 转出来为 xml
*/
// 执行转换的方法
public static boolean wordConverterToPdf(String docxPath,String targetPath) throws IOException {
File file = new File(docxPath);
try {
String osName = System.getProperty("os.name");
String command = "";
if (osName.contains("Windows")) {
command = "soffice -display :0 --headless --convert-to pdf -outdir " + targetPath + " " + docxPath;
} else {
command = "doc2pdf --output=" + targetPath + File.separator + file.getName().replaceAll(".(?i)docx", ".pdf") + " " + docxPath;
}
String result = CommandExecute.executeCommand(command);
if (result.equals("") || result.contains("writer_pdf_Export")) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
throw e;
}
return false;
}