PDFKit – 自定义字体 – fs.readFileSync不是一个函数

我正在使用PDFKit作为应用程序。 我只是在浏览器中的HTML文件,使用Javascript(没有Node.js)。

我从GitHub下载了PDFKit: https : //github.com/devongovett/pdfkit/releases

以及Blobstream: https : //github.com/devongovett/blob-stream

我试图包含一个自定义字体,如下所示:

doc.registerFont('Custom Font', 'fonts/GOODDP__.TTF'); doc.font('Custom Font').fontSize(fontSize).text($("#text1").val(), xPos, yPos, configObj); 

但是我总是得到这个错误:

  fs.readFileSync is not a function 

这是有道理的,因为fs.readFileSync是node.js的一部分,我不使用它。 但是,文档中的示例说这可以在浏览器中使用。

我知道还有一个Browserify选项,但我不知道如何或如果这将有助于在这种情况下

你必须使用一个ArrayBuffer:

  var oReq = new XMLHttpRequest(); oReq.open("GET", "css/fonts/Open_Sans/OpenSans-Regular.ttf", true); oReq.responseType = "arraybuffer"; oReq.onload = function(oEvent) { var arrayBuffer = oReq.response; // Note: not oReq.responseText if (arrayBuffer) { PdfExporter.doc.registerFont('OpenSans', arrayBuffer) } }; oReq.send(null); 

看来你必须使用Browserify来实现这个function,而使用预编译的PDFKit.js不会因为任何Node.js特定的function而削减它。

我也遇到了这个问题,Andrea的答案只是解决scheme的一部分。 你实际上需要调整pdfkit.js文件。 但首先你需要做安德烈所做的:

 var myImage; var oReq = new XMLHttpRequest(); oReq.open("GET", "myimage.jpg", true); oReq.responseType = "arraybuffer"; oReq.onload = function(oEvent) { myImage = oReq.response; //image as an arraybuffer makePDF(); }; oReq.send(null) //then use myImage like normal: doc.image(myImage); 

正如我所说,你需要调整pdfkit.js文件。 在大约2888行:

 PDFImage.open = function(src, label) { var data, match; if (Buffer.isBuffer(src)) { data = src; } else { //START NEW if (src instanceof ArrayBuffer) { data = new Buffer(new Uint8Array(src), 'object'); } else //END NEW if (match = /^data:.+;base64,(.*)$/.exec(src)) { data = new Buffer(match[1], 'base64'); } else { data = fs.readFileSync(src); if (!data) { return; } } } 

确保你还包含blob-stream.js。 我在// START START之后添加了一个额外的选项,用于处理来自XMLHttpRequests的数组缓冲区。

我不知道这是否是最好的解决scheme,但它的工作原理。