欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 科技 > IT业 > org.apache.poi——将 office的各种类型文件(word等文件类型)转为 pdf

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

2025/5/7 0:41:48 来源:https://blog.csdn.net/u010804417/article/details/147600305  浏览:    关键词: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;}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词