Skip to content

How to compile standalone PDFKit for use in the browser

Hamza Mateen edited this page Aug 23, 2023 · 8 revisions

Starting form version 0.10, a standalone build (named pdfkit.standalone.js) is distributed in the package or in the release, so most of the time this procedure is not needed.

This is how to compile PDFKit into a single pdfkit.js file for use in the browser with <script> tags.

For Windows, and OSX

  1. Install NodeJS from https://nodejs.org/en/download/.

  2. Open command line (Windows+R).

  3. Install dependencies with NodeJS:

    npm install browserify brfs
    
  4. You can install the latest release:

    npm install pdfkit  
    
  5. Compile PDFKit into a single javascript file with Browserify:

    npx browserify --standalone PDFDocument node_modules\pdfkit\js\pdfkit.js > pdfkit.js
    
  6. The compiled file named pdfkit.js will be created in the folder where the commands were executed

  7. Link the compiled file using a script tag. The PDFDocument identifier will be defined in the global scope (window)

  8. Optionally you can use uglify-js to get a smaller javascript file as output

    npm install uglify-js
    npx browserify --standalone PDFDocument node_modules\pdfkit\js\pdfkit.js | npx uglifyjs -cm > pdfkit.js
    

To build on Linux (I tested on Ubuntu 23.04 Lunar Lobster), follow two extra steps before building

  1. I had to npm install 'iconv-lite' module. Its a dependency actually. npm install iconv-lite

  2. change the backslashes to forward slashes, I actually spent some time on this annoying bug tbh npx browserify --standalone PDFDocument node_modules/pdfkit/js/pdfkit.js > pdfkit.js

Note when using PDFKit in the browser you will not have access to the local filesystem, so when adding images etc. to a PDF document you will need to fetch them via AJAX as an ArrayBuffer, otherwise you will get fs.readFileSync is not a function errors. An example of how to do this can be found here.