Web Development
Next.jsPDFApp RouterReactPlaywrightPuppeteerServerlessArchitecture

Next.js PDF Generation (App Router): Invoices, Reports, and Reliable Rendering

AO
Adrijan Omićević
·16 min read

# What This Guide Covers#

Next.js PDF generation sounds straightforward until you ship it: missing fonts, broken pagination, huge serverless cold starts, timeouts, and “it works locally” rendering differences.

This guide focuses on reliable PDF generation in Next.js App Router for invoices, reports, and compliance documents. You’ll learn when to use React-PDF versus Playwright or Puppeteer, how to handle fonts and pagination, and how to run generation asynchronously with background jobs and secure delivery.

You’ll also get a reference architecture you can copy into production, including secure storage and download links.

# Why PDF Generation Fails in Production#

Most production issues fall into four buckets:

  1. 1
    Rendering differences between dev and production environments, especially fonts and locale settings.
  2. 2
    Serverless constraints like timeouts, memory caps, and read-only file systems.
  3. 3
    Large payloads and slow rendering for long reports, charts, or high-resolution images.
  4. 4
    Synchronous generation that blocks checkout flows, webhooks, or user requests.

🎯 Key Takeaway: Treat PDFs as an asynchronous pipeline, not a request-time side effect, unless your PDF is tiny and deterministic.

# Choosing an Approach: React-PDF vs Playwright vs Puppeteer#

There is no universal “best” library. Choose based on how you define the document and what “correct rendering” means for you.

Comparison Table#

ApproachBest forStrengthsTrade-offsTypical serverless fit
React-PDFInvoices, statements, labels, simple reportsDeterministic layout, no browser dependency, smaller bundlesLimited CSS support, charts need custom drawing, different mental model than HTMLStrong
Playwright (Chromium)Pixel-perfect HTML to PDF, complex CSS, existing pagesUses real browser engine, supports modern CSS, easier reuse of existing UILarger cold starts, higher memory, harder scaling, needs careful packagingMedium to weak unless optimized
Puppeteer (Chromium)Similar to Playwright, legacy setupsMature ecosystem, many examplesSimilar drawbacks as Playwright, more manual setup in some environmentsMedium to weak unless optimized

Rule of Thumb#

  • Use React-PDF when your source of truth is structured data and you can build a dedicated PDF template.
  • Use Playwright or Puppeteer when your source of truth is HTML, or when you must match a browser layout exactly.

A practical decision metric: if your design relies heavily on CSS features like grid, advanced typography, or you need screenshots of rendered charts, a browser-based renderer is usually faster to implement and easier to match to design.

# Serverless Constraints You Must Design Around#

Next.js App Router typically runs in serverless or edge environments. PDF generation pushes the limits.

Common Constraints by Platform Type#

EnvironmentTypical timeoutTypical memoryBrowser availabilityNotes
Edge runtimeVery limitedLimitedNo headless browserAvoid PDF rendering here
Serverless functionSeconds to tens of secondsModeratePossible but heavyCold starts and size limits matter
Dedicated worker or containerMinutesHighYesBest for large PDFs and browser rendering

If you are on Vercel, the safest pattern is:

  • API route or server action enqueues a job.
  • A background worker generates the PDF.
  • The file is stored in object storage.
  • The app returns a signed download URL.

For a deep dive into job runners, see: Next.js background jobs, queues, and cron on Vercel.

⚠️ Warning: Generating PDFs during checkout or inside webhook handlers is a reliability trap. Webhook endpoints must respond quickly and deterministically, or you will get retries and duplicate side effects. For payments reliability patterns, use: Next.js App Router payments with Stripe webhooks.

# Approach 1: React-PDF in Next.js App Router#

React-PDF renders a PDF from React components. That makes it predictable: the same input renders the same output, without a browser.

When React-PDF Shines#

  • Invoice PDFs with consistent structure
  • Multi-page documents with predictable sections
  • Bulk generation where you want stable performance
  • Environments where running Chromium is impractical

Minimal Server Route Example#

Use a route handler that streams the PDF. Keep it small and deterministic.

TypeScript
// app/api/invoices/[id]/pdf/route.ts
import { NextResponse } from "next/server";
import { renderToBuffer } from "@react-pdf/renderer";
import { InvoicePdf } from "@/pdf/InvoicePdf";
import { getInvoiceById } from "@/lib/db";
 
export async function GET(_: Request, ctx: { params: Promise<{ id: string }> }) {
  const { id } = await ctx.params;
  const invoice = await getInvoiceById(id);
 
  const pdfBuffer = await renderToBuffer(<InvoicePdf invoice={invoice} />);
 
  return new NextResponse(pdfBuffer, {
    headers: {
      "Content-Type": "application/pdf",
      "Content-Disposition": `inline; filename="invoice-${id}.pdf"`,
      "Cache-Control": "private, max-age=0, no-store",
    },
  });
}

This works for small, on-demand PDFs, but it does not solve async generation, access control, or caching. We’ll cover that in the reference architecture section.

Font Embedding in React-PDF#

Font problems are the top cause of “PDF looks different in production.” Do not rely on system fonts.

Register fonts explicitly and store them in your repo or a stable asset location.

TypeScript
// pdf/fonts.ts
import { Font } from "@react-pdf/renderer";
 
export function registerPdfFonts() {
  Font.register({
    family: "Inter",
    fonts: [
      { src: "https://your-cdn.example/fonts/Inter-Regular.ttf", fontWeight: 400 },
      { src: "https://your-cdn.example/fonts/Inter-SemiBold.ttf", fontWeight: 600 },
    ],
  });
}

Call the registration once when building the PDF component tree.

If you need full Unicode coverage, plan for font file size. A single broad-coverage font can be tens of megabytes, which impacts cold starts. For invoices, you can often get away with Latin subsets, or a font family with smaller footprint.

💡 Tip: Add a “render validation invoice” snapshot in CI that includes diacritics and multiple currencies, for example Č, Ž, €, £, ₹. It catches missing glyphs before customers do.

Pagination with React-PDF#

React-PDF supports automatic page wrapping, but you still need to think about page breaks:

  • Avoid rows that split in the middle, especially line items.
  • Keep headers and footers consistent.
  • Use a fixed table header on each page for long tables.

The practical pattern is to build a “line items” component that renders rows with wrap={false} when splitting would be unacceptable, and let React-PDF move the whole row to the next page.

For invoices, keep each row height predictable. If a row can grow due to long descriptions, enforce truncation rules or render a secondary “notes” section.

# Approach 2: Playwright for HTML to PDF Rendering#

Playwright renders PDFs using Chromium. It is the closest you can get to “print the page” in a controlled way.

When Playwright Is the Best Option#

  • Reports that already exist as HTML pages
  • Complex layout and typography using modern CSS
  • Chart-heavy documents that are easiest to render in-browser
  • International content where your web typography setup is already validated

A Practical Playwright PDF Function#

Keep the surface area small: open a page, set content, wait for stable layout, export PDF.

TypeScript
// lib/pdf/playwright.ts
import { chromium } from "playwright";
 
export async function htmlToPdfBuffer(html: string) {
  const browser = await chromium.launch();
  const page = await browser.newPage();
 
  await page.setContent(html, { waitUntil: "networkidle" });
 
  const pdf = await page.pdf({
    format: "A4",
    printBackground: true,
    margin: { top: "12mm", right: "12mm", bottom: "12mm", left: "12mm" },
  });
 
  await browser.close();
  return pdf;
}

In production, you should reuse a browser instance where possible, but in many serverless environments long-lived instances are unreliable. In job runners or containers, reuse is a major performance win.

For browser-based rendering, you control pagination using print styles:

  • page-break-before and page-break-after for hard breaks
  • break-inside: avoid on table rows and cards
  • @page for margins

Keep the print stylesheet separate from your screen styles to prevent regressions.

If your PDFs have a fixed header and footer, consider rendering them using Chromium’s header and footer templates, but test thoroughly. Complex header templates can be fragile across Chromium versions.

Font Embedding with Chromium#

Relying on system fonts is a mistake because serverless environments vary. Use @font-face and ship font files.

CSS
/* pdf-print.css */
@font-face {
  font-family: Inter;
  src: url("https://your-cdn.example/fonts/Inter-Regular.woff2") format("woff2");
  font-weight: 400;
  font-style: normal;
  font-display: swap;
}
 
html, body {
  font-family: Inter, system-ui, sans-serif;
}

Use WOFF2 for download performance, but validate that the PDF output includes embedded fonts when needed. Some compliance requirements demand embedded fonts.

Performance Reality Check#

Launching Chromium is expensive. Real-world cold start overhead can be multiple seconds even before your code runs, and memory usage can exceed hundreds of megabytes for complex pages.

That is why browser-based PDF generation belongs in an async job pipeline unless you are certain your platform can handle it synchronously.

# Approach 3: Puppeteer and Why It Still Exists#

Puppeteer remains common because many older setups and examples use it. If your team already has stable Puppeteer code and infra, there is no urgent reason to rewrite.

Choose Playwright for new builds when you want:

  • Better cross-browser tooling
  • More active development patterns and testing utilities
  • Cleaner APIs for waiting on page readiness

From a PDF rendering standpoint, both are Chromium-driven and share most constraints.

# Reference Architecture: Async PDF Generation with Background Jobs and Secure Delivery#

A production-grade system answers these questions:

  • How do we generate without blocking user flows?
  • How do we prevent duplicate generation?
  • How do we store and serve PDFs securely?
  • How do we support regeneration when data changes?
  • How do we observe failures and retry safely?

High-Level Flow#

  1. 1
    User requests an invoice PDF from the app.
  2. 2
    API route creates a pdf_job record with status queued.
  3. 3
    A background worker generates the PDF.
  4. 4
    Worker uploads PDF to object storage.
  5. 5
    App returns a short-lived signed URL for download.

This pattern works for both React-PDF and browser-based renderers.

Data Model Table#

EntityKey fieldsNotes
pdf_jobid, type, referenceId, status, attempts, error, createdAtreferenceId could be invoice id, report id, statement id
pdf_fileid, jobId, storageKey, sha256, sizeBytes, contentType, createdAtStore checksum to detect corruption and enable caching
access_grantuserId, fileId, expiresAtOptional, if you need auditable access control

Why Object Storage and Signed URLs#

Deliver PDFs via object storage with signed URLs. It offloads bandwidth, supports large files, and enables secure access without exposing your backend.

For implementation details and best practices, use: Next.js file uploads with S3 or R2 presigned URLs.

Secure Delivery Pattern#

  • Store PDFs with non-guessable keys, for example pdf/invoices/{invoiceId}/{jobId}.pdf but avoid exposing sequential ids.
  • Validate access in your app before signing.
  • Issue a short-lived signed URL, typically 60 seconds to 10 minutes depending on UX.

API Endpoints#

A practical set of endpoints looks like this:

EndpointMethodPurposeReturns
/api/pdf/invoices/{id}/requestPOSTCreate or reuse a pdf jobjob id and status
/api/pdf/jobs/{jobId}GETPoll job statusqueued, running, done, failed
/api/pdf/files/{fileId}/downloadPOSTAuthorize and sign URLsigned URL

You can reduce endpoints by returning the file URL when ready, but keeping download signing separate is cleaner for auditing.

Idempotency and Deduplication#

For invoices, you typically want deterministic outputs. Use an idempotency key like invoiceId + invoiceVersion to avoid generating the same PDF repeatedly.

A simple rule:

  • If an existing pdf_file exists for the latest invoice version, return it.
  • If a job is already queued or running for that version, return the job id.

This prevents stampedes when multiple users click “Download” at the same time.

Background Worker Setup#

The worker can run as:

  • A separate service
  • A serverless cron-triggered runner
  • A queue consumer

If you are on Vercel, you’ll usually combine a queue with cron or an external worker. The background jobs guide covers practical options: Next.js background jobs, queues, and cron on Vercel.

Example Worker Pseudocode#

Keep the job handler strict: validate inputs, generate, upload, then atomically mark done.

TypeScript
// worker/pdf-job.ts
import { generateInvoicePdf } from "@/lib/pdf/generate-invoice";
import { uploadPdf } from "@/lib/storage/upload";
import { db } from "@/lib/db";
 
export async function handlePdfJob(jobId: string) {
  const job = await db.pdfJob.findUniqueOrThrow({ where: { id: jobId } });
  await db.pdfJob.update({ where: { id: jobId }, data: { status: "running" } });
 
  try {
    const { buffer, sha256 } = await generateInvoicePdf(job.referenceId);
    const storageKey = await uploadPdf(buffer, `pdf/${job.type}/${jobId}.pdf`);
 
    const file = await db.pdfFile.create({
      data: { jobId, storageKey, sha256, sizeBytes: buffer.byteLength, contentType: "application/pdf" },
    });
 
    await db.pdfJob.update({ where: { id: jobId }, data: { status: "done", fileId: file.id } });
  } catch (e) {
    await db.pdfJob.update({
      where: { id: jobId },
      data: { status: "failed", error: e instanceof Error ? e.message : "Unknown error" },
    });
    throw e;
  }
}

Where Stripe Webhooks Fit#

If your PDFs are invoices tied to payments, generate them after you have a confirmed payment event. Do not generate them inside the webhook handler itself.

Instead:

  • Webhook verifies event authenticity.
  • Webhook writes state changes and enqueues a PDF job.
  • Worker generates the PDF.

This matches the reliability guidance in: Next.js App Router payments with Stripe webhooks.

# Rendering Reliability: Fonts, Locales, and Determinism#

Lock Your Inputs#

PDF generation should be deterministic. Store a snapshot of the data used to generate the PDF, or version your invoice and render from that immutable version.

If the invoice total can change after the PDF is generated, you’ll eventually deliver the “wrong” PDF. This becomes a compliance issue in many industries.

Locale and Currency Formatting#

Use a consistent locale in formatting. A classic production bug is a server using a different default locale than your dev machine.

Prefer explicit formatting via Intl.NumberFormat with fixed locale and currency.

TypeScript
// lib/format/money.ts
export function formatMoney(amountCents: number, currency: string) {
  return new Intl.NumberFormat("en-US", {
    style: "currency",
    currency,
  }).format(amountCents / 100);
}

Image Handling#

  • Use vector formats when possible for logos, otherwise high-resolution PNG.
  • Cache external assets. Do not fetch remote logos during generation unless you control the uptime.
  • If you must fetch assets, timebox requests and fail gracefully.

# Pagination Strategies That Don’t Break#

Pagination is where many PDFs fail, especially long reports.

For Invoices and Simple Documents#

  • Keep line items with a fixed height.
  • Use consistent margins and avoid fractional pixel issues.
  • Ensure totals and payment instructions never split across pages.

For Reports and Analytics#

  • Consider splitting sections by page intentionally.
  • Use a “cover page”, “summary”, then “details” approach.
  • For tables, repeat headers each page if your renderer supports it, or render the header before each chunk.

A practical chunking rule for tables: decide on a max row count per page based on font size and row height, then chunk server-side before rendering. This avoids renderer-specific surprises.

# Performance: What to Measure and How to Improve It#

What Actually Matters#

Track these metrics:

MetricWhy it mattersTypical target
Time to first byte for signed URLUser-perceived latencyless than 300 ms
Job queue wait timeBacklog indicatorless than 30 s p95
PDF render timeCPU costless than 3 to 10 s depending on size
Failure rateReliability indicatorless than 0.5 percent
Regeneration rateSignals non-determinismtrending to zero

Optimization Levers#

  • Prefer React-PDF for high-volume, consistent layouts.
  • Avoid huge images and base64 payloads inside HTML.
  • For Playwright, minimize network requests by inlining critical CSS and using local assets.
  • Use caching keyed by documentId + version.

ℹ️ Note: For long reports, the fastest optimization is often product-level: generate a summary PDF by default and provide a separate “full export” that runs asynchronously and notifies the user when ready.

# Practical Recommendation Matrix#

Use this as a starting point:

Use caseRecommended rendererWhy
SaaS invoice PDFReact-PDFDeterministic layout, stable fonts, scalable generation
Shipping labelReact-PDFPredictable size and positioning
Client-ready proposal matching a web pagePlaywrightPixel-perfect HTML rendering
Analytics report with chartsPlaywrightBrowser rendering for charts and CSS
Massive report, 200 plus pagesReact-PDF or dedicated worker with PlaywrightNeeds chunking, careful memory management

# Key Takeaways#

  • Choose React-PDF for deterministic, template-driven documents like invoices, and Playwright or Puppeteer for pixel-perfect HTML rendering and complex CSS.
  • Treat Next.js PDF generation as an async pipeline: enqueue a job, generate in a worker, store in object storage, and deliver via short-lived signed URLs.
  • Embed fonts explicitly and validate with CI snapshots that include special characters, currencies, and multi-page tables.
  • Design pagination intentionally using chunking and “no split” rules for critical blocks like totals and signature sections.
  • Protect critical flows: do not render PDFs inside Stripe webhooks or checkout requests, enqueue jobs instead and keep handlers fast.
  • Measure queue wait time, render time, and failure rate, then optimize by caching per document version and reducing browser overhead.

# Conclusion#

Next.js PDF generation is reliable when you pick the right renderer, embed fonts deliberately, and move heavy rendering into an async job pipeline with secure delivery. If you want a production-ready implementation for invoices or reports in the App Router, Samioda can help you design the job system, storage, and rendering layer so PDFs generate fast and look identical in every environment.

Contact us through Samioda to review your current setup and ship a PDF pipeline that won’t break under real traffic.

FAQ

Share
A
Adrijan OmićevićFounder & Senior Developer

Founder & Senior Developer at Samioda. 8+ years building React, Next.js, Flutter and n8n automation solutions for clients across Europe.

Need help with your project?

We build custom solutions using the technologies discussed in this article. Senior team, fixed prices.