Search code examples
javascriptpdfpdf-generationpdfkitnode-pdfkit

PDFKit: Unknown image format error for PNG


I'm using the prebuilt version of PDFKit in the browser, and when attempting to add a PNG I get the following error:

Uncaught Error: Unknown image
    PDFImage.open                             format.util.js:546
    module.exports.image                      deflate.js:773
    img.onload                                PDFrenderer.js:195

I'm converting my images to PNG on the server (to crop them into circles) and the mime type of the images returned by the server is 'image/png'. I'm unsure whether the method I'm using to convert the PNG into an ArrayBuffer is incorrect.

Here is the code I use to fetch the PNG and convert it into an ArrayBuffer:

var img = new Image, ctxData;

img.onError = function () {
    throw new Error('Cannot load image: "' + url + '"');
}

img.onload = function () {
    var canvas = document.createElement('canvas');
    document.body.appendChild(canvas);
    canvas.width = img.width;
    canvas.height = img.height;

    var ctx = canvas.getContext('2d');
    ctx.drawImage(img, 0, 0);
    ctxData = canvas.toDataURL('image/png').slice('data:image/png;base64,'.length);
    ctxData = atob(ctxData);
    document.body.removeChild(canvas);

    var buffer = [];

    for (var i = 0, l = ctxData.length; i < l; i++) {
        buffer.push(ctxData.charCodeAt(i));
        buffer._isBuffer = true;
        buffer.readUInt16BE = function (offset, noAssert) {
            var len = this.length;
            if (offset >= len) return;

            var val = this[offset] << 8;
            if (offset + 1 < len)
                l |= this[offset + 1];
            return val;
        }
    }
    pdf.image(buffer);
}

img.src = url;

This works fine for JPEGs when this line is changed from

ctxData = canvas.toDataURL('image/png').slice('data:image/png;base64,'.length);

to

ctxData = canvas.toDataURL('image/jpeg').slice('data:image/jpeg;base64,'.length);

however I need to be able to pass in PNGs so that I can place I can place round images over any background.

I've also tried passing in the full url (e.g. 'http://mysite.dev/userimages/1234/roundavatar.png'), however I'm then presented with the following error:

Uncaught TypeError: undefined is not a function
    PDFImage.open                 util.js:535
    module.exports.image          deflate.js:773

Has anyone had any success adding PNGs to PDFkit via the browser, and if so what method did you use?


Solution

  • I found a solution as per this https://github.com/devongovett/pdfkit/blob/master/lib/image.coffee just make sure your name your png files with at capital ending .PNG, it worked for me.