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