Photo by CURVD® on Unsplash

How to Create and Modify PDF Files With pdf-lib

Atakan Demircioğlu

--

In this post, we will cover how to modify an existing PDF using JavaScript with PDF-lib. Specifically, we’ll generate a QR code and insert it into a PDF.

How to create QR with NodeJS?

I selected one of the simplest libraries named qrcode. There are multiple types of generation but I preferred the PNG response for adding my PDF easily.

import QRCode from "qrcode";
export const generateQR = async text => {
try {
const response = await QRCode.toDataURL(text);
return response;
} catch (err) {
console.error(err)
}
}

How to modify existing PDFs with NodeJS?

When I started to research, I just saw that finding a library to read existing PDFs is hard. Most libraries are designed for creating new PDFs.

For archiving this I used PDF-lib. This package allows you to modify existing PDFs and also create new PDFs.

Let’s read the existing PDF file;

const existingPdfBytes = await fsPromises.readFile('YOUR_FILE.pdf');
const pdfDoc = await PDFDocument.load(existingPdfBytes);

After that let’s add a new page to our PDF and add a generated QR

// adding new page
const…

--

--

Atakan Demircioğlu
Atakan Demircioğlu

Written by Atakan Demircioğlu

Passionate about blogging and sharing insights on tech, web development, and beyond. Join me on this digital journey! 🚀

Responses (1)