[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);
    }
相关推荐
code bean20 小时前
【CMake】为什么需要清理 CMake 缓存文件?深入理解 CMake 生成器切换机制
java·spring·缓存
selt79120 小时前
Redisson之RedissonLock源码完全解析
android·java·javascript
RestCloud20 小时前
智能制造的底层基建:iPaaS 如何统一 ERP、MES 与 WMS 的数据流
java·wms·erp·数据传输·ipaas·mes·集成平台
guslegend20 小时前
SpringBoot源码剖析
java
皮卡龙20 小时前
Spring MVC 接收请求参数的核心
java·spring·mvc
爱笑的眼睛1121 小时前
FastAPI 路由系统深度探索:超越基础 CRUD 的高级模式与架构实践
java·人工智能·python·ai
武子康21 小时前
Java-193 Spymemcached 深入解析:线程模型、Sharding 与序列化实践全拆解
java·开发语言·redis·缓存·系统架构·memcached·guava
韩凡21 小时前
HashMap的理解与结构
java·开发语言·哈希算法
hhzz1 天前
Spring Boot整合Activiti的项目中实现抄送功能
java·spring boot·后端