"Error: Unknown Version 0" when using NodeJS PDFKit

"Error: Unknown Version 0" when using NodeJS PDFKit

我正在尝试获得非常出色的NodeJS PDFKit to use custom fonts OpenSans and Roboto from Google Fonts。我的代码如下所示:

this.doc = new PDFDocument({bufferPages: true});
this.doc.registerFont("Roboto-Black", path.join(__dirname, "fonts", "Roboto-Black.ttf"));

我已经打印了路径 - 它找到了正确的文件。我收到以下错误:

C:\projects\qbdvision\node_modules\restructure\src\VersionedStruct.js:37
        throw new Error("Unknown version " + res.version);
        ^

Error: Unknown version 0
    at VersionedStruct.decode (C:\projects\qbdvision\node_modules\restructure\src\VersionedStruct.js:37:15)
    at C:\projects\qbdvision\node_modules\restructure\src\Pointer.js:69:30
    at Pointer.decode (C:\projects\qbdvision\node_modules\restructure\src\Pointer.js:79:16)
    at ArrayT.decode (C:\projects\qbdvision\node_modules\restructure\src\Array.js:49:30)
    at VersionedStruct.Struct._parseFields (C:\projects\qbdvision\node_modules\restructure\src\Struct.js:53:22)
    at VersionedStruct.decode (C:\projects\qbdvision\node_modules\restructure\src\VersionedStruct.js:42:12)
    at VersionedStruct.decode (C:\projects\qbdvision\node_modules\restructure\src\VersionedStruct.js:40:23)
    at C:\projects\qbdvision\node_modules\restructure\src\Pointer.js:69:30
    at Pointer.decode (C:\projects\qbdvision\node_modules\restructure\src\Pointer.js:79:16)
    at ArrayT.decode (C:\projects\qbdvision\node_modules\restructure\src\Array.js:49:30)
 FAILED

当我删除 Roboto 字体并尝试使用 OpenSans 时,它至少可以工作,但一切看起来都很糟糕。字母一起流血,看起来几乎弄脏了。

我通过单击 "Select this font" 从 fonts.google.com 下载字体,单击出现的“1 Family Selected”弹出窗口,然后单击右上角的下载图标那个弹出窗口。

为什么这些字体不起作用?

解决方法是将字体转成base64编码后再导入。因此,在命令行中,使用 Linux / Cygwin,键入:

base64 --wrap=0 Roboto-Black.ttf > Roboto-Black-Base64.ttf

这将生成一个新的 TTF 文件,其中应包含所有文本。如果您使用外部服务,请确保没有任何包装。它应该是一个连续的文本块。

然后,在您的 NodeJS 代码中,执行:

let fs = require("fs");

let doc = new PDFDocument({bufferPages: true});
let filePath = path.join(__dirname, "fonts", "Roboto-Black-Base64.ttf");
let fileContents = fs.readFileSync(filePath, "utf8");
this.doc.registerFont(fontName, new Buffer(fileContents, "base64"));

然后您的字体会crystal清晰显示。支持 this answer 为我提供所需的线索。