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包,实际上是需要授权的,否则会有水印,是个隐患。
目录
相关文章
|
16小时前
|
Java
如何解决使用若依前后端分离打包部署到服务器上后主包无法找到从包中的文件的问题?如何在 Java 代码中访问 jar 包中的资源文件?
如何解决使用若依前后端分离打包部署到服务器上后主包无法找到从包中的文件的问题?如何在 Java 代码中访问 jar 包中的资源文件?
5 0
|
2天前
|
Java Spring
Java 效率编码 必备插件 Lombok 让代码更优雅
该内容是一个关于Lombok插件的教程摘要:介绍了Lombok用于减少Java开发中的模板代码,提升效率;讲解了如何在IntelliJ IDEA中安装Lombok插件,以及在pom.xml中添加依赖;并提到了@Data注解能自动生成getter/setter、equals、hashCode和toString方法,@Slf4j注解自动处理日志,@Builder用于构建对象,以及@AllArgsConstructor和@NoArgsConstructor注解生成构造函数。还鼓励探索更多Lombok的注解用法。
|
2天前
|
Java 关系型数据库 测试技术
Java代码一键生成数据库文档(案例详解)
Screw是一个自动化数据库文档生成工具,能根据数据库表结构快速生成简洁、多格式(HTML、Word、Markdown)的文档,支持MySQL、MariaDB等多数据库。它使用Freemarker模板,允许用户自定义样式。依赖包括HikariCP数据库连接池和对应JDBC驱动。通过在Java代码或Maven插件中配置,可方便生成文档。示例代码展示了如何在测试用例中使用Screw。文档效果依赖于数据库中的表和字段注释。
|
2天前
|
NoSQL Java API
java一行代码实现RESTFul接口
Spring Data REST是构建在Spring Data之上的库,可自动将repository转换为REST服务,支持JPA、MongoDB、Neo4j、GemFire和Cassandra。无需手动创建Service和Controller层。要开始,需配置JPA数据源,创建实体类和Repository接口。快速实现REST接口,只需引入spring-boot-starter-data-rest Maven依赖,并在Repository接口上添加@RepositoryRestResource注解。
|
5天前
|
Java 编译器 开发者
【JAVA】为什么代码会重排序
【JAVA】为什么代码会重排序
|
3天前
|
弹性计算 运维 Shell
|
4天前
|
JSON 监控 JavaScript
【LLM】基于LLama构建智能助理实现与PDF文件智能对话
【4月更文挑战第12天】构建智能助理服务,实现与PDF的自由对话
|
10天前
|
Python
python html(文件/url/html字符串)转pdf
python html(文件/url/html字符串)转pdf
9 0
|
14天前
|
Python
Python 合并多个 PDF 文件并建立书签目录
Python 合并多个 PDF 文件并建立书签目录
13 1
|
20天前
|
Web App开发 Windows
【Windows】 chrome 如何下载网站在线预览PDF文件,保存到本地
【Windows】 chrome 如何下载网站在线预览PDF文件,保存到本地
120 0