Search code examples
javascriptnode.jsbrowserbrowserifypdfkit

PDFKit Can't load image in browser


I'm working with PDFKit to generate a PDF in the browser, and then send the blob data of that PDF to a new tab for the user to download. I really like PDFKit...it's pretty slick.

However, I'm running into an issue when I try and use the PDFDocument.image() function to "draw" an image file:

Uncaught TypeError: fs.readFileSync is not a function

I'm pretty familiar with Node, and so I recognized that method signature immediately - the browser doesn't have fs natively! I'm less familiar with Browserify, and opted to instead use the pre-built version of PDFKit to avoid having to integrate another dependency that I'm not even familiar with.

My only guess is that the developers of PDFKit haven't included a working fallback for using this particular feature in the browser without Browserify - would using Browserify even give me access to the fs module (again, never used it)? Is that my only option here? Am I missing a particular step required to get this feature working?

Currently I'm including the following JS files as dependencies for my generate_pdf.js file:

  • pdfkit.js
  • blob-stream.js

Is there a module that emulates fs that I also need? I'm not seeing that documented, but it's been a long day.


Solution

  • Well, there are some libraries (like this or this), but I would highly recommend to write your own fs.readFileSync.

    Since you're not likely to access client's filesystem from the browser anyway, using some existing solution would imply adding an abstraction level, etc.

    So, probably the simplest and the easiest solution would be to add

    var fs = {
      readFileSync: (path) => {
        // magic
      }
    }
    

    Why probably? Well...

    1. If there are usages of many fs functions, you'd obviously want to do it with some library

    2. Synchronous requests. I guess you're loading images from some url, so you'll have to use synchronous requests in the implementation of fs.readFileSync to achieve the desired result. It's not like a big deal, but you'll get warnings in console.

    P.S. sorry, but there's a hight probability that you'll face more issues with that because it's much more common to create pdfs on the server-side. Wy not move to the backend? ;)