/**
* windows系统word转pdf
* @param pdfFile 转换后的pdf文件
* @param wordFile word源文件
*/
public static void winWordToPdf(File pdfFile, File wordFile) {
try (InputStream docxInputStream = new FileInputStream(wordFile);
OutputStream outputStream = new FileOutputStream(pdfFile) ){
IConverter converter = LocalConverter.builder().build();
converter.convert(docxInputStream)
.as(DocumentType.DOCX)
.to(outputStream)
.as(DocumentType.PDF).execute();
converter.shutDown();
} catch (FileNotFoundException e) {
log.error("word转换pdf失败", e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* linux系统word转pdf
* 使用LibreOffice转换。系统需安装LibreOffice
* 转换命令 libreoffice --invisible --convert-to pdf --outdir output_dir source_path
* 转换后的pdf文件名使用的是源文件的名称,所以如果要指定输出文件名称,就需把源文件名称改成想要输出的名称
* @param pdfFile 转换后的pdf文件
* @param wordFile word源文件
*/
public static void linuxWordToPdf(File pdfFile, File wordFile) {
// 获取word文件的绝对路径
String sourcePath = wordFile.getAbsolutePath();
// 获取pdf文件存放文件夹的绝对路径
String outDir = pdfFile.getAbsolutePath().substring(0, pdfFile.getAbsolutePath().lastIndexOf(File.separator));
// 构建LibreOffice的命令行工具命令
String command = "libreoffice --invisible --convert-to pdf --outdir " + outDir + " " + sourcePath;
log.info(command);
// 执行转换命令
try {
executeLinuxCmd(command);
} catch (Exception e) {
log.error("linuxWordToPdf linux环境word转换为pdf时出现异常:", e);
}
}
/**
* 执行命令行
*
* @param cmd 命令行
* @return
*/
private static boolean executeLinuxCmd(String cmd) {
try {
Process process = Runtime.getRuntime().exec(cmd);
process.waitFor();
} catch (InterruptedException e) {
log.error("executeLinuxCmd 执行Linux命令异常:", e);
Thread.currentThread().interrupt();
return false;
} catch (IOException e) {
log.error("获取系统命令执行环境异常", e);
}
return true;
}