如何在pdf-lib中添加自定义字体?遇Unknown font format错误求助
问题
尝试为pdf-lib库添加自定义字体时,始终提示Unknown font format错误,试过TTF、OTF、WOFF、WOFF2格式都无法解决。代码如下:
const url = "./Roboto-Italic.ttf"; const fontBytes = await fetch(url).then((res) => res.arrayBuffer()); pdfDoc.registerFontkit(fontkit); const font = await pdfDoc.embedFont(fontBytes);
错误栈信息:
at Object.create (http://localhost:3000/main.86466a5e8eefe1529961.hot-update.js:8806:11) at Function.<anonymous> (http://localhost:3000/main.86466a5e8eefe1529961.hot-update.js:47584:42) at step (http://localhost:3000/main.86466a5e8eefe1529961.hot-update.js:56459:17) at Object.next (http://localhost:3000/main.86466a5e8eefe1529961.hot-update.js:56408:14) at http://localhost:3000/main.86466a5e8eefe1529961.hot-update.js:56382:67 at new Promise (<anonymous>) at __awaiter (http://localhost:3000/main.86466a5e8eefe1529961.hot-update.js:56364:10) at CustomFontEmbedder.for (http://localhost:3000/main.86466a5e8eefe1529961.hot-update.js:47579:60) at PDFDocument.<anonymous> (http://localhost:3000/main.86466a5e8eefe1529961.hot-update.js:35659:91) at step (http://localhost:3000/main.86466a5e8eefe1529961.hot-update.js:56459:17)
解决方案
- 调整fontkit注册顺序:fontkit必须在PDFDocument实例创建完成后、调用
embedFont之前注册,顺序错了会导致字体识别失败。修改代码顺序:const pdfDoc = await PDFDocument.create(); pdfDoc.registerFontkit(fontkit); // 先注册工具 // 再获取字体文件 const url = "./Roboto-Italic.ttf"; const res = await fetch(url); const fontBytes = await res.arrayBuffer(); const font = await pdfDoc.embedFont(fontBytes); - 检查字体文件完整性:可能是字体文件损坏或下载不完整。先打开本地的
Roboto-Italic.ttf确认能正常预览,或者在fetch时增加状态校验:const res = await fetch(url); if (!res.ok) { console.error(`字体下载失败,状态码:${res.status}`); return; } const fontBytes = await res.arrayBuffer(); - 使用兼容的fontkit包:pdf-lib仅支持
@pdf-lib/fontkit,不要混用其他fontkit版本。重新安装并导入:npm install @pdf-lib/fontkitimport fontkit from '@pdf-lib/fontkit'; - 弃用WOFF/WOFF2格式:pdf-lib对WOFF系列格式支持有限,优先使用标准TTF或OTF字体,避免经过压缩或特殊处理的版本。
- 确认字体文件路径:开发环境下,字体文件需放在项目public目录中(如Vite、Create React App的public文件夹),或使用绝对路径确保fetch能正确获取文件。
内容的提问来源于stack exchange,提问作者Gurami Tchumburidze
相关产品推荐
相关产品推荐

