kongdeqiang
2026-10-12 7c687dd3c8fba9f7632f5e29d94a708e5f497abd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
package com.custom.webui.util;
 
import com.custom.webui.config.props.ExportProperties;
import com.custom.webui.exception.BusinessException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.fontbox.ttf.CmapLookup;
import org.apache.fontbox.ttf.TTFParser;
import org.apache.fontbox.ttf.TrueTypeCollection;
import org.apache.fontbox.ttf.TrueTypeFont;
import org.apache.pdfbox.io.RandomAccessReadBufferedFile;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.springframework.stereotype.Component;
 
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
 
/**
 * 为 PDF 导出准备一份**能写中文**的字体。
 *
 * <h2>为什么必须嵌入字体</h2>
 * PDF 内置的 14 个标准字体(Helvetica / Times 等)只覆盖 Latin-1,
 * 写中文会直接抛 {@code IllegalArgumentException: No glyph for U+4E2D}。
 * 而「引用系统里的 CJK 标准字体」(STSong-Light + UniGB-UCS2-H)虽然省事,
 * 但阅读器不一定装了对应字体 —— 用户拿到的是一个打开就空白或乱码的文件,
 * 而导出文件往往就是用来长期保存和发给别人的,不能赌对方的环境。
 * 所以这里从系统里找一份真实的中文字体,**按子集嵌入**(只带用到的字形,
 * 一个几百字的中文对话最终 PDF 通常只有几十 KB)。
 *
 * <h2>为什么用 cmap 判断字形,而不是 PDType0Font.hasGlyph()</h2>
 * 这是实测踩到的坑:{@code PDType0Font.hasGlyph(',')} 对 Arial Unicode 返回
 * <b>false</b>,而同一份字体的 cmap 里 U+FF0C 明明有字形(glyphId=6632)。
 * 如果信了它,会有两个后果:
 * <ol>
 *   <li>字体选择阶段会把 Arial Unicode 误判成「不含中文」而跳过;</li>
 *   <li>文本清洗阶段会把每个全角逗号都替换成方框 —— 中文回答里满地 □。</li>
 * </ol>
 * 因此这里统一用 fontbox 的 {@link CmapLookup#getGlyphId(int)}
 * (返回 0 才代表真的没有这个字形)。
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class PdfFontSupport {
 
    /**
     * 兜底候选字体,按顺序探测。
     *
     * <p>只放**单体**字体文件(.ttf / .otf)与常见的字体集合(.ttc):
     * .ttc 会由 {@link TrueTypeCollection} 逐个挑出含中文字形的那一款。
     */
    private static final List<String> CANDIDATES = List.of(
            // macOS
            "/System/Library/Fonts/Supplemental/Arial Unicode.ttf",
            "/Library/Fonts/Arial Unicode.ttf",
            "/System/Library/Fonts/Supplemental/Songti.ttc",
            "/System/Library/Fonts/PingFang.ttc",
            "/System/Library/Fonts/Hiragino Sans GB.ttc",
            // Linux
            "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
            "/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc",
            "/usr/share/fonts/opentype/noto/NotoSerifCJK-Regular.ttc",
            "/usr/share/fonts/truetype/wqy/wqy-zenhei.ttc",
            "/usr/share/fonts/truetype/arphic/uming.ttc",
            "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
            // Windows
            "C:/Windows/Fonts/msyh.ttc",
            "C:/Windows/Fonts/msyh.ttf",
            "C:/Windows/Fonts/simsun.ttc",
            "C:/Windows/Fonts/simhei.ttf"
    );
 
    /** 用来判断「这份字体到底认不认识中文」的探针字符 */
    private static final int[] CJK_PROBE = {'中', '文', ',', '。'};
 
    private final ExportProperties properties;
 
    private volatile File cachedFont;
    private volatile boolean probed;
 
    /**
     * 为给定文档打开字体。
     *
     * @throws BusinessException 找不到可用字体时抛出,message 里带具体配置方法
     */
    public PdfFontHandle open(PDDocument document) {
        File file = resolveFontFile();
        if (file == null) {
            throw BusinessException.serverError(
                    "导出 PDF 需要一份中文字体,但系统里没有探测到可用的。"
                            + "请在配置里显式指定:webui.export.pdf-font-path=/path/to/中文字体.ttf"
                            + "(TXT / JSON 导出不受影响)");
        }
 
        try {
            if (isCollection(file)) {
                TrueTypeCollection collection = new TrueTypeCollection(file);
                TrueTypeFont picked = pickFace(collection);
                if (picked == null) {
                    closeQuietly(collection);
                    throw BusinessException.serverError("字体 " + file
                            + " 里没有找到包含中文字形的字体,请改配 webui.export.pdf-font-path");
                }
                return new PdfFontHandle(PDType0Font.load(document, picked, true),
                        new Closeable[]{collection}, picked.getUnicodeCmapLookup());
            }
 
            RandomAccessReadBufferedFile raf = new RandomAccessReadBufferedFile(file);
            TrueTypeFont ttf = new TTFParser().parse(raf);
            CmapLookup lookup = ttf.getUnicodeCmapLookup();
            if (lookup == null || !knowsChinese(lookup)) {
                closeQuietly(ttf);
                closeQuietly(raf);
                throw BusinessException.serverError("字体 " + file
                        + " 不含中文字形,请改配 webui.export.pdf-font-path");
            }
            // 注意:子集化发生在 save() 阶段,所以 ttf / raf 必须活到那时,
            // 由 handle 统一关闭(见 PdfFontHandle 的说明)
            return new PdfFontHandle(PDType0Font.load(document, ttf, true),
                    new Closeable[]{ttf, raf}, lookup);
        } catch (BusinessException e) {
            throw e;
        } catch (IOException e) {
            throw BusinessException.serverError("加载 PDF 字体失败:" + file + " —— " + e.getMessage());
        }
    }
 
    /** 供启动自检展示 */
    public String describe() {
        File file = resolveFontFile();
        if (file == null) {
            return "未找到中文字体 —— PDF 导出不可用(TXT / JSON 仍可用)。"
                    + "可配置 webui.export.pdf-font-path 指定字体文件";
        }
        return "已就绪:" + file;
    }
 
    // ------------------------------------------------------------------
    // 字体探测
    // ------------------------------------------------------------------
 
    private File resolveFontFile() {
        if (probed) {
            return cachedFont;
        }
        synchronized (this) {
            if (probed) {
                return cachedFont;
            }
 
            List<String> paths = new ArrayList<>();
            if (properties.getPdfFontPath() != null && !properties.getPdfFontPath().isBlank()) {
                // 显式配置优先,且**只**用它:用户指定了字体却静默回退到别的字体,
                // 会让人以为配置没生效(本项目已经踩过好几次「配置被静默忽略」的坑)
                paths.add(properties.getPdfFontPath().trim());
            } else {
                paths.addAll(CANDIDATES);
            }
 
            for (String path : paths) {
                File file = new File(path);
                if (!file.isFile() || file.length() == 0) {
                    continue;
                }
                if (recognizesChinese(file)) {
                    log.info("PDF 导出将使用中文字体: {}", file);
                    cachedFont = file;
                    probed = true;
                    return cachedFont;
                }
                log.debug("字体 {} 存在但不含中文字形,跳过", file);
            }
 
            log.warn("未找到可用于 PDF 导出的中文字体,PDF 导出将不可用(TXT/JSON 不受影响)");
            probed = true;
            return null;
        }
    }
 
    /**
     * 从字体集合里挑一款。
     *
     * <p>两轮:先找名字里带 Regular 的(字体集合的第一个 face 往往是 Black / Bold
     * 之类的重字重,导出的正文会粗得没法看),找不到再退回第一个含中文字形的。
     */
    private TrueTypeFont pickFace(TrueTypeCollection collection) throws IOException {
        List<TrueTypeFont> faces = new ArrayList<>();
        collection.processAllFonts(faces::add);
        if (faces.isEmpty()) {
            return null;
        }
 
        TrueTypeFont regular = null;
        TrueTypeFont fallback = null;
        for (TrueTypeFont face : faces) {
            CmapLookup lookup = face.getUnicodeCmapLookup();
            if (lookup == null || !knowsChinese(lookup)) {
                continue;
            }
            if (fallback == null) {
                fallback = face;
            }
            String name = face.getName();
            if (name != null) {
                String lower = name.toLowerCase();
                if (lower.contains("regular") || lower.contains("light")) {
                    regular = face;
                    break;
                }
            }
        }
        return regular != null ? regular : fallback;
    }
 
    private boolean recognizesChinese(File file) {
        try {
            if (isCollection(file)) {
                try (TrueTypeCollection collection = new TrueTypeCollection(file)) {
                    return pickFace(collection) != null;
                }
            }
            try (RandomAccessReadBufferedFile raf = new RandomAccessReadBufferedFile(file)) {
                TrueTypeFont ttf = new TTFParser().parse(raf);
                try {
                    CmapLookup lookup = ttf.getUnicodeCmapLookup();
                    return lookup != null && knowsChinese(lookup);
                } finally {
                    closeQuietly(ttf);
                }
            }
        } catch (Exception e) {
            log.debug("字体探测失败 {}: {}", file, e.getMessage());
            return false;
        }
    }
 
    /** glyphId 为 0 表示 .notdef,即这份字体确实没有该字形 */
    private boolean knowsChinese(CmapLookup lookup) {
        try {
            for (int cp : CJK_PROBE) {
                if (lookup.getGlyphId(cp) == 0) {
                    return false;
                }
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }
 
    private boolean isCollection(File file) {
        return file.getName().toLowerCase().endsWith(".ttc");
    }
 
    private void closeQuietly(Closeable closeable) {
        try {
            closeable.close();
        } catch (Exception ignored) {
            // 关闭失败不影响主流程
        }
    }
 
    /**
     * 字体句柄:给出绘图用的 {@code PDType0Font},同时把**底层字体资源**
     * 与**字形判断能力**一起带出来。
     *
     * <p>三样东西缺一不可,所以绑在一个句柄里:
     * <ul>
     *   <li>{@code font} —— 真正往 PDF 里写字的对象</li>
     *   <li>底部资源 —— 用 {@code embedSubset=true} 加载时,PDFBox 是
     *       <b>延迟到 {@code save()}</b> 才去读字体文件裁子集的;
     *       若在此之前关闭了文件句柄,保存时会报「TTF is closed」
     *       这种与导出内容毫不相干的错误</li>
     *   <li>{@code cmap} —— 判断某个字符有没有字形(用来把 emoji 之类的
     *       缺字形字符替换掉,否则一个表情符号就能让整份导出失败)</li>
     * </ul>
     *
     * <p>用法固定为:
     * <pre>
     * try (var handle = fontSupport.open(doc)) {
     *     ... 写内容 ...
     *     doc.save(out);      // 子集化发生在这里,此时字体必须还活着
     * }
     * </pre>
     */
    public static final class PdfFontHandle implements Closeable {
 
        private final PDType0Font font;
        private final Closeable[] resources;
        private final CmapLookup cmap;
 
        PdfFontHandle(PDType0Font font, Closeable[] resources, CmapLookup cmap) {
            this.font = font;
            this.resources = resources;
            this.cmap = cmap;
        }
 
        public PDType0Font font() {
            return font;
        }
 
        /** 该码位在这份字体里是否有字形(false 时应替换成占位符) */
        public boolean hasGlyph(int codePoint) {
            if (cmap == null) {
                // 拿不到 cmap 时保守地认为「有」,交给 PDFBox 去报错,
                // 也好过把正常文字大量替换成方框
                return true;
            }
            try {
                return cmap.getGlyphId(codePoint) != 0;
            } catch (Exception e) {
                return true;
            }
        }
 
        @Override
        public void close() throws IOException {
            for (Closeable resource : resources) {
                resource.close();
            }
        }
    }
}