Spring Boot中Excel/Word转PDF【封装好的工具类】【转换效果99%】【无水印】,超级好用!

🏆本文收录于「滚雪球学SpringBoot」专栏,手把手带你零基础入门Spring Boot,从入门到就业,助你早日登顶实现财富自由🚀;同时,欢迎大家关注&&收藏&&订阅!持续更新中,up!up!up!!

环境说明:Windows 10 + IntelliJ IDEA 2021.3.2 + Jdk 1.8

Excel转Pdf教学

1.引入第三方库与证书文件

这里我把这些先放到了

这里给出所需要的依赖包 aspose-cells-8.5.2.jar 和 excel-license.xml;关注公众号:「猿圈奇妙屋」 ,后台回复【转PDF】即可。

注意:使用前,先安装下载的aspose-cells-8.5.2.jar包,然后把excel-license.xml放在resources目录下就行了。【word转PDF写法也一样】

先把如上jar包跟excel-license.xml 证书配置放置到正确位置。

        <!-- 引入自定义 jar 包 -->
        <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-cells</artifactId>
            <version>8.5.2</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/src/main/resources/lib/aspose-cells-8.5.2.jar</systemPath>
        </dependency>

2.ExcelUtil.java工具类

如下我将大家看下,如何通过代码将Excel/Word转成PDF,转换效果99%,且无水印,绝绝子!

package com.hh.common.utils.fileUtil.excelToPdf;

import com.aspose.cells.License;
import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;
import com.hh.common.utils.file.FileUtils;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.file.Paths;

/**
 * Excel转PDF工具类
 *
 * @author bug菌
 * @Source 公众号:猿圈奇妙屋
 * @date: 2025-01-10 17:17
 */
public class ExcelUtil {

    /**
     * excel 转 pdf
     *
     * @param excelFilePath excel文件路径
     */
    public static void excel2pdf(String excelFilePath) {
        excel2pdf(excelFilePath, null, null);
    }

    /**
     * excel 转 pdf
     *
     * @param excelFilePath excel文件路径
     * @param convertSheets 需要转换的sheet
     */
    public static void excel2pdf(String excelFilePath, int[] convertSheets) {
        excel2pdf(excelFilePath, null, convertSheets);
    }

    /**
     * excel 转 pdf
     *
     * @param excelFilePath excel文件路径
     * @param pdfFilePath   pdf文件路径
     */
    public static void excel2pdf(String excelFilePath, String pdfFilePath) {
        excel2pdf(excelFilePath, pdfFilePath, null);
    }

    /**
     * excel 转 pdf
     *
     * @param excelFilePath excel文件路径
     * @param pdfFilePath   pdf文件路径
     * @param convertSheets 需要转换的sheet
     */
    public static void excel2pdf(String excelFilePath, String pdfFilePath, int[] convertSheets) {
        try {
            pdfFilePath = pdfFilePath == null ? getPdfFilePath(excelFilePath) : pdfFilePath;
            // 验证 License
            getLicense();
            Workbook wb = new Workbook(excelFilePath);
            FileOutputStream fileOS = new FileOutputStream(pdfFilePath);
            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();

            //删除强制每个sheet为一页的设置,允许Aspose自动分页
            pdfSaveOptions.setOnePagePerSheet(true);
            // 如果有指定需要转换的sheet,隐藏不需要转换的sheet
            if (null != convertSheets) {
                printSheetPage(wb, convertSheets);
            }
            // 将文件保存为PDF
            wb.save(fileOS, pdfSaveOptions);
            fileOS.flush();
            fileOS.close();
            System.out.println("convert success");
        } catch (Exception e) {
            System.out.println("convert failed");
            e.printStackTrace();
        }
    }

    /**
     * 获取生成的 pdf 文件路径,默认与源文件同一目录
     *
     * @param excelFilePath excel文件路径
     * @return 生成的 pdf 文件路径
     */
    public static String getPdfFilePath(String excelFilePath) {
        if (excelFilePath == null || excelFilePath.isEmpty()) {
            throw new IllegalArgumentException("Excel file path cannot be null or empty");
        }
        int dotIndex = excelFilePath.lastIndexOf('.');
        if (dotIndex > 0) {
            return excelFilePath.substring(0, dotIndex) + ".pdf";
        }
        // 如果文件路径中没有扩展名,直接追加 .pdf
        return excelFilePath + ".pdf";
    }


    /**
     * 获取 license 去除水印
     * 若不验证则转化出的pdf文档会有水印产生
     */
    public static void getLicense() {
        String licenseFilePath = "excel-license.xml";
        try {
            InputStream is = ExcelUtil.class.getClassLoader().getResourceAsStream(licenseFilePath);
            License license = new License();
            license.setLicense(is);
        } catch (Exception e) {
            System.out.println("license verify failed");
            e.printStackTrace();
        }
    }

    /**
     * 隐藏workbook中不需要的sheet页。
     *
     * @param sheets 显示页的sheet数组
     */
    public static void printSheetPage(Workbook wb, int[] sheets) {
        for (int i = 1; i < wb.getWorksheets().getCount(); i++) {
            wb.getWorksheets().get(i).setVisible(false);
        }
        if (null == sheets || sheets.length == 0) {
            wb.getWorksheets().get(0).setVisible(true);
        } else {
            for (int i = 0; i < sheets.length; i++) {
                wb.getWorksheets().get(i).setVisible(true);
            }
        }
    }

    public static void main(String[] args) {
        String srcFilePath = Paths.get(FileUtils.getRootPath("fileDir"), "/templates/差旅费报销单打印模板.xlsx").toString();
        ExcelUtil.excel2pdf(srcFilePath);
    }
}

Word转Pdf教学

1.引入第三方jar包及校验证书

        <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-cells</artifactId>
            <version>8.5.2</version>
            <scope>system</scope>
            <systemPath>${project.basedir}/src/main/resources/lib/aspose-words-15.8.0.jar</systemPath>
        </dependency>

2.DocUtil工具类

package com.hh.common.utils.fileUtil.excelToPdf;

import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import com.hh.common.utils.file.FileUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.file.Paths;
import java.util.Objects;

/**
 * word转PDF 工具类
 *
 * @author bug菌
 * @Source 公众号:猿圈奇妙屋
 * @date: 2025-01-16 9:24
 */
@Slf4j
public class DocUtil {

    /**
     * 获取 license 去除水印
     * 若不验证则转化出的pdf文档会有水印产生
     */
    private static void getLicense() {
        String licenseFilePath = "word-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().exists()) {
            file.getParentFile().mkdir();
        }
        getLicense();
        try (FileOutputStream os = new FileOutputStream(new File(pdfFile))) {
            Document doc = new Document(wordFile);
            doc.save(os, SaveFormat.PDF);
        } catch (Exception e) {
            log.error("word转pdf失败", e);
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String docFilePath = Paths.get(FileUtils.getRootPath("fileDir"), "/templates/演示文档导出.doc").toString();
        String pdfFilePath = Paths.get(FileUtils.getRootPath("fileDir"), "/templates/演示文档导出.pdf").toString();

        DocUtil.word2Pdf(docFilePath, pdfFilePath);
    }
}

打印效果演示

原excel

如下是我的一份Excel文件,作为演示文件进行。

运行测试类,将Excel文件转成PDF

excel转pdf效果

原word

运行测试类,将Word文件转成PDF

word转pdf效果

脚本获取方式

这里我把对应的脚本及jar包全部都打包放在了网盘,由于平台会和谐网盘链接,顾我放在了我的公众号:「猿圈奇妙屋」 ,后台回复【转PDF】关键字即可免费获取。

🧧福利赠与你🧧

  无论你是计算机专业的学生,还是对编程有兴趣的小伙伴,都建议直接毫无顾忌的学习此专栏「滚雪球学SpringBoot」,bug菌郑重承诺,凡是学习此专栏的同学,均能获取到所需的知识和技能,全网最快速入门SpringBoot,就像滚雪球一样,越滚越大, 无边无际,指数级提升。

最后,如果这篇文章对你有所帮助,帮忙给作者来个一键三连,关注、点赞、收藏,您的支持就是我坚持写作最大的动力。

同时欢迎大家关注公众号:「猿圈奇妙屋」 ,以便学习更多同类型的技术文章,免费白嫖最新BAT互联网公司面试题、4000G pdf电子书籍、简历模板、技术文章Markdown文档等海量资料。

✨️ Who am I?

我是bug菌,CSDN | 掘金 | InfoQ | 51CTO | 华为云 | 阿里云 | 腾讯云 等社区博客专家,C站博客之星Top30,华为云多年度十佳博主/价值贡献奖,掘金多年度人气作者Top40,掘金等各大社区平台签约作者,51CTO年度博主Top12,掘金/InfoQ/51CTO等社区优质创作者;全网粉丝合计 30w+;更多精彩福利点击这里;硬核微信公众号「猿圈奇妙屋」,欢迎你的加入!免费白嫖最新BAT互联网公司面试真题、4000G PDF电子书籍、简历模板等海量资料,你想要的我都有,关键是你不来拿。

-End-

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

bug菌¹

你的鼓励将是我创作的最大动力。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值