[POI] ofdrw 2.1.0 转换pdf,部分ofd内部字体无法加载的问题

导致字体无法加载主要有两个因素: 1. 系统内没有安装对应的字体 2. 如果是ofd文件ofdrw首先去ofd解压文件抓取内部字体文件,如果这里出现异常会导致该部分字体无法正常显示。相关问题也可以看我这篇开发手账(一),下面是解决方案

一、对于没有安装字体的,需要安装字体,或者使用org.ofdrw.converter.FontLoader#scanFontDir(java.nio.file.Path)进行启动时扫描,可使用反射对以加载字体进行查看。

java 复制代码
Field namePathMapping = ReflectUtil.getField(FontLoader.class, "fontNamePathMapping");

Map<String, String> fontNamePathMapping = (Map<String, String>) ReflectUtil.getFieldValue(preload,namePathMapping);

System.out.println("已加载字体:" + JSONUtil.toJsonStr(fontNamePathMapping.keySet()));

二、ofdrw会走下面的方法org.ofdrw.converter.FontLoader#loadFontSimilarStream进行字体加载,可用看到它在首次会判断从ResourceLocator 加载ctFont,并没有对字体文件有效性进行判断,如果外部异常,则无法加载默认字体从而导致部分文字直接显示不出来。

解决方法 :可用直接注释掉内嵌字体绝对路径几行代码(我选用的),或者在异常报错处进行捕获并加载有效字体。需要这里都是需要对ofdrw源码进行修改

java 复制代码
    public InputStream loadFontSimilarStream(ResourceLocator rl, CT_Font ctFont) {
        byte[] buf = null;
        try {
            if (ctFont != null) {
                // 内嵌字体绝对路径
                ST_Loc fontFileLoc = ctFont.getFontFile();
                if (fontFileLoc != null) {
                    String fontAbsPath = rl.getFile(ctFont.getFontFile()).toAbsolutePath().toString();
                    buf = Files.readAllBytes(Paths.get(fontAbsPath));
                } else {

                    // 无法从内部加载时,通过相似字体查找
                    String similarFontPath = getReplaceSimilarFontPath(ctFont.getFamilyName(), ctFont.getFontName());
                    if (similarFontPath != null) {
                        buf = Files.readAllBytes(Paths.get(similarFontPath));
                    }
                }
            }
        } catch (Exception e) {
            if (DEBUG) {
                log.warn("无法加载字体: " + ctFont.getFamilyName() + " " + ctFont.getFontName() + " " + ctFont.getFontFile(), e);
            }
        }

        if (buf == null || buf.length == 0) {
            try {
                buf = Files.readAllBytes(DefaultFontPath);
            } catch (IOException e) {
                throw new RuntimeException("默认字体文件读取异常", e);
            }
        }
        return new ByteArrayInputStream(buf);
    }
相关推荐
持敬chijing3 小时前
JAVA与CVE漏洞4-Log4J 漏洞原理与实现
java·网络安全·log4j·系统安全·网络攻击模型·安全威胁分析
软件技术NINI4 小时前
基于SpringBoot的社区留守儿童帮扶系统
java·spring boot·后端
会编程的吕洞宾5 小时前
Spring Boot虚拟线程实战:吞吐提升3倍
java·经验分享·后端·spring
Rain的Java大神之路5 小时前
Spring Boot 4 + Spring AI 2.0 迁移实战:别急着改版本号,先算算你欠了多少债
java·后端·ai编程
代码不停6 小时前
Linux基础知识
java·linux·数据库
钉先生贾7 小时前
HarmonyOS 7.0 性能排障实战 43:图片与大资源加载抖动时,怎样区分解码、布局与状态更新
java·前端·harmonyos
FRing037 小时前
for循环、while循环、Java高级语法、数组
java·开发语言·后端·算法
syf0611137 小时前
Java Math 类详解:常用数学运算方法全解析
java·开发语言
bs_wa667 小时前
(赠源码)大学生社团管理系统72638-( java、PHP、python、C#、小程序、硬件、机器学习、大数据分析、深度学习,大屏、文案、毕设等)
java·spring boot·redis·mysql·tomcat·maven·idea
stormsha9 小时前
MySQL 连不上:2003 / 1045 / 1040 三张面孔与一个排查顺序
java·数据库·mysql