当前位置:   article > 正文

java关于word转PDF的实现_java doc转pdf

java doc转pdf

       word转PDF这个功能在工作中还是非常常用的,但是word转PDF大部分都是需要收费的,或者说就是对页面的转换页数有限制,那么身为程序员当然是能白嫖就白嫖的了,那么具体怎么实现呢,小编这里有几种实现方式,希望可以帮到你。

        1.第一种则是使用aspose-words实现转换,这是一个免安装office工具的实现方式

  1. <dependency>
  2. <groupId>com.aspose</groupId>
  3. <artifactId>aspose-words</artifactId>
  4. <version>21.11-jdk17</version>
  5. <exclusions>
  6. <exclusion>
  7. <artifactId>logback-classic</artifactId>
  8. <groupId>ch.qos.logback</groupId>
  9. </exclusion>
  10. <exclusion>
  11. <groupId>org.springframework.boot</groupId>
  12. <artifactId>spring-boot-starter-logging</artifactId>
  13. </exclusion>
  14. </exclusions>
  15. </dependency>

引入依赖之后将名为license.xml的文件放在resource文件夹下,文件内容如下:

  1. <License>
  2. <Data>
  3. <Products>
  4. <Product>Aspose.Total for Java</Product>
  5. <Product>Aspose.Words for Java</Product>
  6. </Products>
  7. <EditionType>Enterprise</EditionType>
  8. <SubscriptionExpiry>20991231</SubscriptionExpiry>
  9. <LicenseExpiry>20991231</LicenseExpiry>
  10. <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
  11. </Data>
  12. <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>
  13. </License>

 依赖引入之后转换工具类:

  1. /**
  2. * 获取 license 去除水印
  3. * 若不验证则转化出的pdf文档会有水印产生
  4. */
  5. public static void getLicense() {
  6. String licenseFilePath = "license.xml";
  7. try {
  8. InputStream is = DocUtil.class.getClassLoader().getResourceAsStream(licenseFilePath);
  9. License license = new License();
  10. license.setLicense(Objects.requireNonNull(is));
  11. } catch (Exception e) {
  12. log.error("license verify failed");
  13. e.printStackTrace();
  14. }
  15. }
  1. /**
  2. * word 转 pdf
  3. *
  4. * @param wordFile word 文件路径
  5. * @param pdfFile 生成的 pdf 文件路径
  6. */
  7. public static void word2Pdf(String wordFile, String pdfFile) {
  8. File file = new File(pdfFile);
  9. if (file.getParentFile() != null && !file.getParentFile().exists()) {
  10. file.getParentFile().mkdir();
  11. }
  12. getLicense();
  13. try (FileOutputStream os = new FileOutputStream(new File(pdfFile))) {
  14. Document doc = new Document(wordFile);
  15. // 检查文档页数
  16. if (doc.getPageCount() == 0) {
  17. throw new BizException(BaseCode.ERROR, "Word文档没有内容或格式不受支持。");
  18. }
  19. doc.save(os, SaveFormat.PDF);
  20. } catch (Exception e) {
  21. log.error("word转pdf失败", e);
  22. throw new BizException(BaseCode.ERROR, "word转换PDF失败");
  23. }
  24. }

 

 2.第二种的话那便是poi转换了,poi转换需要添加以下依赖包

  1. <dependency>
  2. <groupId>com.documents4j</groupId>
  3. <artifactId>documents4j-local</artifactId>
  4. <version>1.0.3</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>com.documents4j</groupId>
  8. <artifactId>documents4j-transformer-msoffice-word</artifactId>
  9. <version>1.0.3</version>
  10. </dependency>

引入依赖添加工具类:

  1. public static void documents4jWordToPdf(String wordPath, String pdfPath) {
  2. File inputWord = new File(wordPath);
  3. File outputFile = new File(pdfPath);
  4. try {
  5. InputStream docxInputStream = new FileInputStream(inputWord);
  6. OutputStream outputStream = new FileOutputStream(outputFile);
  7. IConverter converter = LocalConverter.builder().build();
  8. if (wordPath.split("\\.")[1].equals("doc")) {
  9. converter.convert(docxInputStream).as(DocumentType.DOC).to(outputStream).as(DocumentType.PDF).execute();
  10. } else {
  11. converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
  12. }
  13. outputStream.close();
  14. docxInputStream.close();
  15. } catch (Exception e) {
  16. throw new BizException(BaseCode.ERROR, "PDF转换失败");
  17. }
  18. }

        上面两种方式都可以实现word转换PDF,不过第一种方式转换PDF会有一部分特殊的PDF转换不了,毕竟也是别人开发的,可能会有一些地方没有考虑全面,你懂得,不过可以根据自己需求看看,你们的word是否全部支持转换,第一种方式是不用再Linux上安装office工具支持的。

        第二种方式的话是poi实现的,众所周知poi很强大,但是poijar包版本管理却是个令人头疼的事情,搞不好,poi的某些jar包之间就相互冲突了,而且poi这种实现方式在转换过程中去调用了Windows底层文件去转换的,如果你要部署在Linux上面的话,那这个底层文件肯定是调不到了,导致转换失败,

        那前面两种都实现不了怎么办呢,别急,小编这里还有第三种实现方式,可能不是最优的,不过一定够用了,要通过下面这种方式在Linux上面实现的话,思路就是在java中调用Linux命令在office工具中实现转换,所以听了这个思路大概很多小伙伴应该就知道了,对,没错,这种方式实现的话是借助office工具,所以必然要在Linux上面安装office工具,以及至少一种字体,话不多说,上代码:

        首先安装libreoffice 安装时候需要注意:export LD_LIBRARY_PATH=/usr/lib64配上这条环境变量,你那个可执行文件名称是名为soffice.bin的文件,另外当你下载完成之后会发现libreoffice依赖不全

这时候就要你手动去安装这些,完成操作之后就可以使用了

  1. public static int poiWord2PDF(String source, String targetDir, String libreOfficeCommand) {
  2. // libreOfficeCommand Linux可执行文件的路径 source word完整路径 targeDir 则是PDF的存放目录,不带文件名称噢,文件名称会自动取source的文件名称作为名称
  3. String[] cmdArray = {
  4. libreOfficeCommand,
  5. "--headless",
  6. "--convert-to", "pdf:writer_pdf_Export",
  7. source,
  8. "--outdir", targetDir
  9. };
  10. int exitCode = 0;
  11. try {
  12. Process process = Runtime.getRuntime().exec(cmdArray);
  13. // simhei.ttf
  14. // 获取命令执行的输出
  15. InputStream inputStream = process.getInputStream();
  16. BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
  17. String line;
  18. while ((line = reader.readLine()) != null) {
  19. log.info(line);
  20. }
  21. exitCode = process.waitFor();
  22. log.error("转换码:"+exitCode);
  23. } catch (Exception e) {
  24. log.error(e.getMessage());
  25. throw new BizException(BaseCode.ERROR, "网络繁忙,请重试!");
  26. }
  27. return exitCode;
  28. }

都看到这里了,还希望各位老板动动发财的小手给老弟点点赞,分享给更多需要的人!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/670313
推荐阅读
相关标签
  

闽ICP备14008679号