fix(pdf-tools): 水印中文显示成??? — 嵌入Droid Sans Fallback中文字体子集

- Helvetica(WinAnsi)无法编码中文被替换为?, 改为含非西文字符时按需加载
  public/fonts/DroidSansFallback.ttf + @cantoo/fontkit embedFont(subset)
- 新增依赖 @cantoo/fontkit; 纯英文水印保持原Helvetica路径不下载字体
- 浏览器端到端验证: 中文文本层HAS_CN=true无???, 英文回归通过
This commit is contained in:
jinghui committed 2026-11-14 22:42:27 +08:00
1 parent 78c348198d
commit 3aefc2633b
5 files changed
+74 -6

No files matched your search

+23 -2
View File
@@ -1,6 +1,7 @@
<script setup lang="ts">
import { useUserAuth } from '@/composable/user-auth';
import { degrees, PDFDocument, rgb } from '@cantoo/pdf-lib';
import fontkit from '@cantoo/fontkit';
import { getDocument, GlobalWorkerOptions } from 'pdfjs-dist';
import pdfWorkerUrl from 'pdfjs-dist/build/pdf.worker.min.js?url';
import { zipSync } from 'fflate';
@@ -387,16 +388,36 @@ async function doDecrypt() {
statusMsg.value = '解密完成(输出为高清图片版,无密码),点击下载';
}
// 中文字体(Droid Sans Fallback,覆盖 CJK):仅含非西文水印时按需加载,模块级缓存字节
let cjkFontBytes: ArrayBuffer | null = null;
async function getCjkFontBytes(): Promise<ArrayBuffer> {
if (!cjkFontBytes) {
const res = await fetch(`${import.meta.env.BASE_URL}fonts/DroidSansFallback.ttf`);
if (!res.ok) throw new Error('中文字体加载失败');
cjkFontBytes = await res.arrayBuffer();
}
return cjkFontBytes;
}
async function doWatermark() {
if (!wmText.value.trim()) {
throw new Error('请输入水印文字');
}
const src = await loadDoc(files.value[0]);
const pages = src.getPages();
const font = await src.embedFont('Helvetica');
const text = wmText.value.slice(0, 30);
// Helvetica(WinAnsi) 无法编码中文,会被替换成 ?;含非西文字符时嵌入中文字体子集
const needCjk = [...text].some(ch => ch.charCodeAt(0) > 0xff);
let font;
if (needCjk) {
src.registerFontkit(fontkit);
font = await src.embedFont(await getCjkFontBytes(), { subset: true });
}
else {
font = await src.embedFont('Helvetica');
}
for (const page of pages) {
const { width, height } = page.getSize();
const text = wmText.value.slice(0, 30);
const tw = font.widthOfTextAtSize(text, wmSize.value);
page.drawText(text, {
x: (width - tw) / 2,