当前位置: 首页 > news >正文

org.apache.poi——将 office的各种类型文件(word等文件类型)转为 pdf

org.apache.poi——将 office的各种类型文件(word等文件类型)转为 pdf

  • 简介
  • 使用方法
    • word转pdf
  • 使用示例
    • word转pdf

简介

使用方法

word转pdf

Maven坐标为

		<dependency><groupId>com.documents4j</groupId><artifactId>documents4j-local</artifactId><version>1.0.3</version></dependency><dependency><groupId>com.documents4j</groupId><artifactId>documents4j-transformer-msoffice-word</artifactId><version>1.0.3</version></dependency>

核心方法如下所示。

//创建转换器
IConverter converter = LocalConverter.builder().build();
//转换需要的参数,依次是输入流、转换前的原类型、输出流、转换后的目标类型
boolean execute = converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).schedule().get();

使用示例

word转pdf

亲测有效

//    public static void main(String[] args) {
//        WordToPdfConverter converter = new WordToPdfConverter("C:\\Users\\LJH\\Desktop\\上传文件sha1为02.docx","C:\\Users\\LJH\\Desktop\\testConvert.pdf");
//        converter.convert();
//    }public class WordToPdfConverter {String sourcePath;String targetPath;public WordToPdfConverter(String sourcePath, String targetPath){this.sourcePath = sourcePath;this.targetPath = targetPath;}/*** 输入:目前被限制为Path.toUri()* return:可能为null* */public File convert() {File inputWord = new File(sourcePath.toUri());File outputPdf = new File(targetPath.toUri());InputStream docxInputStream = null;OutputStream outputStream = null;try {docxInputStream = new FileInputStream(inputWord);outputStream = new FileOutputStream(outputPdf);IConverter converter = LocalConverter.builder().build();boolean execute = converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).schedule().get();if (execute) {System.out.println("转换完毕 targetPath = " + outputPdf.getAbsolutePath());} else {System.out.println("[documents4J] word转pdf失败:");return null;}converter.shutDown();} catch (Exception e) {System.out.println("[documents4J] word转pdf失败:"+e.toString());return null;}finally {if (outputStream != null) {try {outputStream.close();} catch (IOException e) {throw new RuntimeException(e);}}if (docxInputStream != null) {try {docxInputStream.close();} catch (IOException e) {throw new RuntimeException(e);}}}return outputPdf;}
}

相关文章:

  • 14.Excel:排序和筛选
  • 19、权限控制:分院帽系统——React 19 RBAC实现
  • Kubernetes 安装 minikube
  • Day3:设置页面全局渐变线性渐变背景色uniapp壁纸实战
  • qmt下载的数据放在了哪里了?
  • 利用flask设计接口
  • Linux 的网络卡
  • 黑马点评day01(基于Redis)
  • C++ 多态:原理、实现与应用
  • 补充:建立实体类与数据表的映射关系
  • C盘莫名其妙一直变大
  • 从github的插件直接导入unity
  • stm32week14
  • Android运行时ART加载类和方法的过程分析
  • 学习黑客 ATTCK
  • 多段线和二维多段线的区别及顶点遍历
  • Docker 服务搭建
  • 【windows操作技巧】设置应用的开机自启动
  • C++入门☞关于类的一些特殊知识点
  • AI跑得快,MCP来加速——模型计算平台在训练与推理中的硬核作用
  • 四人自驾游宣恩因酒店爆满无处住宿,求助文旅局后住进局长家
  • 华尔兹转岗与鲁比奥集权:特朗普政府人事震荡背后的深层危机
  • 新能源车盈利拐点:8家上市车企去年合计净利854亿元,多家扭亏
  • 上海:以税务支持鼓励探索更多的创新,助力企业出海
  • 剑指3000亿产业规模,机器人“武林大会”背后的无锡“野望”
  • 金砖国家外长会晤落幕,外交部:发出了反对单边霸凌行径的“金砖声音”