Skip to content

Instantly share code, notes, and snippets.

@atakde
Created March 13, 2024 19:39
Show Gist options
  • Save atakde/957a36870d129621c3a71fb9b39753ba to your computer and use it in GitHub Desktop.
Save atakde/957a36870d129621c3a71fb9b39753ba to your computer and use it in GitHub Desktop.
How to add QR code to PDF?
import fs from 'fs';
import fsPromises from 'fs/promises';
import { PDFDocument } from "pdf-lib";
import QRCode from "qrcode";
export const generateQR = async text => {
try {
const response = await QRCode.toDataURL(text);
return response;
} catch (err) {
console.error(err)
}
}
const existingPdfBytes = await fsPromises.readFile('qr.pdf');
const pdfDoc = await PDFDocument.load(existingPdfBytes);
const page = pdfDoc.addPage();
const qrResponse = await generateQR('https://www.google.com');
const qrImage = await pdfDoc.embedPng(qrResponse);
const { height } = page.getSize();
page.drawImage(qrImage, {
x: 50,
y: height - 300,
width: 200,
height: 200,
});
const pdfBytes = await pdfDoc.save();
fs.writeFileSync('qr.pdf', pdfBytes);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment