Skip to content
matthewcm.dev

    ↑ ↓ move · ↵ open · tab scopeopen graph →

    PDFs as React Components: Live Previews with react-pdf

    react-pdf (@react-pdf/renderer) is a React renderer whose output is a PDF, not the DOM. The same component gives a live preview in the browser and the final file on the server. What it is, how to integrate it (preview, download, server rendering, fonts, paging), the gotchas, and where it connects to schemas, forms and calm UIs.

    Seedtended planted 8 min read

    🌱 A rough idea, planted recently. Expect rough edges — it will grow.

    On this page

    PDFs are usually the last mile of a product, and the worst-loved part of it. A quote, an invoice, a booking confirmation or a certificate gets built on the server from a template, and the only way to see what it looks like is to click Download and open the file. Change a margin, redeploy, download again.

    react-pdf flips that around. The PDF is a React component tree. Change a prop and the document re-renders, so you can put a live preview of the real file next to the form that feeds it, and render the exact same component on the server when it’s time to send it.

    What it is

    @react-pdf/renderer is a React renderer, in the same family as react-dom and React Native. Instead of DOM nodes it produces a PDF. You write components with its own primitives:

    PrimitiveRole
    DocumentThe file: metadata (title, author, language) and the pages
    PageA page, with a size (A4, LETTER, custom) and orientation
    ViewThe box: layout, borders, backgrounds, like a div
    TextText, the only place strings can go
    Image, Svg, CanvasGraphics
    Link, NoteLinks and annotations

    There’s no browser in the pipeline. The docs describe the steps: React’s reconciler builds the tree, styles are resolved into full values, fonts and images are fetched, text is shaped with fontkit and broken into lines with the Knuth-Plass algorithm (the one TeX uses, which balances a whole paragraph rather than filling lines greedily), Yoga (the flexbox engine from React Native) lays out the boxes and pages, and pdfkit writes the file. Because nothing depends on a browser, the same code runs on the client and in Node.

    [!note] Two libraries, similar names react-pdf on npm (by Wojciech Maj) displays existing PDFs. @react-pdf/renderer, the one in this note, creates them. The docs site is react-pdf.org. Check which one a tutorial means before copying code.

    A first document

    npm install @react-pdf/renderer
    import { Document, Page, View, Text, StyleSheet } from "@react-pdf/renderer";
    
    type Quote = {
      ref: string;
      customer: string;
      lines: { item: string; qty: number; total: string }[];
      grandTotal: string; // already formatted by the server
    };
    
    const s = StyleSheet.create({
      page: { padding: "18mm", fontSize: 10, fontFamily: "Helvetica" },
      row: { flexDirection: "row", justifyContent: "space-between", paddingVertical: 4 },
      title: { fontSize: 18, marginBottom: 12 },
    });
    
    export function QuoteDocument({ quote }: { quote: Quote }) {
      return (
        <Document title={`Quote ${quote.ref}`}>
          <Page size="A4" style={s.page}>
            <Text style={s.title}>Quote {quote.ref}</Text>
            <Text>For {quote.customer}</Text>
            {quote.lines.map((l) => (
              <View key={l.item} style={s.row}>
                <Text>{l.qty} × {l.item}</Text>
                <Text>{l.total}</Text>
              </View>
            ))}
            <View style={s.row}>
              <Text>Total</Text>
              <Text>{quote.grandTotal}</Text>
            </View>
          </Page>
        </Document>
      );
    }

    It reads like a React Native screen: flexbox by default, styles as objects, every string inside a Text. Styles can be inline, arrays (style={[s.row, overdue && s.warning]}) or created with StyleSheet.create. Units include pt (the default, 72 per inch), mm, cm, in, %, vw and vh. Media queries work on page width, height and orientation.

    The live preview

    This is the part I find exciting. PDFViewer renders the document into an iframe using the browser’s own PDF viewer, so what you see is the file, not an HTML imitation of it:

    import { PDFViewer } from "@react-pdf/renderer";
    
    function QuoteEditor() {
      const [quote, setQuote] = useState<Quote>(emptyQuote);
      return (
        <div className="editor">
          <QuoteForm value={quote} onChange={setQuote} />
          <PDFViewer width="100%" height="100%" showToolbar={false}>
            <QuoteDocument quote={quote} />
          </PDFViewer>
        </div>
      );
    }

    Type in the form and the preview updates. For small documents that’s all there is to it. For bigger ones, two things matter:

    • Rendering is synchronous and not cheap. Every step runs on the calling thread, so re-rendering a 20-page document on each keystroke will make typing feel sticky. Debounce it. The usePDF hook gives you control: const [instance, update] = usePDF({ document: <QuoteDocument quote={quote} /> }), then call update(...) when the input settles and show instance.url in your own <iframe>. instance.loading and instance.error drive a spinner and an error state.
    • Large documents belong in a worker. The docs suggest rendering in a web worker in the browser. It’s the same lesson as any heavy client work (see 60fps under a firehose): keep the main thread for the person typing.

    Download and blobs

    When the preview looks right, there are three ways to hand the file over (all web-only):

    • PDFDownloadLink: a link that builds and downloads the file. <PDFDownloadLink document={<QuoteDocument quote={quote} />} fileName="quote.pdf">. Its children can be a function of { loading }, so the button can say “Preparing…”.
    • BlobProvider: a render prop with { blob, url, loading, error } when you want to upload, attach or open the file yourself.
    • pdf(<QuoteDocument … />).toBlob(): the imperative version, for event handlers or code outside React.

    The same component on the server

    The other half of the value: the server can render the exact component the user just previewed. renderToBuffer, renderToStream, renderToFile and renderToString all take the root element.

    import { renderToStream } from "@react-pdf/renderer";
    import { QuoteDocument } from "@shared/pdf/QuoteDocument";
    
    app.get("/quotes/:ref.pdf", async (req, res) => {
      const quote = await quotes.get(req.params.ref); // totals computed here, not in the PDF
      res.setHeader("Content-Type", "application/pdf");
      const stream = await renderToStream(<QuoteDocument quote={quote} />);
      stream.pipe(res);
    });

    That gives you one source of truth for the document:

    • Preview in the browser while editing, from local state.
    • Final file on the server when it’s sent, stored or emailed, from saved data.
    • Same component, same fonts, same layout. No “the preview looked different” bugs.

    Laying out for paper

    Paper has rules the screen doesn’t. react-pdf covers the common ones:

    • Page wrapping is on by default. Content flows onto new pages. wrap={false} on a View keeps it in one piece (it jumps to the next page instead of splitting), as long as it fits on a single page.
    • break forces a new page before an element.
    • fixed repeats an element on every page: headers, footers, a watermark.
    • render props give you the page number: <Text fixed render={({ pageNumber, totalPages }) => pageNumber + " / " + totalPages} />. totalPages only exists on Text, and the function runs twice (once to lay out, once when the total is known).
    • minPresenceAhead on a heading keeps it from being stranded at the bottom of a page. The docs prefer this to wrapping a heading and its paragraph in wrap={false}. There’s also orphan and widow protection for paragraphs.
    • debug on any element draws its box, which is the fastest way to find out why something moved.

    Fonts

    • The built-in families are Helvetica, Times-Roman and Courier (with bold and italic variants). Anything else must be registered.
    • Font.register({ family: "Inter", fonts: [{ src: regular }, { src: bold, fontWeight: 700 }] }). Only TTF and WOFF, and register static weights: variable fonts don’t work properly.
    • Hyphenation is on for English. Font.registerHyphenationCallback((word) => [word]) turns it off. For other languages there’s @react-pdf/hyphenate.
    • PDFs can’t use colour emoji fonts. Font.registerEmojiSource embeds them as images from a CDN, which means rendering needs network access.

    Integrating it into a project

    What I’d set up from the start:

    1. A pdf/ folder of document components that take plain, typed data as props, and nothing else. No fetching, no hooks into app state. That’s what lets the same component run in a browser preview, on the server and in tests. Type the props: the document is a contract between whoever produces the data and the layout (TypeScript as a Team Contract).
    2. No business maths in the document. Totals, tax, currency formatting and rounding come in as finished values from the back end. A PDF is a record someone may rely on; it shouldn’t compute its own numbers (Let the Server Do the Money Maths).
    3. Lazy-load the renderer in the client. It brings Yoga, fontkit and pdfkit, which is a lot to ship to people who never open the preview. Load the editor route (or the preview panel) with a dynamic import().
    4. Shared tokens. Put brand colours, font sizes and spacing in one module used by both the web UI and the documents, so the PDF stays recognisably the same product.
    5. Tests on the output. renderToBuffer in a unit test, then check the page count and that the key text is there. Add a visual check for the one or two documents that matter most.

    Compatibility notes from the docs:

    • React 16.8 and later, including React 19 since v4.1. At the time of writing the current version is 4.9.
    • Node: tested on 18, 20 and 21. Bun is unofficial but reported to work.
    • Next.js: fine in general. The App Router crash is fixed in 14.1.1+. On older versions, add serverComponentsExternalPackages: ["@react-pdf/renderer"] under experimental in the Next config. PDFViewer only runs in the browser, so put it in a client component, loaded without SSR.
    • esbuild in ESM mode can fail with __dirname is not defined in ES module scope (from Yoga). The docs give a small shim to inject until Yoga fixes it.

    Gotchas

    • It’s not HTML and CSS. You can’t drop your web components in. Only the react-pdf primitives render, the CSS is a subset (flexbox yes, grid no) and there’s no DOM. Plan for a separate set of document components, sharing tokens and data, not markup.
    • Images need CORS when they’re fetched in the browser, and remote images and fonts slow every render. Bundle the ones you always use.
    • Accessibility and selection. Text stays real, selectable text, which is good. Still check tagging and reading order if the documents need to meet an accessibility standard.

    react-pdf or a headless browser?

    The other common route is rendering HTML and printing it with a headless browser (Puppeteer or Playwright’s page.pdf()).

    react-pdfHeadless browser
    SourceReact components, own primitivesAny HTML and CSS you already have
    Live previewThe real file, in the browserOnly by rendering on a server
    Server needsNodeA Chromium binary
    LayoutFlexbox, paging built inFull CSS, print CSS for paging
    Best forDesigned documents: quotes, invoices, tickets, certificates, CVsPrinting a web page as it already looks

    If the document is its own designed thing, and especially if people edit it before it goes out, react-pdf is the better fit.

    Where this connects to earlier ideas

    • Documents as data. If domain experts publish schemas and the UI just renders them (Keep the UI Dumb: Let Domain Experts Publish Schemas), a PDF template is one more renderer of the same data. A document component that only takes typed props is exactly a “dumb UI”.
    • Forms that feed documents. The sketch-to-form builder idea ends with a JSON Schema form. Put a react-pdf preview next to it and the form shows its own output as you fill it in.
    • Preview in its own tab. In Grow the Interface with the User the preview and the summary got their own tab rather than being squeezed under the editor. A PDF preview is the clearest case of that, and a template catalog (use a template, duplicate and change, build from scratch) is the same Use → Adapt → Author path.
    • Confirm the difference. In Compact, Not Cramped the commit step shows what’s unusual before money moves. A live preview of the exact document a customer will receive is the strongest form of that: no surprises in the file after it’s sent.

    Things I want to try with it

    • A CV and portfolio PDF generated from the same content as this site, so the two never drift apart.
    • Workout session sheets, printable, from the same data as the training graphics.
    • A quote or booking-confirmation editor with a side-by-side preview and a “what changed since the last version” summary.

    Sources

    • react-pdf.org: docs for components, styling, fonts, the Node API, rendering process, page wrapping, dynamic content, on-the-fly rendering and compatibility (v4).
    • diegomura/react-pdf on GitHub.
    • #react
    • #pdf
    • #react-pdf
    • #document-generation
    • #live-preview
    • #nodejs
    • #nextjs
    • #web-development

    Nothing links here yet — it’s a fresh shoot.

    ↪ Links to (4)