libreoffice转PDF文件
package com.example.test.controller; import lombok.SneakyThrows; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileNotFoundException; public class libreOfficePDFController { private static final Logger log = LoggerFactory.getLogger(libreOfficePDFController.class); /** * 将office文档转成pdf文件 * @param sourcePath * @param targetPath */ @SneakyThrows public static boolean word2pdf(String sourcePath, String targetPath) { if (!new File(sourcePath).exists()) { throw new FileNotFoundException(); } // 配置环境变量 $PATH 使用如下: // String command = String.format("soffice --convert-to pdf:writer_pdf_Export %s --outdir %s", sourcePath, targetPath); // 未配置环境变量如下: String command = String.format("/Applications/LibreOffice.app/Contents/MacOS/soffice --convert-to pdf:writer_pdf_Export %s --outdir %s", sourcePath, targetPath); log.info("command=" + command); boolean flag = executeCommand(command); log.info("word2pdf: convert pdf complete. flag="+flag); return flag; } /** * 执行libreoffice的转换命令 * @param command * @return */ public static boolean executeCommand(String command){ try { long start = System.currentTimeMillis(); Process process = Runtime.getRuntime().exec(command); // 返回值是子线程执行完毕的返回值,返回0表示正常结束 int exitStatus = process.waitFor(); log.info("executeCommand: convert pdf exitStatus= " + exitStatus); // 销毁子进程 process.destroy(); long end = System.currentTimeMillis(); log.info("executeCommand: convert pdf cost time " + (end - start) + "ms"); return exitStatus == 0; }catch (Exception e){ log.error("executeCommand: runtime exec error", e); } return false; } @SneakyThrows public static void main(String[] args) { String source = "/tmp/pdf/test.DOCX"; String target = "/tmp/pdf/"; boolean inputStream = word2pdf(source, target); log.info(inputStream); } }
标签:
java
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 字符编码:从基础到乱码解决
· 提示词工程——AI应用必不可少的技术