基于Java实现将word,excel文件转换为pdf的工具类

 更新时间:2025年08月01日 10:30:37   作者:yuanzhengme  
这篇文章主要为大家详细介绍了如何使用Java编写一个工具类,可以实现将word,excel文件转换为pdf格式和将pdf文档转换为image格式,希望对大家有所帮助

包含的工具类

WordToPdfUtil用于将word文档转换为pdf格式的工具类

ExcelToPdfUtil用于将excel文档转换为pdf格式的工具类

PdfToImageUtil用于将pdf文档转换为image格式的工具类

lib文件说明

使用的

aspose-words-15.8.0-jdk16.jar 将word文档转换为pdf需要引入

aspose-cells-8.5.2.jar 将excel文档转换为pdf需要引入

aspose-cells-20.7.jar 将excel文档转换为pdf需要引入(Linux端中文出现乱码时使用)

未使用的

aspose-words-15.12.0-jdk16.jar 未测试

aspose-pdf-22.4.cracked.jar 将pdf转换为其他格式【破解版效果不佳】

aspose-pdf-22.4.jar 将pdf转换为其他格式【未破解效果依然不佳】

核心代码

WordToPdfUtil

    /**
     * word 转 pdf
     *
     * @param wordFilePath word文件路径
     * @param pdfFilePath  pdf文件路径
     */
    public static void convert(String wordFilePath, String pdfFilePath) {
        FileOutputStream fileOutputStream = null;
        try {
            pdfFilePath = pdfFilePath == null ? getPdfFilePath(wordFilePath) : pdfFilePath;
            setLicense();
            File file = new File(pdfFilePath);
            fileOutputStream = new FileOutputStream(file);
            Document doc = new Document(wordFilePath);
            doc.save(fileOutputStream, SaveFormat.PDF);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                assert fileOutputStream != null;
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

ExcelToPdfUtil

    /**
     * excel 转 pdf
     *
     * @param excelFilePath excel文件路径
     * @param pdfFilePath   pdf文件路径
     * @param convertSheets 需要转换的sheet
     */
    public static void convert(String excelFilePath, String pdfFilePath, int[] convertSheets) {
        FileOutputStream fileOutputStream = null;
        try {
            pdfFilePath = pdfFilePath == null ? getPdfFilePath(excelFilePath) : pdfFilePath;
            // 设置License
            setLicense();
            // 读取excel文件
            Workbook wb = new Workbook(excelFilePath);
            fileOutputStream = new FileOutputStream(pdfFilePath);
            // 设置pdf格式
            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
            pdfSaveOptions.setOnePagePerSheet(true);
            if (null != convertSheets) {
                printSheetPage(wb, convertSheets);
            }
            wb.save(fileOutputStream, pdfSaveOptions);
            fileOutputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                assert fileOutputStream != null;
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

PdfToImageUtil

    /**
     * 根据参数将全部的PDF转换为Image
     *
     * @param pdfFilePath   PDF文件路径
     * @param imageFileDir  图片存储目录
     * @param imageFileName 图片存储文件没
     * @param type          图片类型
     */
    public static void convertAllPage(String pdfFilePath, String imageFileDir, String imageFileName, String type) {
        System.setProperty("sun.java2d.cmm", "sun.java2d.cmm.kcms.KcmsServiceProvider");
        // 图片类型
        if (type == null || "".equals(type)) {
            type = IMAGE_TYPE_JPG;
        }
        // 1.加载PDF文件
        File file = new File(pdfFilePath);
        // 2.生成JPG图片的文件夹
        imageFileDir = imageFileDir == null ? getImageFileDir(pdfFilePath) : imageFileDir;
        imageFileName = imageFileName == null ? getImageFileName(pdfFilePath) : imageFileName;
        try {
            PDDocument pdDocument = PDDocument.load(file);
            PDFRenderer renderer = new PDFRenderer(pdDocument);
            int pageCount = pdDocument.getNumberOfPages();

            for (int i = 0; i < pageCount; i++) {
                BufferedImage image = renderer.renderImageWithDPI(i, 144);
                ImageIO.write(image, type,
                        new File(imageFileDir.concat(File.separator).concat(imageFileName).concat("_")
                                .concat(String.valueOf(i + 1)).concat(".").concat(type)));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

问题处理

都需要将字体文件simsun.ttc上传到jarPath/font目录下。

Word中文无法转换

在Linux环境下,如果转换后的pdf文件无中文,在WordToPdfUtil转换方法里添加以下代码:

// 设置字体
String realPath = new ApplicationHome(WordToPdfUtil.class).getSource().getParentFile().toString();
FontSettings.setFontsFolder(realPath + File.separatorChar + "font", false);

Excel中文无法转换

使用aspose-cells-20.7.jar:

<dependency>
	<groupId>com.aspose.cells</groupId>
	<artifactId>aspose-cells</artifactId>
	<version>20.7</version>
	<scope>system</scope>
	<systemPath>${project.basedir}/lib/aspose-cells-20.7.jar</systemPath>
</dependency>

并在ExcelToPdfUtil转换方法里添加以下代码:

// 设置字体
String realPath = new ApplicationHome(WordToPdfUtil.class).getSource().getParentFile().toString();
String fontDir = realPath + File.separatorChar + "font";
IndividualFontConfigs individualFontConfigs = new IndividualFontConfigs();
individualFontConfigs.setFontFolder(fontDir, false);
LoadOptions loadOptions = new LoadOptions();
loadOptions.setFontConfigs(individualFontConfigs);
// 读取excel文件
Workbook wb = new Workbook(excelFilePath, loadOptions);

7.总结

PDF转换为其他格式的方法效果不佳,遇到好的方案会进行补充。

主要用到aspose的jar包,实际上是需要授权的,否则会有水印,是个隐患。

到此这篇关于基于Java实现将word,excel文件转换为pdf的工具类的文章就介绍到这了,更多相关Java word与excel转pdf内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • SpringBoot快速实现接口消息加密的过程详解

    SpringBoot快速实现接口消息加密的过程详解

    在项目中,为了保证数据的安全,我们常常会对传递的数据进行加密,常用的加密算法包括对称加密(AES)和非对称加密(RSA),博主选取码云上最简单的API加密项目进行下面的讲解,需要的朋友可以参考下
    2023-11-11
  • Java如何把map分割成多个map

    Java如何把map分割成多个map

    这篇文章主要介绍了Java如何把map分割成多个map,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧
    2024-08-08
  • springBoot整合RocketMQ及坑的示例代码

    springBoot整合RocketMQ及坑的示例代码

    这篇文章主要介绍了springBoot整合RocketMQ及坑的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-11-11
  • java实现带有背景图片的窗体

    java实现带有背景图片的窗体

    这篇文章主要为大家详细介绍了java实现带有背景图片的窗体,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-03-03
  • Java缺失区间的查找方法

    Java缺失区间的查找方法

    在 Java 的算法世界里,有许多有趣又具有挑战性的问题等待我们去探索,今天,跟着小编一起来深入研究缺失区间的查找秘籍,文中有详细的代码示例供大家参考,需要的朋友可以参考下
    2025-02-02
  • SpringBoot整合redis使用缓存注解详解

    SpringBoot整合redis使用缓存注解详解

    这篇文章主要介绍了SpringBoot整合redis使用缓存注解详解,@Cacheable在方法执行前判断对应缓存是否存在,如果存在直接返回缓存结果,否者执行方法将结果缓存,适用于查询类,需要的朋友可以参考下
    2024-01-01
  • Spring Boot 2.X 快速集成单元测试解析

    Spring Boot 2.X 快速集成单元测试解析

    这篇文章主要介绍了Spring Boot 2.X 快速集成单元测试解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-08-08
  • Spring容器刷新prepareRefresh第一步

    Spring容器刷新prepareRefresh第一步

    这篇文章主要为大家介绍了Spring容器刷新prepareRefresh第一步示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-03-03
  • java根据负载自动抓取jstack dump详情

    java根据负载自动抓取jstack dump详情

    这篇文章主要介绍了java根据负载自动抓取jstack dump详情,文章围绕主题展开详细的内容介绍,具有一定的参考价值,需要的小伙伴可以参考一下
    2022-09-09
  • SpringBoot之自定义banner使用代码实例

    SpringBoot之自定义banner使用代码实例

    这篇文章主要介绍了SpringBoot之自定义banner使用代码实例,在Spring Boot中,你可以通过定制Banner来个性化你的应用程序启动时的输出,Banner是一个在应用程序启动时显示的ASCII艺术字形式的标志,用于增加应用程序的识别度和个性化,需要的朋友可以参考下
    2024-01-01

最新评论