Skip to content Skip to sidebar Skip to footer

Pdfkit - Custom Fonts - Fs.readfilesync Is Not A Function

I'm using PDFKit for an application. I'm just using it in the Browser in an HTML file, with Javascript (no Node.js). I downloaded PDFKit from GitHub: https://github.com/devongovet

Solution 1:

You have to use an ArrayBuffer:

var oReq = newXMLHttpRequest();
        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.responseTextif (arrayBuffer) {
                PdfExporter.doc.registerFont('OpenSans', arrayBuffer)
            }
        };

        oReq.send(null);

Solution 2:

It seems you must use Browserify for this functionality and that using a pre-compiled PDFKit.js won't cut it for any of the Node.js-specific functionality.

Solution 3:

Here's the steps I followed to load a custom unicode font.

  1. Create package.json using the default values:

npm init -y

  1. Install fontkit

npm install fontkit

  1. Install browserify globally (in case you do not have browserify)

npm install -g browserify

  1. Create an empty file and name it compile.js (or whatever you like)

  2. Paste the following code inside compile.js

    fontkit = require("fontkit");
    const fontName = "OpenSans-Regular";
    const fontPath = fontName + ".ttf";
    
    fetch(fontPath)
        .then(res => res.arrayBuffer())
        .then(fontBlob => {
            const customFont = fontkit.create(newBuffer(fontBlob)).stream.buffer;
            const doc = newPDFDocument({});
            const stream = doc.pipe(blobStream());
            doc.registerFont(fontName, customFont);
            doc.fontSize(14);
            doc.font(fontName)
            .fillColor("black")
                .text(
                    "Custom unicode font loaded. Ω is the 24th and last letter of the Greek alphabet.",
                    50,
                    50,
                    { width: 800, align: "left" }
                );
            doc.end();
            stream.on("finish", function() {
                const blob = stream.toBlob("application/pdf");
                const iframe = document.querySelector("iframe");
                iframe.src = stream.toBlobURL("application/pdf");
            });
        });
    

    To load a diffrent font simply change the fontName value. The above code assumes that a font file named OpenSans-Regular.ttf is present in the same directory as compile.js. You can change the fontPath to whatever path or URL you like.

  3. Run the following (in your Terminal or command prompt) to create a custom version of fontkit.

browserify compile.js -o fontkit.js

  1. You can delete compile.js file. It's no longer needed. You can also delete node_modules directory as well as package.json. (If you are not using other packages and you are only doing this for creating a custom version of fontkit)

  2. Create an index.html file and paste the following:

    <!DOCTYPE html><htmllang="en"><head><title>Custom Font</title><metacharset="UTF-8"><metaname="viewport"content="width=device-width, initial-scale=1"></head><body><iframeid="frame1"width="100%"height="500px"></iframe></body><scriptsrc="pdfkit.js"></script><scriptsrc="blob-stream.js"></script><scriptsrc="fontkit.js"></script></html>
  3. Here's a screenshot of index.html in the browser:

enter image description here

Solution 4:

I also ran in to this problem and Andrea's answer is only part of the solution. You actually need to tweak the pdfkit.js file. But first you need to do what Andrea did:

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

As I said you need to tweak the pdfkit.js file. At about line 2888:

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

Make sure you also include blob-stream.js. I added an extra option after //START NEW that takes care of array buffers that come from XMLHttpRequests.

I don't know if this is the best solution, but it works.

Solution 5:

This works for me:

async function makePDF() {
   const font = await fetch('./fonts/arial.ttf')
   const arrayBuffer = await font.arrayBuffer()

   doc.registerFont('Arial', arrayBuffer)

   doc.font('Arial').text('Hello World!')
}

Post a Comment for "Pdfkit - Custom Fonts - Fs.readfilesync Is Not A Function"