PDFKit is a JavaScript PDF generation library primarily used with Node.js, but it's also compatible with web browsers. Its aim is to simplify the creation of complex, multi-page, printable documents by offering both low-level functions and abstractions for higher-level functionalities. PDFKit's capabilities include generating vector graphics, embedding fonts and images, creating text with line wrapping and alignment options, incorporating annotations, and offering AcroForms, outlines and PDF security features such as encryption and access privileges.
To use PDFKit, you first need to install it using the npm package manager by running the command npm install pdfkit
. After the installation, you can require it in your Node.js code and start using its features. Here's an example of how to use it:
const PDFDocument = require('pdfkit');
const fs = require('fs');
const doc = new PDFDocument();
doc.pipe(fs.createWriteStream('output.pdf'));
doc
.font('fonts/PalatinoBold.ttf')
.fontSize(25)
.text('Some text with an embedded font!', 100, 100);
doc.image('path/to/image.png', {
fit: [250, 300],
align: 'center',
valign: 'center'
});
doc
.addPage()
.fontSize(25)
.text('Here is some vector graphics...', 100, 100)
.save();
doc.end();
This code creates a new PDF document, sets an output file, embeds a font and places text, adds an image, and generates a new page with text. In the end, it finalizes the PDF file.
The documentation for PDFKit includes a detailed explanation of the API, examples, and more usage guidelines. It can be found on the PDFKit website. The documentation is designed to be straightforward to simplify the process of generating complex documents using just a few function calls. It also includes an interactive in-browser demo to display PDFKit's functionality effectively.