PDFreact-print-pdf
DocsBrowser-only alpha

React API

usePDFExport, Printable, and ExportButton — sugar on top of the imperative exportToPDF function.

Edit this page

exportToPDF(element, options) is the primitive: it takes an HTMLElement, runs the pipeline, and returns a result handle. Everything else on this page is sugar on top of that one function so the common case is one component or one hook call.

When to use what

ToolUse it when
exportToPDFYou're outside React, or you want full control over the lifecycle.
usePDFExportYou're in a React component and want the ref + loading state + error state to come for free.
<Printable>You want the printable container's width to match the PDF page automatically.
<ExportButton>You want a working button in one component, no boilerplate.

You can mix and match. The hook + <Printable> pair is the most common combination.

usePDFExport

import { Printable, usePDFExport } from "react-print-pdf";

function InvoiceExport() {
  const { ref, exportPDF, isExporting, error, lastResult, reset } = usePDFExport({
    format: "A4",
    margin: "20mm",
    filename: "invoice.pdf",
    title: "Invoice #1042",
  });

  return (
    <>
      <button type="button" onClick={exportPDF} disabled={isExporting}>
        {isExporting ? "Exporting…" : "Export PDF"}
      </button>

      {error && (
        <div role="alert">
          {error.message}
          <button type="button" onClick={reset}>Dismiss</button>
        </div>
      )}

      <Printable ref={ref} format="A4" margin="20mm">
        <Invoice />
      </Printable>
    </>
  );
}

Returned values

FieldTypeMeaning
refMutableRefObject<HTMLElement | null>Attach to the printable container.
exportPDF() => Promise<void>Trigger an export. Resolves when the export finishes (success or failure).
isExportingbooleanTrue between the moment exportPDF() is called and the moment its work completes.
errorError | nullLast error. Cleared when a fresh export starts or on reset().
lastResultPDFExportResult | nullResult from the most recent successful export.
reset() => voidClear error and lastResult without triggering an export.

Hook-only options

In addition to every field on ExportOptions, the hook accepts:

OptionDefaultMeaning
autoSavetrueCalls result.save() automatically after a successful export. Set false for upload-only flows.
onSuccessFires after a successful export, before the optional auto-save. Receives the PDFExportResult.
onErrorFires when the export throws. Receives the Error (typed as PdfExportError when it originates from the library).

Generic ref typing

The hook is generic in the element type so the ref attaches to whatever container you use:

const { ref } = usePDFExport<HTMLElement>(); // matches a <Printable> or any element
const { ref } = usePDFExport<HTMLDivElement>(); // strictly a <div>

The default is HTMLDivElement to match the most common case.

Stable identity

exportPDF and reset are stable across renders, so it's safe to put them in useEffect / useCallback dependency arrays. Options are read fresh from a ref on every call, so changing filename or margin between renders takes effect immediately without forcing the hook to re-create its handlers.

<Printable>

A forwardRef'd <div> that:

  1. Sets width to pageContentWidth({ format, margin, orientation }) so the source DOM matches the destination PDF.
  2. Tags itself with data-rpp-printable so future tooling (debug overlay UI, optional ESLint plugin) can find printable regions.
<Printable ref={ref} format="A4" margin="20mm">
  <Invoice />
</Printable>

Props

PropTypeDefaultMeaning
formatPageFormat"A4"Page format used to compute width.
orientationOrientation"portrait"Page orientation used to compute width.
marginMargin"20mm"Page margin used to compute width.
autoWidthbooleantrueSet false to opt out of automatic sizing (e.g. nesting inside another sized container).

Every other <div> prop (className, style, role, data-*, …) is forwarded.

The component uses forwardRef, so the ref always lands on the underlying <div>. Pair it with usePDFExport().ref:

const { ref } = usePDFExport({ format: "A4", margin: "20mm" });
return <Printable ref={ref} format="A4" margin="20mm"><Invoice /></Printable>;

When you pass conflicting margins / formats to the hook and the component, the hook's options drive the export and the component's drive the on-screen size. Keep them in sync.

<ExportButton>

A <button> wired to usePDFExport for the simple case.

import { useRef } from "react";
import { ExportButton, Printable } from "react-print-pdf";

function InvoiceExport() {
  const target = useRef<HTMLDivElement>(null);

  return (
    <>
      <ExportButton
        target={target}
        options={{ format: "A4", margin: "20mm", filename: "invoice.pdf" }}
      >
        Download PDF
      </ExportButton>

      <Printable ref={target} format="A4" margin="20mm">
        <Invoice />
      </Printable>
    </>
  );
}

Props

PropTypeDefaultMeaning
targetRefObject<HTMLElement>Required. Ref to the printable element.
optionsUsePDFExportOptions{}Forwarded to the underlying usePDFExport.
childrenReactNode"Export PDF"Idle-state label.
loadingLabelReactNode | null"Exporting…"In-flight label. Pass null to keep the original label (useful when you put a spinner inline).
onExportError(e: Error) => voidConvenience prop for error handling. Fires alongside options.onError if both are set.

The button defaults to type="button" so it never accidentally submits a parent form. It's disabled while an export is in flight. Every other <button> prop (className, style, aria-*, …) is forwarded.

When to drop down to the hook

Reach for usePDFExport directly when you need any of:

  • A non-button trigger (link, menu item, command palette entry)
  • Custom in-flight UI (progress bar driven by onProgress or onPageRendered, skeleton, toast)
  • Multiple targets reachable from one trigger
  • Error UI more elaborate than a single onExportError handler

On this page