Skip to content

How to compile standalone PDFKit for use in the browser

Md. Touhidur Rahman edited this page Jan 9, 2022 · 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. These instructions are for Windows and OSX. It is similar in other operating systems.

  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 uglify-js -cm > 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.

Clone this wiki locally