目的:项目有需求word转pdf
实现思路:在服务器上安装libreoffice
libreoffice --convert-to pdf --outdir / /Invoice1706094532861.doc
代码工具类:
public class DocUtils {
public static File word2PDFCmd(String inputWordFilePath) throws Exception {
String command = "libreoffice --convert-to pdf --outdir " + "/" + " " + inputWordFilePath;
log.info("command:{}", command);
try {
executeLinuxShell(command);
} catch (Exception e) {
e.printStackTrace();
log.error(e.getMessage(), e);
}
File inputFile = new File(inputWordFilePath);
String name = "bid.pdf";
if (inputWordFilePath.endsWith("doc")) {
name = inputFile.getName().replace(".doc", ".pdf");
}
if (inputWordFilePath.endsWith("docx")) {
name = inputFile.getName().replace(".docx", ".pdf");
}
File outputFile = new File("/" + name);
return outputFile;
}
public static String executeLinuxShell(String shellPath) {
Runtime run = Runtime.getRuntime();
try {
Process process = run.exec(new String[]{"/bin/bash", "-c", shellPath});
String line;
BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuffer out = new StringBuffer();
while ((line = stdoutReader.readLine()) != null) {
out.append(line);
}
try {
process.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (stdoutReader != null) {
try {
stdoutReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
process.destroy();
return out.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}