[Infrastructure] Smart Solutions for High-Volume PDF Generation in Serverless Environments: Automated Invoice Generation Pattern Using Vercel Sandbox and Puppeteer
The Wall of "Resources" in PDF Generation within Serverless Environments
The automated creation of monthly invoices, estimates, or analytical report PDFs is an extremely high-frequency task in B2B business automation processes.
In web system development, because of the ease of designing, the best practice is known to be "creating the layout of the form with HTML and CSS, and outputting (printing) it as a PDF using a headless browser (like Puppeteer)."
However, executing this approach with standard Vercel APIs (Serverless Functions) leaves the following problems unresolved:
- Massive Spikes in Memory Consumption: The process of launching a browser (Chromium) and rendering a page consumes a massive amount of CPU and memory, causing functions to crash when multiple requests overlap.
- Launch Failures Due to Size Limits: The Chromium binary does not fit within the Serverless Functions package size limit (50MB or less on the Pro plan), requiring complex workarounds such as manually and dynamically loading a massive external binary package (
@sparticuz/chromium). - Japanese Font Rendering Corruption: Since Japanese fonts are not pre-installed in serverless environments, characters in the output PDF turn into tofu (□□□).
To smartly overcome these issues, we deploy a server architecture that stably outputs high volumes of PDFs by pre-installing fonts and browsers on Vercel Sandbox, which provides a persistent Node.js execution environment.
2. Before & After: Resolving the Challenges
| Item | PDF Generation with Standard Serverless APIs (Before) | Vercel Sandbox + Puppeteer Architecture (After) |
|---|---|---|
| Font Support | Prone to Japanese character corruption (tofu) | Japanese fonts can be permanently installed in the Sandbox container |
| Launch Stability | Launch errors occasionally occur due to Chromium loading delays | The container can stably operate the browser in the background at all times |
| Memory Limits | Functions die instantly upon hitting the 1024MB limit | Sufficient memory resources are allocated, enabling multi-page PDF outputs |
| PDF Quality | Some CSS print media queries are ignored | Flawless drop-in reproduction of rendering results |
3. Concrete Implementation Example: HTML to PDF Conversion Script on Sandbox
Below is an example of processing code that takes an HTML string and outputs a high-quality PDF binary for printing using Puppeteer.
import puppeteer from "puppeteer-core";
export async function generatePdfFromHtml(htmlContent: string): Promise<Buffer> {
let browser = null;
try {
browser = await puppeteer.launch({
args: [
"--no-sandbox",
"--disable-setuid-sandbox",
"--font-render-hinting=none", // Makes font rendering clearer
],
// Specify the Chromium path on the Vercel Sandbox container
executablePath: process.env.CHROMIUM_PATH || "/usr/bin/chromium-browser",
headless: true,
});
const page = await browser.newPage();
// 1. Set HTML content on the page
await page.setContent(htmlContent, { waitUntil: "networkidle0" });
// 2. Generate an optimized PDF utilizing print CSS (A4 Size)
const pdfBuffer = await page.pdf({
format: "A4",
printBackground: true, // Apply background colors and images
margin: {
top: "20mm",
right: "15mm",
bottom: "20mm",
left: "15mm",
},
});
return Buffer.from(pdfBuffer);
} catch (error) {
console.error("PDF generation pipeline failed:", error);
throw error;
} finally {
if (browser) {
await browser.close();
}
}
}
4. HadayaLab's Automated Document System Development
HadayaLab supports the introduction of enterprise-grade automated PDF generation pipelines to completely eliminate manual labor in monthly "billing operations" and "customer report dispatches."
- Automated PDF Output Integrated with Billing DBs: Extracts details from the database at scheduled times at the end of the month, automatically creates invoice PDFs, and emails them to each client.
- Japanese Font and Layout Adjustments: Beautiful, uncorrupted reproduction of corporate designs through the embedding of various web fonts.
- Automated Archiving to Google Drive / e-Document Retention Act Compliant Storage: Automatically categorizes and saves generated PDF files to Google Drive in accordance with the requirements of the Electronic Books Maintenance Act (searchable dates, client names, and monetary amount metadata).
If you are a back-office manager who feels that "we manually convert hundreds of invoices into PDFs and send them as email attachments every month," please consult us about HadayaLab's "Billing Document Automation."