Embed QR Codes in PDF: Node.js, Python & API Guide (2026)
Adding a QR code to a PDF is common for verification links, tracking, ticketing, and delivery confirmations. The key is generating the QR code as a Base64 data URI on the server, embedding it in an HTML template, and converting the HTML to PDF via an API.
This guide covers Node.js and Python implementations with copy-paste examples, plus patterns for multi-page PDFs, certificate generation, and batch processing. If you need a broader introduction to HTML-to-PDF conversion, see the HTML to PDF Complete Guide. For troubleshooting layout issues, the HTML to PDF CSS Tips guide covers @page, page breaks, and image rendering in detail.
Why Base64, Not a File Path
FUNBREW PDF renders the HTML string you send (html) on FUNBREW's servers. The renderer cannot see your local filesystem, so referencing a QR code as /tmp/qr.png produces a broken image. The reliable approach is to encode the QR image as a Base64 data URI and embed it directly in the HTML:
<img src="data:image/png;base64,iVBORw0KGgo..." alt="QR Code" />
Because the image lives inside the HTML string, the same code works whether your caller runs on a server, in a Lambda function, or in a Docker container. The html field is limited to 5,000,000 characters by default. A QR PNG is small, but watch the total size if you embed large images alongside it.
Node.js: Generate QR Code and Convert to PDF
Install Dependencies
npm install qrcode axios
Basic Example
FUNBREW PDF's generate API returns JSON, not the PDF itself. Fetch data.download_url with the same API key to get the PDF.
const QRCode = require('qrcode');
const axios = require('axios');
const fs = require('fs');
const API_BASE = 'https://pdf.funbrew.cloud';
const authHeaders = { Authorization: `Bearer ${process.env.FUNBREW_API_KEY}` };
// HTML -> PDF (generate, then fetch download_url)
async function htmlToPdf(html, outputPath) {
const { data: result } = await axios.post(
`${API_BASE}/api/pdf/generate-from-html`,
{ html, options: { 'page-size': 'A4' } },
{ headers: { ...authHeaders, 'Content-Type': 'application/json' } }
);
const pdf = await axios.get(result.data.download_url, {
headers: authHeaders,
responseType: 'arraybuffer',
});
fs.writeFileSync(outputPath, pdf.data);
return outputPath;
}
async function generatePdfWithQr(targetUrl, outputPath) {
// Step 1: Generate QR code as Base64 data URI
const qrDataUri = await QRCode.toDataURL(targetUrl, {
errorCorrectionLevel: 'M',
width: 300,
margin: 4, // quiet zone (the default)
});
// Step 2: Build HTML template with embedded QR code
// (a table layout renders the same on both engines)
const html = `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
body { font-family: Arial, sans-serif; padding: 40px; }
.qr-container { border: 1px solid #ddd; border-collapse: separate; }
.qr-container td { padding: 20px; vertical-align: middle; }
.qr-container img { width: 30mm; height: 30mm; }
.qr-label { font-size: 12px; color: #555; margin-top: 8px; }
h1 { font-size: 24px; }
</style>
</head>
<body>
<h1>Document with QR Verification</h1>
<p>Scan the QR code to verify this document.</p>
<table class="qr-container"><tr>
<td>
<img src="${qrDataUri}" alt="Verification QR Code" />
<p class="qr-label">Scan to verify</p>
</td>
<td>
<strong>Document ID:</strong> DOC-2026-001<br>
<strong>Issued:</strong> 2026-04-28<br>
<strong>Verification URL:</strong><br>
<small>${targetUrl}</small>
</td>
</tr></table>
</body>
</html>
`;
// Step 3: Convert via FUNBREW PDF API and save
await htmlToPdf(html, outputPath);
console.log(`PDF saved to ${outputPath}`);
}
generatePdfWithQr(
'https://verify.example.com/doc/DOC-2026-001',
'./output.pdf'
);
Batch QR Code Generation (client-side concurrency)
When generating multiple PDFs (tickets, certificates, invoices), pre-generate all QR codes in parallel before building templates. The generate API has a per-minute limit per company (Free 10 / Pro 120 / Business 300 requests); above it you get 429 with Retry-After. The example below sends 5 at a time; adjust the concurrency to your plan's limit (PDF downloads also count as requests).
const QRCode = require('qrcode');
const axios = require('axios');
const fs = require('fs');
const API_BASE = 'https://pdf.funbrew.cloud';
const authHeaders = { Authorization: `Bearer ${process.env.FUNBREW_API_KEY}` };
const QR_OPTIONS = { errorCorrectionLevel: 'M', width: 300, margin: 4 };
async function batchGeneratePdfs(records) {
// Generate all QR codes in parallel (local work, not counted by the API)
const qrDataUris = await Promise.all(
records.map(r => QRCode.toDataURL(r.verifyUrl, QR_OPTIONS))
);
// Generate PDFs 5 at a time
fs.mkdirSync('./output', { recursive: true });
const results = [];
for (let i = 0; i < records.length; i += 5) {
const batch = records.slice(i, i + 5);
const batchQrs = qrDataUris.slice(i, i + 5);
const batchResults = await Promise.all(
batch.map((record, idx) => generateOnePdf(record, batchQrs[idx]))
);
results.push(...batchResults);
}
return results;
}
async function generateOnePdf(record, qrDataUri) {
const html = buildTemplate(record, qrDataUri);
const { data: result } = await axios.post(
`${API_BASE}/api/pdf/generate-from-html`,
{ html, options: { 'page-size': 'A4' } },
{ headers: authHeaders }
);
const pdf = await axios.get(result.data.download_url, {
headers: authHeaders,
responseType: 'arraybuffer',
});
const filename = `./output/${record.id}.pdf`;
fs.writeFileSync(filename, pdf.data);
return filename;
}
function escapeHtml(value) {
return String(value).replace(/[&<>"']/g, c => ({
'&': '&', '<': '<', '>': '>', '"': '"', "'": ''',
}[c]));
}
function buildTemplate(record, qrDataUri) {
return `
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
body { font-family: Arial, sans-serif; }
.qr { width: 25mm; height: 25mm; float: right; }
</style>
</head>
<body>
<img class="qr" src="${qrDataUri}" alt="QR" />
<h2>${escapeHtml(record.title)}</h2>
<p>ID: ${escapeHtml(record.id)}</p>
<p>Issued to: ${escapeHtml(record.recipientName)}</p>
</body>
</html>
`;
}
Set the paper size and margins with the API's options (page-size, margin-top and so on; margins in mm, 0 to 50) rather than with @page in the HTML.
Python: Generate QR Code and Convert to PDF
Install Dependencies
pip install "qrcode[pil]" requests
(Quote the package name; zsh expands square brackets.)
Basic Example
import base64
import io
import os
import qrcode
import requests
API_BASE = "https://pdf.funbrew.cloud"
AUTH_HEADERS = {"Authorization": f"Bearer {os.environ['FUNBREW_API_KEY']}"}
def html_to_pdf(html: str, output_path: str) -> None:
"""Convert HTML to PDF, then fetch it from download_url and save it."""
resp = requests.post(
f"{API_BASE}/api/pdf/generate-from-html",
json={"html": html, "options": {"page-size": "A4"}},
headers=AUTH_HEADERS,
timeout=60,
)
resp.raise_for_status()
download_url = resp.json()["data"]["download_url"]
pdf = requests.get(download_url, headers=AUTH_HEADERS, timeout=60)
pdf.raise_for_status()
with open(output_path, "wb") as f:
f.write(pdf.content)
def generate_pdf_with_qr(target_url: str, output_path: str) -> None:
"""Generate a PDF with an embedded QR code."""
# Step 1: Generate QR code
qr = qrcode.QRCode(
version=None,
error_correction=qrcode.constants.ERROR_CORRECT_M,
box_size=8,
border=4, # quiet zone (the default)
)
qr.add_data(target_url)
qr.make(fit=True)
img = qr.make_image(fill_color="black", back_color="white")
# Step 2: Convert to Base64 data URI
buffer = io.BytesIO()
img.save(buffer, format="PNG")
qr_b64 = base64.b64encode(buffer.getvalue()).decode()
qr_data_uri = f"data:image/png;base64,{qr_b64}"
# Step 3: Build HTML template
html = f"""
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
body {{ font-family: Arial, sans-serif; padding: 40px; }}
.qr-section {{ border: 1px solid #ccc; }}
.qr-section td {{ padding: 20px; vertical-align: middle; }}
.qr-section img {{ width: 30mm; height: 30mm; }}
p {{ margin: 4px 0; }}
</style>
</head>
<body>
<h1>Verified Document</h1>
<table class="qr-section"><tr>
<td><img src="{qr_data_uri}" alt="QR Code" /></td>
<td>
<p><strong>Scan to verify this document</strong></p>
<p>URL: {target_url}</p>
<p>Generated: 2026-04-28</p>
</td>
</tr></table>
</body>
</html>
"""
# Step 4: Convert to PDF via FUNBREW PDF API and save
html_to_pdf(html, output_path)
print(f"PDF saved to {output_path}")
if __name__ == "__main__":
generate_pdf_with_qr(
"https://verify.example.com/doc/DOC-2026-001",
"output.pdf",
)
Async Batch Processing (Python)
import asyncio
import base64
import html as html_lib
import io
import os
import aiohttp
import qrcode
API_BASE = "https://pdf.funbrew.cloud"
AUTH_HEADERS = {"Authorization": f"Bearer {os.environ['FUNBREW_API_KEY']}"}
QR_CONFIG = {
"error_correction": qrcode.constants.ERROR_CORRECT_M,
"box_size": 8,
"border": 4,
}
def make_qr_data_uri(url: str) -> str:
qr = qrcode.QRCode(**QR_CONFIG)
qr.add_data(url)
qr.make(fit=True)
img = qr.make_image(fill_color="black", back_color="white")
buf = io.BytesIO()
img.save(buf, format="PNG")
b64 = base64.b64encode(buf.getvalue()).decode()
return f"data:image/png;base64,{b64}"
async def generate_one(session: aiohttp.ClientSession, record: dict) -> str:
qr_uri = make_qr_data_uri(record["verify_url"])
html = f"""<!DOCTYPE html>
<html><head><meta charset="UTF-8"></head>
<body>
<img src="{qr_uri}" style="width: 25mm; height: 25mm;" />
<h2>{html_lib.escape(record['title'])}</h2>
<p>Recipient: {html_lib.escape(record['name'])}</p>
</body></html>"""
async with session.post(
f"{API_BASE}/api/pdf/generate-from-html",
json={"html": html, "options": {"page-size": "A4"}},
headers=AUTH_HEADERS,
) as resp:
resp.raise_for_status()
download_url = (await resp.json())["data"]["download_url"]
async with session.get(download_url, headers=AUTH_HEADERS) as pdf_resp:
pdf_resp.raise_for_status()
pdf_bytes = await pdf_resp.read()
path = f"./output/{record['id']}.pdf"
with open(path, "wb") as f:
f.write(pdf_bytes)
return path
async def batch_generate(records: list) -> list:
os.makedirs("./output", exist_ok=True)
semaphore = asyncio.Semaphore(5) # max 5 concurrent (adjust to your plan's per-minute limit)
async def limited(session, record):
async with semaphore:
return await generate_one(session, record)
async with aiohttp.ClientSession() as session:
tasks = [limited(session, r) for r in records]
return await asyncio.gather(*tasks)
A QR Code on Every Page of a Multi-Page PDF
FUNBREW PDF's generate API has no option for header or footer templates (nothing like headerTemplate / footerTemplate). It accepts html and options (page-size, orientation, margin-*, engine), among others.
To put a QR code on every page, build one block per page in your HTML, place the QR code in each block, and separate the blocks with page breaks. This assumes each block fits on one page (if a block overflows, the QR code on that page moves).
const QRCode = require('qrcode');
async function buildPagedHtml(pages, verifyUrl) {
const qrDataUri = await QRCode.toDataURL(verifyUrl, {
errorCorrectionLevel: 'M',
width: 300,
margin: 4,
});
const pageHtml = pages.map((content, i) => `
<section class="page">
${content}
<table class="page-footer"><tr>
<td>Page ${i + 1} of ${pages.length}</td>
<td style="text-align: right;">
<img src="${qrDataUri}" style="width: 22mm; height: 22mm;" alt="Verify" />
</td>
</tr></table>
</section>
`).join('');
return `
<!DOCTYPE html>
<html><head><meta charset="UTF-8"><style>
body { font-family: Arial, sans-serif; margin: 0; }
.page { page-break-after: always; }
.page:last-child { page-break-after: auto; }
.page-footer { width: 100%; margin-top: 12mm; font-size: 9pt; color: #555; }
</style></head>
<body>${pageHtml}</body></html>
`;
}
// Usage: pass the result to htmlToPdf() from the basic example
// const html = await buildPagedHtml(['<h1>Page one</h1>...', '<h1>Page two</h1>...'], verifyUrl);
// await htmlToPdf(html, './paged.pdf');
If you only need page numbers, you can also send the generated PDF's filename to POST /api/pdf/page-numbers (SaaS edition, when your plan includes the page number feature; position takes one of six values such as bottom-center, and format can contain {page} and {total}).
QR Code Error Correction and Size
There are four error correction levels. The approximate share of damage each can recover from (values from the qrcode npm and Python qrcode documentation):
| Level | Recoverable damage (approx.) |
|---|---|
| L | about 7% |
| M (default) | about 15% |
| Q | about 25% |
| H | about 30% |
A higher level adds modules (dots) for the same data, so each module gets smaller at the same printed size. Use Q or higher for paper that may get dirty or folded (tickets, shipping labels); L or M is enough for screens and clean prints.
The right printed size depends on URL length, error correction level, the printer, and the scanning device, so there is no single value for every use case. Print the actual PDF and scan it with the devices your readers will use. Shorter URLs (for example, only a verification ID) make the code easier to scan at the same size.
Common Issues and Fixes
Broken image in PDF output
Cause: The QR code is referenced as a file path (/tmp/qr.png) instead of a data URI.
Fix: Use QRCode.toDataURL() (Node.js) or encode to Base64 with base64.b64encode() (Python) and embed directly in the <img src> attribute.
QR code not scannable
Cause: The printed size is too small, or the margin (quiet zone) is insufficient.
Fix: Keep margin (Node.js) / border (Python) at the default of 4 modules (the Python qrcode documentation calls 4 the minimum according to the specs). Increase the displayed size, or shorten the URL to reduce the number of modules.
QR code looks blurry
Cause: The source PNG is low resolution relative to its displayed size in the PDF.
Fix: Generate with a larger width (Node.js) / box_size (Python) and set the displayed size with CSS (width: 30mm). Zoom in on and print the output PDF to check.
Certificate Use Case
When combining QR code verification with bulk certificate generation, see the PDF Certificate Automation guide for an implementation that includes recipient CSV import, HTML template variables, and S3 archival.
The QR code in each certificate should point to a verification endpoint that accepts the certificate ID and returns its status:
https://verify.example.com/cert/{certificateId}
The verification endpoint has to confirm that the ID was really issued by you. Either store each ID in a database or key-value store at issue time and look it up, or, to prevent forgery, include a signature made with a secret key (such as an HMAC) in the ID and verify it. A plain hash of the recipient email and issue date is not proof, because anyone who knows those two values can compute it.
Next Steps
- PDF Certificate Automation — bulk certificate generation with QR verification
- HTML to PDF CSS Tips — layout and print CSS for precise positioning
- PDF API Batch Processing — concurrency patterns for high-volume PDF generation
- Automate PDF Reports — scheduling, charting, and email delivery in one pipeline
- FUNBREW PDF Playground — test your QR-embedded HTML templates before writing code
- API Documentation — full reference for the FUNBREW PDF generate endpoint