Next.jsReactTutorial
How to Generate PDFs in Next.js (Server vs Client)
The Next.js PDF Dilemma
So you've built a beautiful Next.js app, and now you need to export a page as a PDF. You have two main options:
- Client-Side: Using libraries like
@react-pdf/rendererorjspdf. - Server-Side: Using an API like pdfmyhtml.
Option 1: Client-Side (@react-pdf/renderer)
This library renders PDFs inside the browser using React components.
Pros:
- Offline capability.
- No server costs.
Cons:
- Bundle Size: Note that
react-pdfcan add megabytes to your JS bundle, slowing down your app. - Limited CSS: You can't use standard CSS or Tailwind. You have to recreate your layout using their custom
StyleSheet.createsyntax. - Glitchy Layouts: Rendering inconsistencies between browsers are common.
Option 2: Server-Side API (The Better Way)
Instead of forcing the user's browser to do the heavy lifting, you simply send your HTML (with standard Tailwind classes!) to an API.
// app/api/generate-pdf/route.ts import { NextResponse } from 'next/server'; export async function POST(req: Request) { const { html } = await req.json(); const res = await fetch('https://api.pdfmyhtml.com/v1/html-to-pdf', { method: 'POST', headers: { 'X-API-Key': process.env.PDF_API_KEY }, body: JSON.stringify({ html }) }); const pdfBuffer = await res.arrayBuffer(); return new NextResponse(pdfBuffer, { headers: { 'Content-Type': 'application/pdf' } }); }
Pros:
- Zero Bundle Impact: No heavy libraries in your client code.
- Use Standard CSS: Use the same Tailwind classes you use for your UI.
- Perfect Quality: Renders exactly like Chrome.
Conclusion
If you are building a simple "Download Resume" button, react-pdf is fine.
But if you need invoices, reports, or anything that needs to look professional, Server-Side Generation is the robust choice.