-
Notifications
You must be signed in to change notification settings - Fork 1.2k
How to compile standalone PDFKit for use in the browser
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
-
Install NodeJS from https://nodejs.org/en/download/.
-
Open command line (Windows+R).
-
Install dependencies with NodeJS:
npm install browserify brfs
-
You can install the latest release:
npm install pdfkit
-
Compile PDFKit into a single javascript file with Browserify:
npx browserify --standalone PDFDocument node_modules\pdfkit\js\pdfkit.js > pdfkit.js
-
The compiled file named
pdfkit.js
will be created in the folder where the commands were executed -
Link the compiled file using a script tag. The
PDFDocument
identifier will be defined in the global scope (window) -
Optionally you can use
uglify-js
to get a smaller javascript file as outputnpm 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
-
I had to npm install 'iconv-lite' module. Its a dependency actually.
npm install iconv-lite
-
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.