Java【代码 16】将word、excel文件转换为pdf格式和将pdf文档转换为image格式工具类分享(Gitee源码)aspose转换中文乱码问题处理

简介: 【2月更文挑战第3天】Java 将word、excel文件转换为pdf格式和将pdf文档转换为image格式工具类分享(Gitee源码)aspose转换中文乱码问题处理

1.感谢

感谢小伙伴儿的分享:
不羁
郭中天
整合调整后的工具类Gitee地址https://gitee.com/yuanzhengme/java_application_aspose_demo

2.包含的工具类

● WordToPdfUtil用于将word文档转换为pdf格式的工具类
● ExcelToPdfUtil用于将excel文档转换为pdf格式的工具类
● PdfToImageUtil用于将pdf文档转换为image格式的工具类

3.lib文件说明

3.1 使用的

● 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端中文出现乱码时使用)

3.2 未使用的

● aspose-words-15.12.0-jdk16.jar 未测试
● aspose-pdf-22.4.cracked.jar 将pdf转换为其他格式【破解版效果不佳】
● aspose-pdf-22.4.jar 将pdf转换为其他格式【未破解效果依然不佳】

4.核心代码

4.1 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();
            }

        }
    }

4.2 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();
            }
        }
    }

4.3 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();
        }
    }

6.问题处理

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

    6.1 Word中文无法转换

    在Linux环境下,如果转换后的pdf文件无中文,在WordToPdfUtil转换方法里添加以下代码:
    // 设置字体
    String realPath = new ApplicationHome(WordToPdfUtil.class).getSource().getParentFile().toString();
    FontSettings.setFontsFolder(realPath + File.separatorChar + "font", false);
    

    6.2 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包,实际上是需要授权的,否则会有水印,是个隐患。
目录
相关文章
|
1月前
|
Java
有关Java发送邮件信息(支持附件、html文件模板发送)
有关Java发送邮件信息(支持附件、html文件模板发送)
31 1
|
1月前
|
Java
java中替换文件内容
java中替换文件内容
14 1
|
1月前
|
Java API
Java中文件与输入输出
Java中文件与输入输出
|
1月前
|
Java
java实现遍历树形菜单方法——映射文件VoteTree.hbm.xml
java实现遍历树形菜单方法——映射文件VoteTree.hbm.xml
10 0
|
1月前
|
Java
java程序导出堆文件
java程序导出堆文件
|
1月前
|
SQL Oracle Java
sql文件批处理程序-java桌面应用
sql文件批处理程序-java桌面应用
25 0
|
1月前
|
存储 Java 文件存储
如何用 Java 压缩 ZIP 文件?
【2月更文挑战第21天】
35 1
|
5天前
|
Java 关系型数据库 MySQL
Elasticsearch【问题记录 01】启动服务&停止服务的2类方法【及 java.nio.file.AccessDeniedException: xx/pid 问题解决】(含shell脚本文件)
【4月更文挑战第12天】Elasticsearch【问题记录 01】启动服务&停止服务的2类方法【及 java.nio.file.AccessDeniedException: xx/pid 问题解决】(含shell脚本文件)
33 3
|
21小时前
|
存储 前端开发 Java
Java实现文件分片上传
Java实现文件分片上传
4 0
|
1月前
|
Java 数据库连接 API
Java 学习路线:基础知识、数据类型、条件语句、函数、循环、异常处理、数据结构、面向对象编程、包、文件和 API
Java 是一种广泛使用的、面向对象的编程语言,始于1995年,以其跨平台性、安全性和可靠性著称,应用于从移动设备到数据中心的各种场景。基础概念包括变量(如局部、实例和静态变量)、数据类型(原始和非原始)、条件语句(if、else、switch等)、函数、循环、异常处理、数据结构(如数组、链表)和面向对象编程(类、接口、继承等)。深入学习还包括包、内存管理、集合框架、序列化、网络套接字、泛型、流、JVM、垃圾回收和线程。构建工具如Gradle、Maven和Ant简化了开发流程,Web框架如Spring和Spring Boot支持Web应用开发。ORM工具如JPA、Hibernate处理对象与数
94 3