Created
March 13, 2024 19:39
-
-
Save atakde/957a36870d129621c3a71fb9b39753ba to your computer and use it in GitHub Desktop.
How to add QR code to PDF?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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