Pdfkit: In browser using XHR ArrayBuffer, embedding multiple images will use only the first image

Created on 13 Oct 2016  路  7Comments  路  Source: foliojs/pdfkit

@mattblang already mentioned this in this comment on the now closed issue #371.

I'm using XHR with responseType of 'arraybuffer', and feeding the response to pdfkit's image method:

var imageURLs = ['a.png', 'b.png', 'c.png'];
imageURLs.forEach(fetchImage);

var fetchedImages = {};
function fetchImage(url) {
  var request = new XMLHttpRequest();
  request.open("GET", url, true);
  request.responseType = "arraybuffer";

  request.onload = function() {
    fetchedImages[url] = request.response; // ArrayBuffer instance
    if(imageURLs.every(function(imageURL) {
      return fetchedImages[imageURL];
    }) {
      pdfDoc.image(fetchedImages['a.png'], 0, 0);
      pdfDoc.image(fetchedImages['b.png'], 0, 100);
      pdfDoc.image(fetchedImages['c.png'], 0, 200);
    }
  };
  request.send();
}

The first image works fine, but all other images will display the first image instead. The problem is Buffer.isBuffer returns false for ArrayBuffer objects, which causes this code to use an image from cache.

    unless Buffer.isBuffer(src)
      image = @_imageRegistry[src]

A ugly workaround for this is to make ArrayBuffer pretend to be Buffer (this works because Buffer.isBuffer(src) calls src.constructor.isBuffer(src)):

ArrayBuffer.isBuffer = function() {
  return true;
};

But the proper solution would probably be to check that src is either Buffer or ArrayBuffer.

Most helpful comment

I already have an open pull request (#554) for images so I added a fix to this issue

All 7 comments

I already have an open pull request (#554) for images so I added a fix to this issue

Fixed by #554.

This is still happening for me in 0.8.0. Ref fiddle https://jsfiddle.net/qu1j0t3/q0yutrku/24/

It was not yet fixed when 0.8.0 was released. This bug is fixed in 0.8.2

@alafr how do I get hold of the 0.8.2 binary?

If you are on Windows you can follow these instructions:
https://github.com/devongovett/pdfkit/wiki/How-to-compile-PDFKit-for-use-in-the-browser
or you can download the compiled 0.8.2 version from:
https://github.com/alafr/SVG-to-PDFKit/blob/master/examples/pdfkit.js

@alafr i had started down that route. thanks for the wiki. managed it.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

edmelly picture edmelly  路  5Comments

oknoorap picture oknoorap  路  4Comments

tadarao picture tadarao  路  5Comments

akaleeroy picture akaleeroy  路  4Comments

liubin picture liubin  路  4Comments