java关于word转PDF的实现

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

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

<dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-words</artifactId>
            <version>21.11-jdk17</version>
            <exclusions>
                <exclusion>
                    <artifactId>logback-classic</artifactId>
                    <groupId>ch.qos.logback</groupId>
                </exclusion>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-logging</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

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

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

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

 /**
     * 获取 license 去除水印
     * 若不验证则转化出的pdf文档会有水印产生
     */
    public static void getLicense() {
        String licenseFilePath = "license.xml";
        try {
            InputStream is = DocUtil.class.getClassLoader().getResourceAsStream(licenseFilePath);
            License license = new License();
            license.setLicense(Objects.requireNonNull(is));
        } catch (Exception e) {
            log.error("license verify failed");
            e.printStackTrace();
        }
    }
/**
     * word 转 pdf
     *
     * @param wordFile word 文件路径
     * @param pdfFile  生成的 pdf 文件路径
     */
    public static void word2Pdf(String wordFile, String pdfFile) {
        File file = new File(pdfFile);

        if (file.getParentFile() != null && !file.getParentFile().exists()) {
            file.getParentFile().mkdir();
        }
        getLicense();
        try (FileOutputStream os = new FileOutputStream(new File(pdfFile))) {
            Document doc = new Document(wordFile);
            // 检查文档页数
            if (doc.getPageCount() == 0) {
                throw new BizException(BaseCode.ERROR, "Word文档没有内容或格式不受支持。");
            }
            doc.save(os, SaveFormat.PDF);
        } catch (Exception e) {
            log.error("word转pdf失败", e);
            throw new BizException(BaseCode.ERROR, "word转换PDF失败");
        }
    }

 

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

<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>

引入依赖添加工具类:

public static void documents4jWordToPdf(String wordPath, String pdfPath) {
        File inputWord = new File(wordPath);
        File outputFile = new File(pdfPath);
        try {
            InputStream docxInputStream = new FileInputStream(inputWord);
            OutputStream outputStream = new FileOutputStream(outputFile);
            IConverter converter = LocalConverter.builder().build();
            if (wordPath.split("\\.")[1].equals("doc")) {
                converter.convert(docxInputStream).as(DocumentType.DOC).to(outputStream).as(DocumentType.PDF).execute();
            } else {
                converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
            }
            outputStream.close();
            docxInputStream.close();
        } catch (Exception e) {
            throw new BizException(BaseCode.ERROR, "PDF转换失败");
        }
    }

        上面两种方式都可以实现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依赖不全

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

public static int poiWord2PDF(String source, String targetDir, String libreOfficeCommand) {
//   libreOfficeCommand Linux可执行文件的路径  source word完整路径  targeDir 则是PDF的存放目录,不带文件名称噢,文件名称会自动取source的文件名称作为名称
        String[] cmdArray = {
                libreOfficeCommand,
                "--headless",
                "--convert-to", "pdf:writer_pdf_Export",
                source,
                "--outdir", targetDir
        };
        int exitCode = 0;
        try {
            Process process = Runtime.getRuntime().exec(cmdArray);
            // simhei.ttf
            // 获取命令执行的输出
            InputStream inputStream = process.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            while ((line = reader.readLine()) != null) {
                log.info(line);
            }
            exitCode = process.waitFor();
            log.error("转换码:"+exitCode);
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new BizException(BaseCode.ERROR, "网络繁忙,请重试!");
        }
        return exitCode;
    }

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

  • 16
    点赞
  • 36
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值