# Compatibility URL: /docs/v4/compatibility ## Compatibility with Node.js We currently test react-pdf against Node.js 18, 20, and 21 (latest minors), so these are the versions we recommend using. Chances are you may use react-pdf with older versions of Node.js as well, but we can't guarantee it will work as expected. ## Compatibility with Bun While we don't officially support Bun, we have received reports that it works well with react-pdf. ## Compatibility with React `@react-pdf/renderer` is compatible with React 16 (16.8.0 or later), React 17, React 18 and React 19 (since v4.1.0) ## Compatibility with Next.js In general, you may use react-pdf with Next.js regardless of the version. However, before Next.js 14.1.1, Next.js (App Router) suffered from a bug that caused the Next.js server to crash when using react-pdf. If you encounter: ```text TypeError: ba.Component is not a constructor ``` You should upgrade to Next.js 14.1.1 or later. If that's not possible, update your Next.js config like this: ```js const nextConfig = { // … experimental: { // … serverComponentsExternalPackages: ['@react-pdf/renderer'], }, }; ``` ## Compatibility with esbuild If you are using esbuild to bundle your react-pdf application in ESM mode, you may encounter an error: ```text __dirname is not defined in ES module scope ``` This is because our dependency, [Yoga layout](https://yogalayout.com/), uses `__dirname` in their code. This will be fixed by the upcoming release of Yoga layout, but for now, you can work around this issue by using the `inject` option in esbuild. Create a file called `cjs-shim.ts`: ```ts import { createRequire } from 'node:module'; import path from 'node:path'; import url from 'node:url'; globalThis.require = createRequire(import.meta.url); globalThis.__filename = url.fileURLToPath(import.meta.url); globalThis.__dirname = path.dirname(__filename); ``` Then, add it to your `esbuild.ts`: ```ts await esbuild.build({ // … inject: ['cjs-shim.ts'], }); ``` And you should be good to go! --- # Floats URL: /docs/v4/floats react-pdf supports CSS floats. A floated element is taken out of the normal flow and pinned to one side of its container, with the surrounding text wrapping around it. This is the tool for drop caps, figures with captions, pull quotes and other article-style layouts. Set `float` to `left` or `right` on any View or Image, and place the wrapping text as its sibling: ```jsx import React from 'react'; import { Page, Text, View, Image, Document } from '@react-pdf/renderer'; const MyDocument = () => ( This text wraps along the left side of the image, and recovers the full width of the page once past its bottom edge... ); ``` A float only affects the lines that overlap it vertically, and margins on the floated element define the gap between it and the text. Anything nested inside the floated element (a caption, for instance) travels with it and takes no part in the wrapping. > **Protip:** Text wrapping is resolved at layout time, so react-pdf may measure a wrapping paragraph shorter than it ends up being. If content below overlaps it, reserve the real height on the wrapping container with `minHeight` ## Clear The `clear` property moves an element below preceding floats, just like in CSS. Valid values are `left`, `right`, `both` and `none` _(default)_: ```jsx This text wraps around the float This text starts below it ``` ```jsx const styles = StyleSheet.create({ page: { padding: 40, fontSize: 11, fontFamily: 'Times-Roman', }, section: { marginBottom: 30, }, text: { textAlign: 'justify', }, }); const doc = ( E n un lugar de la Mancha, de cuyo nombre no quiero acordarme, no ha mucho tiempo que vivía un hidalgo de los de lanza en astillero, adarga antigua, rocín flaco y galgo corredor. Una olla de algo más vaca que carnero, salpicón las más noches, duelos y quebrantos los sábados, lentejas los viernes, algún palomino de añadidura los domingos, consumían las tres partes de su hacienda. El resto della concluían sayo de velarte, calzas de velludo para las fiestas con sus pantuflos de lo mismo, los días de entre semana se honraba con su vellori de lo más fino. Tenía en su casa una ama que pasaba de los cuarenta, y una sobrina que no llegaba a los veinte, y un mozo de campo y plaza, que así ensillaba el rocín como tomaba la podadera. Frisaba la edad de nuestro hidalgo con los cincuenta años, era de complexión recia, seco de carnes, enjuto de rostro; gran madrugador y amigo de la caza. Quieren decir que tenía el sobrenombre de Quijada o Quesada, aunque por conjeturas verosímiles se deja entender que se llama Quijana; pero esto importa poco a nuestro cuento. This line has clear: right, so it starts below the float. ); ReactPDF.render(doc); ``` [Open in Playground](/playground?example=float) ## Shape outside By default text wraps around the float's rectangular box. The `shapeOutside` property replaces that rectangle with a CSS basic shape, and every line is measured against the shape's real edge instead: | Shape | Example | | ------------------------------ | -------------------------------------------- | | `circle(radius at position)` | `circle(50%)`, `circle(40pt at left center)` | | `ellipse(rx ry at position)` | `ellipse(50% 40% at center)` | | `polygon(x y, x y, ...)` | `polygon(100% 0, 100% 100%, 0 100%)` | | `inset(top right bottom left)` | `inset(0 20pt 0 0)` | Radii, coordinates and offsets take the same lengths, percentages and keywords as CSS (`closest-side` and `farthest-side` included), all resolved against the float's box, and a bare number means points. Anything react-pdf can't parse, `url()` among them, drops the property and leaves the plain box exclusion in place. ```jsx This text creeps in toward the circle, line by line... ``` > **Protip:** there is no `shapeMargin`, and side margins stop widening the exclusion once a shape is set. To leave a gap between the artwork and the text, draw the shape smaller than the float box. The 130pt box around that 100pt circle is what keeps the lines 15pt clear of it ```jsx const styles = StyleSheet.create({ page: { padding: 40, fontSize: 11, fontFamily: 'Times-Roman', }, section: { marginBottom: 16, // floats don't grow their parent, so reserve the artwork's height minHeight: 150, }, label: { fontFamily: 'Courier', fontSize: 9, color: '#4069b4', marginBottom: 6, }, text: { textAlign: 'justify', }, }); const circleText = 'A circle exclusion is widest across its middle, so the lines beside it ' + 'grow shorter down to the equator and then open back up, and the ' + 'paragraph recovers the full measure only once it clears the bottom of ' + 'the shape. The float box here is 130pt square while the drawn circle is ' + 'only 100pt across: shape-margin has no equivalent in react-pdf, and ' + 'side margins stop widening the exclusion once a shape is set, so the ' + 'extra 15pt of empty box on each side is what keeps the text off the ' + 'artwork. Make the box bigger than the shape whenever you want ' + 'breathing room, or shrink ' + 'the radius and leave the box alone. Below the circle the exclusion is ' + 'over and the lines run the full width of the page again.'; const polygonText = 'A polygon takes the same comma-separated coordinate pairs as CSS, each ' + 'resolved against the float box, and every line is measured against the ' + 'real edge rather than the bounding rectangle. This wedge is a point at ' + 'the top and the full width of the box at the bottom, so the first lines ' + 'run nearly to the right margin and each one after gives back a little ' + 'more room to the diagonal. Any convex or concave outline works the same ' + 'way, which is what makes polygons the practical choice for wrapping ' + 'text around a cut-out illustration, a logo or a chart with an irregular ' + 'silhouette. Coordinates may be lengths as well, so the same wedge could ' + 'be written as polygon(130 0, 130 130, 0 130) when the float box has a ' + 'fixed size and you would rather think in points.'; const ellipseText = 'An ellipse takes two radii instead of one, so you can flatten or ' + 'stretch the exclusion independently of the box, and inset() carves a ' + 'rectangle in from the edges of the float box. Radii and offsets accept ' + 'lengths or percentages, percentages resolve against the box, and both ' + 'shapes can be moved with the at keyword exactly like their CSS ' + 'counterparts. When a value cannot be parsed the property is dropped and ' + 'text falls back to wrapping around the plain rectangular box, which is ' + 'also what happens for shapes react-pdf does not support, such as ' + 'url() references, so a typo costs you the curve and never the ' + 'paragraph.'; const doc = ( circle(50%) {circleText} polygon(100% 0, 100% 100%, 0 100%) {polygonText} ellipse(50% 40% at center) {ellipseText} ); ReactPDF.render(doc); ``` [Open in Playground](/playground?example=shape-outside) --- # Fonts URL: /docs/v4/fonts React-pdf is shipped with a `Font` module that enables to load fonts from different sources, handle how words are wrapped and defined an emoji source to embed these glyphs on your document. You can define multiple sources for the same font family, each with a different `fontStyle` or `fontWeight`. React-pdf will pick the appropriate font for each `` based on its style and the registered fonts. Currently, - [only TTF and WOFF fonts files are supported](https://github.com/diegomura/react-pdf/issues/334). A list of available TTF fonts from Google can be found [here](https://gist.github.com/sadikay/d5457c52e7fb2347077f5b0fe5ba9300). - Any OpenType Variable fonts (such as Noto Sans variable weights font) does not work properly because PDF 2.0 spec does not support those. It is required to register separate fonts using 'fonts' property (explained in below). ```jsx import { StyleSheet, Font } from '@react-pdf/renderer'; // Register font Font.register({ family: 'Roboto', src: source }); // Reference font const styles = StyleSheet.create({ title: { fontFamily: 'Roboto', }, }); ``` --- ## OpenType font features The `fontFeatureSettings` style property picks which OpenType features the font applies: tabular figures that line up in a column, slashed zeros, real fractions, small capitals, alternate ligatures, and whatever else the font was built with. Pass an array to switch features on, or an object to set them one by one: ```jsx const styles = StyleSheet.create({ amounts: { fontFeatureSettings: ['tnum', 'zero'] }, plain: { fontFeatureSettings: { calt: 0, kern: 0 } }, }); ``` Kerning and ligatures (`kern`, `liga`, `clig`, `rlig`, `calt`) are applied by default, so the object form is the only way to turn one back off. Like `fontFamily`, the property is inherited: set it on a `View` or `Page` and every `Text` inside picks it up. ### Common tags | Tag | Effect | | --------------- | ------------------------------------------------------------- | | `tnum` | Tabular figures: every digit the same width, so columns align | | `onum` | Old-style figures, with ascenders and descenders | | `lnum` | Lining figures, all at cap height | | `zero` | Slashed zero | | `frac` | Turns `1/2` into a single fraction glyph | | `sups` / `subs` | Superscript and subscript forms | | `smcp` / `c2sc` | Small capitals, from lowercase and from capitals | | `case` | Case-sensitive forms: punctuation raised to match capitals | | `liga` / `dlig` | Standard and discretionary ligatures | | `calt` | Contextual alternates | | `swsh` | Swashes | | `hist` | Historical forms | | `ss01`–`ss20` | Stylistic sets, whose meaning is up to the font | | `kern` | Kerning between letter pairs | Which of these do anything depends on the font file. The standard fonts (`Helvetica`, `Times-Roman`, `Courier`) support none of them, and a registered font only carries the features it shipped with; asking for a tag it doesn't have is silently ignored. To see what a font actually offers: ```js import fontkit from 'fontkit'; fontkit.openSync('Inter-Regular.ttf').availableFeatures; // ['aalt', 'calt', 'case', 'ccmp', 'dlig', 'frac', 'ss01', …, 'tnum', 'zero', 'kern'] ``` ```jsx Font.register({ family: 'Inter', src: '/fonts/Inter-Regular.ttf', }); const styles = StyleSheet.create({ page: { fontFamily: 'Inter', fontSize: 14, padding: 40, }, row: { flexDirection: 'row', alignItems: 'center', marginBottom: 18, }, label: { width: 130, fontSize: 9, color: '#71717a', textTransform: 'uppercase', }, tabular: { fontFeatureSettings: ['tnum'], }, noKerning: { fontFeatureSettings: { kern: 0 }, }, }); const MyDocument = () => ( Default figures Invoice 111,111.11 Invoice 888,888.88 tnum Invoice 111,111.11 Invoice 888,888.88 Default kerning AVATAR Wave Today kern: 0 AVATAR Wave Today ); ReactPDF.render(); ``` [Open in Playground](/playground?example=font-feature-settings) --- ## `register` Fonts really make the difference when it comes on styling a document. For obvious reasons, react-pdf cannot ship a wide amount of them. Here's a list of available font families that are supported out of the box: - `Courier` - `Courier-Bold` - `Courier-Oblique` - `Courier-BoldOblique` - `Helvetica` - `Helvetica-Bold` - `Helvetica-Oblique` - `Helvetica-BoldOblique` - `Times-Roman` - `Times-Bold` - `Times-Italic` - `Times-BoldItalic` In case you want to use a different font, you may load additional font files from many different sources via the `register` method very easily. ```jsx import { Font } from '@react-pdf/renderer' Font.register({ family: 'FamilyName', src: source, fontStyle: 'normal', fontWeight: 'normal', fonts?: [] }); ``` ### source Specifies the source of the font. This can either be a valid URL, or an absolute path if you're using react-pdf on Node. ### family Name to which the font will be referenced on styles definition. Can be any unique valid string ### fontStyle Specifies to which font style the registered font refers to. | Value | Description | | ------- | :------------------------------------------------------------------------------------------------------------------------------------------------------ | | normal | Selects a font that is classified as normal _Default_ | | italic | Selects a font that is classified as italic. If no italic version of the font is registered, react-pdf will fail when a style of this type is present | | oblique | Selects a font that is classified as oblique. If no oblique version of the font is registered, react-pdf will fail when a style of this type is present | ### fontWeight Specifies the registered font weight. | Value | Description | | ---------- | :----------------------------------- | | thin | Equals to value 100 | | ultralight | Equals to value 200 | | light | Equals to value 300 | | normal | Equals to value 400 _Default_ | | medium | Equals to value 500 | | semibold | Equals to value 600 | | bold | Equals to value 700 | | ultrabold | Equals to value 800 | | heavy | Equals to value 900 | | _number_ | Any integer value between 0 and 1000 | When the exact font weight is not registered for a given text, react-pdf will fallback to the nearest registered weight in the same way browsers do. More information [here](https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight#Fallback_weights) ```jsx Font.register({ family: 'Roboto', fonts: [ { src: `/fonts/Roboto-Regular.ttf` }, { src: `/fonts/Roboto-Bold.ttf`, fontWeight: 'bold' }, { src: `/fonts/Roboto-Italic.ttf`, fontWeight: 'normal', fontStyle: 'italic' }, { src: `/fonts/Roboto-BoldItalic.ttf`, fontWeight: 'bold', fontStyle: 'italic' } ] }) const MyDocument = () => ( Velit sit cillum adipisicing aliqua id sint cillum occaecat fugiat adipisicing non elit. Velit sit cillum adipisicing aliqua id sint cillum occaecat fugiat adipisicing non elit. Velit sit cillum adipisicing aliqua id sint cillum occaecat fugiat adipisicing non elit. Velit sit cillum adipisicing aliqua id sint cillum occaecat fugiat adipisicing non elit. ); ReactPDF.render(); ``` [Open in Playground](/playground?example=font-register) ### fonts In many cases you will end up registering multiple sources for the same font family (each with different font-style and font-weight for instance). As an alternative of calling `Font.register` for each of this, you can use the `fonts` attribute to register them all at once: ```jsx Font.register({ family: 'Roboto', fonts: [ { src: source1 }, // font-style: normal, font-weight: normal { src: source2, fontStyle: 'italic' }, { src: source3, fontStyle: 'italic', fontWeight: 700 }, ], }); ``` --- ## `registerHyphenationCallback` Enables you to have fine-grained control over how words break, passing your own callback and handle all that logic for yourself: ```jsx import { Font } from '@react-pdf/renderer'; const hyphenationCallback = (word) => { // Return word parts in an array }; Font.registerHyphenationCallback(hyphenationCallback); ``` To hyphenate a language other than the default `en-us`, register a `syllables` function from [@react-pdf/hyphenate](https://github.com/diegomura/react-pdf/tree/master/packages/hyphenate): ```jsx import { Font } from '@react-pdf/renderer'; import { syllables } from '@react-pdf/hyphenate/de'; Font.registerHyphenationCallback(syllables); ``` ```jsx // Register hyphenation callback. // In this example, we enable words to break in half Font.registerHyphenationCallback(word => { const middle = Math.floor(word.length / 2); const parts = word.length === 1 ? [word] : [word.substr(0, middle), word.substr(middle)]; // Check console to see words parts console.log(word, parts); return parts; }); const styles = StyleSheet.create({ container: { padding: 50 }, text: { textAlign: 'justify' } }); const MyDocument = () => ( Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vulputate erat id sagittis porta. Phasellus ut diam sit amet mi sagittis faucibus sed in purus. Etiam pretium et lacus sit amet fringilla. Aenean hendrerit volutpat nulla, at facilisis ante bibendum non. Integer ut nulla nulla. Etiam ornare interdum iaculis. Sed lectus nisl, faucibus vitae posuere ut, lobortis in lectus. Donec ac magna in libero tincidunt volutpat. Donec ut varius quam. Duis ornare justo quis sapien bibendum cursus. ); ReactPDF.render(); ``` [Open in Playground](/playground?example=hyphenation-callback) ### Disabling hyphenation You can easily disable word hyphenation by just returning the same word as it is passed to the hyphenation callback ```jsx Font.registerHyphenationCallback((word) => [word]); ``` ```jsx Font.registerHyphenationCallback(word => { // Return entire word as unique part return [word]; }); const styles = StyleSheet.create({ container: { padding: 50 }, text: { textAlign: 'justify' } }); const MyDocument = () => ( Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vulputate erat id sagittis porta. Phasellus ut diam sit amet mi sagittis faucibus sed in purus. Etiam pretium et lacus sit amet fringilla. Aenean hendrerit volutpat nulla, at facilisis ante bibendum non. Integer ut nulla nulla. Etiam ornare interdum iaculis. Sed lectus nisl, faucibus vitae posuere ut, lobortis in lectus. Donec ac magna in libero tincidunt volutpat. Donec ut varius quam. Duis ornare justo quis sapien bibendum cursus. ); ReactPDF.render(); ``` [Open in Playground](/playground?example=disable-hyphenation) --- ## `hyphenationPenalty` In some cases you can avoid the need for custom break logic by tuning/adjusting at what level a word is sliced for hyphenation. Providing the `hyphenationPenalty` prop on `Text` components allows you to tune this. Higher values makes the algorithm more reluctant to break words across lines: ```jsx import { Text } from '@react-pdf/renderer'; Lorem ipsum dolor sit amet consectetur adipiscing elit ; ``` It defaults to `100` for justified text and `600` otherwise. Setting it to `Infinity` disables automatic hyphenation entirely for that text block, so lines break only at word boundaries: ```jsx Lorem ipsum dolor sit amet consectetur adipiscing elit ``` --- ## `registerEmojiSource` PDF documents do not support color emoji fonts. This is a bummer for the ones out there who love their expressiveness and simplicity. The only way of rendering this glyphs on a PDF document, is by embedding them as images. React-pdf makes this task simple by enabling you to use a CDN from where to download emoji images. All you have to do is setup a valid URL (we recommend using [Twemoji](https://github.com/twitter/twemoji) for this task), and react-pdf will take care of the rest: ```jsx import { Font } from '@react-pdf/renderer'; Font.registerEmojiSource({ format: 'png', url: 'https://cdnjs.cloudflare.com/ajax/libs/twemoji/14.0.2/72x72/', }); ``` > **Protip:** react-pdf will need a internet connection to download emoji's images at render time, so bare that in mind when choosing to use this API ```jsx const styles = StyleSheet.create({ container: { height: 700, marginVertical: 70, marginHorizontal: "10%" }, text: { fontSize: 100, textAlign: 'center' } }); Font.registerEmojiSource({ format: 'png', url: 'https://cdnjs.cloudflare.com/ajax/libs/twemoji/14.0.2/72x72/', }); const MyDocument = () => ( 😀💩👻🙈 ); ReactPDF.render(); ``` [Open in Playground](/playground?example=emoji) --- # Hooks URL: /docs/v4/hooks ## usePDF `Web only` React-pdf now ships a hook called `usePDF` that enables accessing all PDF creation capabilities via a React hook API. This is great if you need more control over how the document gets rendered or how often it's updated. ### Usage ```js const [instance, update] = usePDF({ document }); ``` ### Parameters | Prop name | Description | Default | | --------- | :---------------------: | ----------- | | document | Document's root element | _undefined_ | ### Instance object | Prop name | Description | Default | | --------- | :---------------------------------------------------------: | ----------- | | url | Rendered document blog url. Null if loading or errored | _undefined_ | | blob | Rendered document blob instance. Null if loading or errored | _undefined_ | | loading | Loading state. It's true if current render is in place | _false_ | | error | Error message if rendering failed | _undefined_ | ### Update function Used to trigger a document re-render. By default, changing the document instance does not triggers a new PDF file creation. This is especially helpful when rendering a download button or something similar, where you might want to render the document right before the action gets triggered. The update function takes the new document and does not return anything. > For more information about how this hook is used please refer to the [Using the usePDF hook](/docs/v4/advanced/on-the-fly-rendering#using-the-usepdf-hook) section --- --- # Quick start guide URL: /docs/v4 ## 1. Install React and react-pdf Starting with react-pdf is extremely simple. npm yarn pnpm bun ```bash npm install @react-pdf/renderer --save ``` ```bash yarn add @react-pdf/renderer ``` ```bash pnpm add @react-pdf/renderer ``` ```bash bun add @react-pdf/renderer ``` Since a renderer simply implements _how elements render into something_, you still need to have React to make it work (and react-dom for client-side document generation). You can find instructions on how to do that [here](https://react.dev/learn/add-react-to-an-existing-project). ## 2. Create your PDF document This is where things start getting interesting. React-pdf exports a set of React primitives that enable you to render things into your document very easily. It also has an API for styling them, using CSS properties and Flexbox layout. Let's make the code speak for itself: ```jsx // import React from 'react'; // import { Page, Text, View, Document, StyleSheet } from '@react-pdf/renderer'; // Create styles const styles = StyleSheet.create({ page: { padding: 48, fontSize: 11, lineHeight: 1.6, color: '#3f3f46', }, header: { flexDirection: 'row', justifyContent: 'space-between', borderBottomWidth: 1, borderBottomColor: '#e4e4e7', paddingBottom: 12, }, title: { fontSize: 26, color: '#18181b', marginTop: 40, paddingBottom: 16, borderBottomWidth: 3, borderBottomColor: '#e0301e', }, paragraph: { marginTop: 20, }, }); // Create Document Component const MyDocument = () => ( Field Notes Issue 01 Documents, written in React Everything on this page is a component. View lays things out with flexbox, Text renders the copy, and StyleSheet keeps styling close to the CSS you already write. Edit any value above and the page redraws. No template language, no build step, just React. ); ReactPDF.render(); ``` [Open in Playground](/playground?example=quick-start) That's a single page holding a header row, a title and some copy, laid out with flexbox and styled with plain style objects. `Document`, `Page`, `View` and `Text` are not the only primitives you can use. Please refer to the Components or Examples sections for more information. ## 3. Choose where to render the document React-pdf enables you to render the document in two different environments: **web** and **server**. The process is essentially the same, but catered to needs of each environment. ### Save in a file ```jsx import ReactPDF from '@react-pdf/renderer'; ReactPDF.render(, `${__dirname}/example.pdf`); ``` ### Render to a stream ```jsx import ReactPDF from '@react-pdf/renderer'; ReactPDF.renderToStream(); ``` ### Render in DOM ```jsx import React from 'react'; import ReactDOM from 'react-dom'; import { PDFViewer } from '@react-pdf/renderer'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` ## 4. Have fun! Maybe the most important step — make use of all react-pdf capabilities to create beautiful and awesome documents! --- # MCP server URL: /docs/v4/mcp react-pdf.org hosts an [MCP](https://modelcontextprotocol.io) server so coding agents can search and read these docs instead of guessing from memory. It is public, needs no key, and exposes two tools: - `search_docs({ query })` — returns the best matching pages as `[{ url, title }]` - `read_doc({ url })` — returns one page as Markdown ## Connect Claude Code: ```bash claude mcp add --transport http react-pdf https://react-pdf.org/mcp ``` Cursor, in `.cursor/mcp.json`: ```json { "mcpServers": { "react-pdf": { "url": "https://react-pdf.org/mcp" } } } ``` Any other MCP client works the same way: point it at `https://react-pdf.org/mcp` over streamable HTTP. ## Without MCP The docs are also plain Markdown over HTTP, which is enough for most tools: - Append `.mdx` to any docs URL — `react-pdf.org/docs/v4/components/text.mdx` — to get that page's source. The **Copy Markdown** button next to every page title does the same thing. - [/llms.txt](/llms.txt) lists every page of the current version. - [/llms-full.txt](/llms-full.txt) is the whole documentation in a single file. --- # Node API URL: /docs/v4/node ## renderToFile Helper function to render a PDF into a file. ### Usage ```js const MyDocument = () => ( React-pdf ); await renderToFile(, `${__dirname}/my-doc.pdf`); ``` ### Arguments | Prop name | Description | Default | | --------- | :-------------------------------------------------: | ----------- | | document | Document's root element to be rendered | _undefined_ | | path | File system path where the document will be created | _undefined_ | | callback | Function to be called after rendering is finished | _undefined_ | ## renderToString Helper function to render a PDF into a string. ### Usage ```js const MyDocument = () => ( React-pdf ); const value = await renderToString(); ``` ### Arguments | Prop name | Description | Default | | --------- | :------------------------------------: | ----------- | | document | Document's root element to be rendered | _undefined_ | ### Returns String representation of PDF document ## renderToBuffer Helper function to render a PDF into a Node Buffer. ### Usage ```js const MyDocument = () => ( React-pdf ); const buffer = await renderToBuffer(); ``` ### Arguments | Prop name | Description | Default | | --------- | :------------------------------------: | ----------- | | document | Document's root element to be rendered | _undefined_ | ### Returns Buffer representation of PDF document ## renderToStream Helper function to render a PDF into a Node Stream. ### Usage ```js const MyDocument = () => ( React-pdf ); const stream = await renderToStream(); ``` ### Arguments | Prop name | Description | Default | | --------- | :------------------------------------: | ----------- | | document | Document's root element to be rendered | _undefined_ | ### Returns PDF document Stream --- # Styling URL: /docs/v4/styling Because a document without styles would be very boring, react-pdf ships a powerful styling solution using CSS and Flexbox. ## StyleSheet API React-pdf also sticks with the primitives specs when it comes to styling. ### StyleSheet.create() Creates a stylesheet from a plain object of CSS definitions. Each key becomes a style you can hand to a component through its `style` prop. ```jsx import { StyleSheet, Page, Text } from '@react-pdf/renderer'; const styles = StyleSheet.create({ page: { padding: 40 }, title: { fontSize: 18, marginBottom: 12 }, }); const Report = () => ( Quarterly report ); ``` ### Inline styling There's no need to call `StyleSheet.create` in order to style components. A plain JS object works just as well. ```jsx Quarterly report ``` ### Mixing both solutions The `style` prop also accepts an array. Entries are merged left to right, and falsy ones are skipped, which is what you want for styles that depend on props. ```jsx const Badge = ({ overdue }) => ( {overdue ? 'Overdue' : 'Paid'} ); ``` --- ## Media queries There may be times in which you'll need to apply different styles based on the document context. For that, we provide media-queries support (just as you would do it for the web!). You can query based on both `width` and `height` (min and max), and also `orientation`: ```jsx const styles = StyleSheet.create({ row: { flexDirection: 'row', '@media max-width: 400': { flexDirection: 'column' }, '@media orientation: landscape': { gap: 20 }, }, }); ``` The example below renders the same component on a 500pt page and a 300pt one: ```jsx const styles = StyleSheet.create({ body: { padding: 35, }, content: { padding: 20, '@media max-width: 400': { flexDirection: 'column', }, '@media min-width: 400': { flexDirection: 'row', }, }, block: { height: 150, width: 150, backgroundColor: 'red', }, }); const MediaComponent = () => ( ); const doc = ( ); ReactPDF.render(doc); ``` [Open in Playground](/playground?example=media-queries) --- ## Valid units | Unit | Meaning | | ---- | ----------------------------------------------------- | | `pt` | Points. The default, based on the 72 dpi PDF document | | `in` | Inches | | `mm` | Millimeters | | `cm` | Centimeters | | `%` | Percentage of the parent | | `vw` | Percentage of the page width | | `vh` | Percentage of the page height | --- ## Valid CSS properties ### Flexbox - flex - flexDirection _(row · column · row-reverse · column-reverse)_ - flexWrap _(nowrap · wrap · wrap-reverse)_ - flexFlow - flexGrow - flexShrink - flexBasis - alignContent - alignItems - alignSelf - justifyContent - gap - rowGap - columnGap ### Layout - display _(flex · none)_ - position _(static · relative · absolute)_ - top - right - bottom - left - zIndex - overflow _(hidden)_ - aspectRatio - float _(left · right · none)_ - clear _(left · right · both · none)_ - shapeOutside _(circle · ellipse · polygon · inset)_ ### Dimension - width - height - minWidth - minHeight - maxWidth - maxHeight ### Spacing - margin - marginHorizontal - marginVertical - marginTop - marginRight - marginBottom - marginLeft - padding - paddingHorizontal - paddingVertical - paddingTop - paddingRight - paddingBottom - paddingLeft ### Border - border - borderWidth - borderColor - borderStyle _(solid · dashed · dotted)_ - borderRadius - borderTop - borderTopWidth - borderTopColor - borderTopStyle - borderRight - borderRightWidth - borderRightColor - borderRightStyle - borderBottom - borderBottomWidth - borderBottomColor - borderBottomStyle - borderLeft - borderLeftWidth - borderLeftColor - borderLeftStyle - borderTopLeftRadius - borderTopRightRadius - borderBottomRightRadius - borderBottomLeftRadius ### Color - color - backgroundColor - opacity ### Text - fontFamily - fontSize - fontStyle _(normal · italic · oblique)_ - fontWeight - fontFeatureSettings - letterSpacing - lineHeight - textAlign _(left · center · right · justify)_ - textDecoration _(underline · line-through · none)_ - textDecorationColor - textDecorationStyle - textIndent - textOverflow _(ellipsis)_ - textTransform _(uppercase · lowercase · capitalize · upperfirst)_ - verticalAlign _(sub · super)_ - direction _(ltr · rtl)_ - maxLines ### Image - objectFit _(fill · contain · cover · scale-down · none)_ - objectPosition ### Transform - transform _(rotate · scale · translate · skew · matrix)_ - transformOrigin --- # Tailwind URL: /docs/v4/tailwind The `@react-pdf/tailwind` package converts a compatible subset of the Tailwind CSS class syntax into style objects that react-pdf understands. ## Installation ```bash npm install @react-pdf/tailwind ``` ## Usage ```jsx import { Document, Page, Text, View } from '@react-pdf/renderer'; import { createTw } from '@react-pdf/tailwind'; // Apply your own styles on top of Tailwind defaults const tw = createTw({ fontFamily: { sans: ['Papyrus'], }, colors: { custom: '#bada55', }, }); const MyDocument = () => ( Section #1 Section #2 ); ``` The returned `tw` function takes a space-separated class string and returns a react-pdf `Style` object. Unknown classes are skipped with a console warning, emitted once per distinct class. ## createTw `createTw(config, options)` builds the `tw` function. `config` is a theme object merged into Tailwind's `defaultTheme`, following the Tailwind v4 theme shape — see [Tailwind's default theme](https://github.com/tailwindlabs/tailwindcss/blob/main/packages/tailwindcss/src/compat/default-theme.ts) for reference. ```js const tw = createTw( { fontFamily: { sans: ['Papyrus'], }, spacing: { verybig: '999rem', }, colors: { custom: '#bada55', }, }, { // Base font size in points. Defaults to 12. ptPerRem: 12, }, ); ``` Scales merge one level deep, so overriding a single key keeps the rest of the default scale — `spacing: { 4: '2rem' }` changes `p-4` while leaving `p-8` alone, and `colors: { gray: { 500: '#fff' } }` leaves the other grays intact. Replace a whole scale by overriding it with a non-object value. `fontFamily` is the exception: it comes from your config alone, neither merging with Tailwind's defaults nor falling back to them. react-pdf can only draw [fonts you have registered](/docs/v4/fonts), and Tailwind's stacks name web families like `-apple-system`, so resolving `font-sans` against them would throw at render time. Register a font, map it in the config, and `font-` works; without a config, `font-sans` / `font-serif` / `font-mono` warn as unsupported while `font-bold` and friends still resolve. ## Color opacity `bg-red-500/50` and friends work anywhere a color does — `bg-`, `text-`, `border-`, `decoration-` — including black, white, custom and arbitrary colors: ```js tw('bg-red-500/50'); // { backgroundColor: '#ef444480' } tw('text-black/25'); // { color: '#00000040' } tw('bg-[#bada55]/60'); // { backgroundColor: '#bada5599' } ``` A bare suffix is a percentage; a bracketed one is `0`–`1` unless it carries a `%`, so `/[0.55]` and `/[55%]` agree. `transparent`, `currentColor` and `inherit` name no channel to modulate and reject the suffix. ## Variants Breakpoint and orientation variants become react-pdf media queries, which resolve against the **page box** rather than a viewport: ```js tw('p-2 lg:p-4 landscape:p-6'); // { // padding: 6, // '@media min-width: 768': { padding: 12 }, // '@media orientation: landscape': { padding: 18 }, // } ``` | Variant | Becomes | | ------------------------------ | ----------------------- | | `sm:` `md:` `lg:` `xl:` `2xl:` | `@media min-width: N` | | `max-sm:` … `max-2xl:` | `@media max-width: N` | | `min-[600px]:` `max-[40rem]:` | the width you give it | | `portrait:` `landscape:` | `@media orientation: …` | | stacked, e.g. `lg:portrait:` | both, joined with `and` | Tailwind v4 states its breakpoints in rem, so at the default `1rem = 12pt` they land at page scale: `sm` is 480pt, `md` 576pt, `lg` 768pt, `xl` 960pt. An A4 page is 595pt wide upright and 842pt on its side, so `md` matches portrait and `lg` matches landscape. Set `screens` in the config to choose your own. State variants — `hover:`, `focus:`, `dark:`, `group-*`, `peer-*` — describe something a printed page never enters, and are reported as unsupported rather than applied. Applying them would bake the hover style into the output. ## Notes - Supports the CSS properties that make sense in a PDF context and are supported by react-pdf — see [valid CSS properties](/docs/v4/styling#valid-css-properties). - Uses `pt` as the internal unit ([valid units](/docs/v4/styling#valid-units)), with `1rem = 12pt` by default. Change it with `ptPerRem`. - react-pdf uses [Yoga](https://yogalayout.dev/) for layout, so some defaults differ from the web — `flex-direction` defaults to `column`, for example. Add `flex-row` where you need it. - Line heights are emitted unitless, since react-pdf only supports unitless `lineHeight`. - `aspect-auto` and `line-clamp-none` warn as unsupported. react-pdf has no style value meaning "no aspect ratio" or "no clamp" — leaving the utility off is the reset. - Intrinsic sizing (`w-fit`, `h-min`, `max-w-max`, …), `max-w-none` / `max-h-none`, and lengths in units react-pdf can't parse (`max-w-prose` is `65ch`) warn as unsupported. Yoga has no equivalent, and passing the value through would throw while laying out the document. - `float-*` and `clear-*` map to react-pdf's [float support](/docs/v4/floats), which is newer and has rough edges: setting `lineHeight` on floated content breaks text wrap, and parents don't grow to contain their floats. --- # Math URL: /docs/v4/addons/math React-pdf supports rendering LaTeX mathematical expressions via the `@react-pdf/math` package. It converts LaTeX notation into vector graphics (SVG paths), so all glyphs are fully embedded in the PDF without external fonts or assets. ## Installation ```bash npm install @react-pdf/math ``` ## Usage ```jsx import { Document, Page, Text, View } from '@react-pdf/renderer'; import { Math } from '@react-pdf/math'; const MyDocument = () => ( {"x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}"} ); ``` ## Inline mode By default, expressions render in display mode (centered, larger). Set `inline` to render compact equations suitable for embedding alongside text: ```jsx The equation {"E = mc^2"} is famous. ``` ```jsx import { Math } from '@react-pdf/math'; const styles = StyleSheet.create({ page: { padding: 40, backgroundColor: '#fafafa', }, title: { fontSize: 18, fontWeight: 'bold', marginBottom: 4, color: '#1a1a1a', }, subtitle: { fontSize: 9, color: '#888', marginBottom: 20, }, card: { backgroundColor: 'white', borderRadius: 5, padding: 12, marginBottom: 8, borderWidth: 1, borderColor: '#e8e8e8', }, cardLabel: { fontSize: 8, color: '#999', marginBottom: 6, textTransform: 'uppercase', letterSpacing: 0.5, }, row: { flexDirection: 'row', gap: 8, marginBottom: 8, }, halfCard: { flex: 1, backgroundColor: 'white', borderRadius: 5, padding: 12, borderWidth: 1, borderColor: '#e8e8e8', }, inlineRow: { flexDirection: 'row', alignItems: 'center', }, inlineText: { fontSize: 10, color: '#333', }, footer: { marginTop: 'auto', paddingTop: 12, borderTopWidth: 1, borderTopColor: '#e8e8e8', flexDirection: 'row', justifyContent: 'space-between', }, footerText: { fontSize: 7, color: '#aaa', }, }); const doc = ( Mathematical Typesetting LaTeX expressions rendered as vector graphics via @react-pdf/math Quadratic Formula {'x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}'} Euler's Identity {'e^{i\\pi} + 1 = 0'} Limits {'\\lim_{x \\to 0} \\frac{\\sin x}{x} = 1'} Gaussian Integral {'\\int_{-\\infty}^{\\infty} e^{-x^2} dx = \\sqrt{\\pi}'} Basel Problem {'\\sum_{n=1}^{\\infty} \\frac{1}{n^2} = \\frac{\\pi^2}{6}'} Matrix Notation {'A = \\begin{pmatrix} a_{11} & a_{12} \\\\ a_{21} & a_{22} \\end{pmatrix}'} Binomial Theorem {'(x + y)^n = \\sum_{k=0}^{n} \\binom{n}{k} x^{n-k} y^k'} Maxwell's Equation (Faraday's Law) {'\\nabla \\times \\vec{E} = -\\frac{\\partial \\vec{B}}{\\partial t}'} Inline Usage The famous equation {'E = mc^2'} relates mass and energy. Generated with @react-pdf/math Powered by MathJax ); ReactPDF.render(doc); ``` [Open in Playground](/playground?example=math) ## Valid props | Prop name | Description | Type | Default | |-----------|:---------------------------------------------------------------------------:|-------------------:|------------:| | children | LaTeX math expression to render | _String_ | _undefined_ | | inline | Inline mode (compact) vs display mode (centered, larger) | _Boolean_ | _false_ | | width | Width of the rendered expression. Auto-calculated from aspect ratio if omitted | _Number_, _String_ | _undefined_ | | height | Height of the rendered expression. Defaults to 22 if omitted | _Number_, _String_ | _22_ | | color | Color of the math expression | _String_ | _"black"_ | | debug | Enables debug mode showing a border around the expression | _Boolean_ | _false_ | ## Supported LaTeX features All standard LaTeX math features supported by MathJax are available, including: - Fractions, roots, and arithmetic operators - Greek and Hebrew letters - Summations, products, and integrals - Limits and derivatives - Matrices and arrays - Binomial coefficients - Trigonometric functions - Accents and decorations - Piecewise functions and aligned equations --- # Mermaid URL: /docs/v4/addons/mermaid React-pdf renders [Mermaid](https://mermaid.js.org/) diagrams via the `@react-pdf/mermaid` package. Definitions are turned into vector graphics at layout time, so flowcharts, sequence diagrams and the rest are drawn as real PDF shapes and text rather than embedded as a bitmap. ## Installation ```bash npm install @react-pdf/mermaid ``` ## Usage ```jsx import { Document, Page, View } from '@react-pdf/renderer'; import { Mermaid } from '@react-pdf/mermaid'; const MyDocument = () => ( {`graph TD A[Start] --> B{Decision} B -->|Yes| C[Ship it] B -->|No| D[Back to the drawing board]`} ); ``` Both `width` and `height` are optional. Left out, the diagram takes the size of its own viewBox; given one of the two, the other follows the aspect ratio. ## Supported diagrams | Diagram | Keyword | |---------|---------| | Flowchart | `graph TD`, `graph LR` | | Sequence | `sequenceDiagram` | | State | `stateDiagram-v2` | | Class | `classDiagram` | | Entity relationship | `erDiagram` | | XY chart | `xychart-beta` | ```jsx {`classDiagram Document <|-- Page Page <|-- View View <|-- Text`} ``` ## Colors Colors can be set one by one, or picked up from a built-in theme: ```jsx {`graph LR A --> B --> C`} ``` Individual color props override the theme, so a theme can be used as a starting point and adjusted from there: ```jsx {`graph LR A --> B --> C`} ``` Available themes are `tokyo-night`, `tokyo-night-storm`, `tokyo-night-light`, `catppuccin-mocha`, `catppuccin-latte`, `nord`, `nord-light`, `dracula`, `github-dark`, `github-light`, `solarized-dark`, `solarized-light`, `one-dark`, `zinc-dark` and `zinc-light`. ## Valid props | Prop name | Description | Type | Default | |-----------|:--------------------------------------------------------------------------:|-------------------:|------------:| | children | Mermaid diagram definition | _String_ | _undefined_ | | width | Width of the rendered diagram. Derived from the viewBox aspect ratio if omitted | _Number_, _String_ | _undefined_ | | height | Height of the rendered diagram. Derived from the viewBox aspect ratio if omitted | _Number_, _String_ | _undefined_ | | theme | Built-in theme name | _String_ | _undefined_ | | color | Foreground and text color | _String_ | _"black"_ | | bg | Background color of the diagram | _String_ | _undefined_ | | accent | Accent color for arrowheads and highlights | _String_ | _undefined_ | | line | Edge and connector stroke color | _String_ | _undefined_ | | muted | Secondary text and label color | _String_ | _undefined_ | | surface | Node fill color | _String_ | _undefined_ | | border | Node stroke color | _String_ | _undefined_ | | transparent | Use a transparent background | _Boolean_ | _false_ | | debug | Enables debug mode showing a border around the diagram | _Boolean_ | _false_ | --- # Debugging URL: /docs/v4/advanced/debugging React-pdf ships a built-in debugging system you can use whenever you have doubts about how elements are being laid out on the page. All you have to do is to set the `debug` prop to `true` on any valid primitive (except _Document_) and re-render the document to see the result on the screen. ```jsx const styles = StyleSheet.create({ container: { height: 300, width: 400, margin: 20, paddingVertical: 20, }, }); const MyDocument = () => ( ); ReactPDF.render(); ``` [Open in Playground](/playground?example=debugging) --- # Document Navigation URL: /docs/v4/advanced/document-navigation There are two main ways to make a document navigable: ## Destinations `v2.0.0` Destinations are the simplest form of navigation. They allow to create interactive links that take the user directly to the defined place within the document. A destination can be created by setting the `id` prop to a _String_ on any supported element ([see more](/docs/v4/components)). After that, the destination can be linked to by setting the `src` prop on the `` element to the same _String_, but with the leading hash (`#`) symbol: ```js import { Document, Link, Page, Text } from '@react-pdf/renderer' const doc = () => ( // Notice the hash symbol Click me to get to the footnote // Other content here // No hash symbol You are here because you clicked the link above ); ``` ## Bookmarks `v2.2.0` Bookmarks allow the user to navigate interactively from one part of the document to another. They form a tree-structured hierarchy of items, which serve as a visual table of contents to display the document’s structure to the user. A bookmark can be defined by the `bookmark` prop on any of the supported components ([see more](/docs/v4/components)), and can take the form of either a _String_ or a _Bookmark_ type ```js import { Document, Page, Text } from '@react-pdf/renderer' const doc = () => ( {...} ); ``` The example above will create a table of content of 2 nested items: The parent will be the book's name, and the child the chapter's name. You can nest as many bookmarks as you want. Note that some older PDF viewers may not support bookmarks. ### Bookmark type Object that matches the following schema: | Value | Description | Type | |-----------------------|:-----------------------------------------------------------------------------------:|----------:| | title | Bookmark value | _String_ | | top _(Optional)_ | Y coodinate from the document top edge where user get's redirected. Defaults to 0 | _Number_ | | left _(Optional)_ | X coodinate from the document top edge where user get's redirected. Defaults to 0 | _Number_ | | zoom _(Optional)_ | Reader zoom value after clicking on the bookmark | _Number_ | | fit _(Optional)_ | Redirect user to the start of the page | _Boolean_ | | expanded _(Optional)_ | Viewer should expand tree node in table of contents (not supported in some viewers) | _Boolean_ | --- # Dynamic content URL: /docs/v4/advanced/dynamic-content With react-pdf, now it is possible to render dynamic text based on the context in which a certain element is being rendered. All you have to do is to pass a function to the `render` prop of the `` or `` component. The result will be rendered inside the text block as a child. ```jsx import { Document, Page } from '@react-pdf/renderer' const doc = () => ( ( `${pageNumber} / ${totalPages}` )} fixed /> ( pageNumber % 2 === 0 && ( I'm only visible in odd pages! ) )} /> ); ``` ## Available arguments | Name | Description | Type | | ---------------------- | :-----------------------------------------: | --------: | | pageNumber | Current page number | _Integer_ | | totalPages `Text only` | Total amount of pages in the final document | _Integer_ | | subPageNumber | Current subpage in the Page component | _Integer_ | | subPageTotalPages `Text only` | Total amount of pages in the Page component | _Integer_ | Bear in mind that the `render` function is called twice for `` elements: once for layout on the page wrapping process, and another one after it's know how many pages the document will have. > **Protip:** Use this API in conjunction with fixed elements to render page number indicators ```jsx const styles = StyleSheet.create({ page: { padding: 60 }, box: { width: '100%', marginBottom: 30, borderRadius: 5 }, pageNumbers: { position: 'absolute', bottom: 20, left: 0, right: 0, textAlign: 'center' }, }); const doc = ( ( `${pageNumber} / ${totalPages}` )} fixed /> ); ReactPDF.render(doc); ``` [Open in Playground](/playground?example=page-numbers) --- # Usage with Express.js URL: /docs/v4/advanced/express ```jsx import React from 'react'; import ReactPDF from '@react-pdf/renderer'; const pdfStream = await ReactPDF.renderToStream(); res.setHeader('Content-Type', 'application/pdf'); pdfStream.pipe(res); pdfStream.on('end', () => console.log('Done streaming, response sent.')); ``` --- # Hyphenation URL: /docs/v4/advanced/hyphenation Hyphenation refers to the automated process of breaking words between lines to create a better visual consistency across a text block. This is a complex problem. It involves knowing about the language of the text, available space, ligatures, among other things. React-pdf internally implements the [Knuth and Plass line breaking algorithm](http://www.eprg.org/G53DOC/pdfs/knuth-plass-breaking.pdf) that produces the minimum amount of lines without compromising text legibility. By default it's setup to hyphenate english words. ## Other languages Words are split with [@react-pdf/hyphenate](https://github.com/diegomura/react-pdf/tree/master/packages/hyphenate), a fast Liang hyphenation engine with an entry point per language, `en-us` being the default. To hyphenate another language, register its `syllables` function: ```jsx import { Font } from '@react-pdf/renderer'; import { syllables } from '@react-pdf/hyphenate/de'; Font.registerHyphenationCallback(syllables); ``` Every language shipped by [hyphen](https://github.com/ytiurin/hyphen) is available under the same name (`de`, `es`, `fr`, `ru`, `zh-latn-pinyin`, and 80+ more). Each language is its own entry point, so bundlers only include the patterns you actually import. ## Custom callback If you need more fine-grained control over how words break, you can pass your own callback and handle all that logic by yourself: ```jsx import { Font } from '@react-pdf/renderer' const hyphenationCallback = (word) => { // Return word syllables in an array } Font.registerHyphenationCallback(hyphenationCallback); ``` > **Protip:** If you don't want to hyphenate words at all, just provide a callback that returns the same words it receives. More information [here](/docs/v4/fonts#registerhyphenationcallback) ```jsx // Register hyphenation callback. // In this example, we enable words to break in half Font.registerHyphenationCallback(word => { const middle = Math.floor(word.length / 2); const parts = word.length === 1 ? [word] : [word.substr(0, middle), word.substr(middle)]; // Check console to see words parts console.log(word, parts); return parts; }); const styles = StyleSheet.create({ container: { padding: 50 }, text: { textAlign: 'justify' } }); const MyDocument = () => ( Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vulputate erat id sagittis porta. Phasellus ut diam sit amet mi sagittis faucibus sed in purus. Etiam pretium et lacus sit amet fringilla. Aenean hendrerit volutpat nulla, at facilisis ante bibendum non. Integer ut nulla nulla. Etiam ornare interdum iaculis. Sed lectus nisl, faucibus vitae posuere ut, lobortis in lectus. Donec ac magna in libero tincidunt volutpat. Donec ut varius quam. Duis ornare justo quis sapien bibendum cursus. ); ReactPDF.render(); ``` [Open in Playground](/playground?example=hyphenation-callback) --- # Advanced URL: /docs/v4/advanced - [Page wrapping](/docs/v4/advanced/page-wrapping) - [Document Navigation](/docs/v4/advanced/document-navigation) - [On the fly rendering](/docs/v4/advanced/on-the-fly-rendering) - [Orphan & widow protection](/docs/v4/advanced/orphans-and-widows) - [Dynamic content](/docs/v4/advanced/dynamic-content) - [Debugging](/docs/v4/advanced/debugging) - [Hyphenation](/docs/v4/advanced/hyphenation) - [Usage with Express.js](/docs/v4/advanced/express) --- # On the fly rendering URL: /docs/v4/advanced/on-the-fly-rendering There are some cases in which you may need to generate a document without showing it on screen. For those scenarios, react-pdf provides three different solutions: ## Download link Is it possible that what you need is just a "Download" button. If that's the case, you can use `` to easily create and download your document. ```jsx import { PDFDownloadLink, Document, Page } from '@react-pdf/renderer'; const MyDoc = () => ( // My document data ); const App = () => (
} fileName="somename.pdf"> {({ blob, url, loading, error }) => loading ? 'Loading document...' : 'Download now!' }
); ``` > **Protip:** You still have access to blob's data if you need it. ## Access blob data However, react-pdf does not stick to just download the document but also enables direct access to the document's blob data for any other possible use case. All you have to do is make use of ``. ```jsx import { BlobProvider, Document, Page } from '@react-pdf/renderer'; const MyDoc = ( // My document data ); const App = () => (
{({ blob, url, loading, error }) => { // Do whatever you need with blob here return
There's something going on on the fly
; }}
); ``` You can also obtain the blob data imperatively, which may be useful if you are using react-pdf on a non-React frontend (web only). ```jsx import { pdf, Document, Page } from '@react-pdf/renderer'; const MyDoc = ( // My document data ); const blob = pdf(MyDoc).toBlob(); ``` ## Using the usePDF hook React-pdf now ships a hook API that will give you direct access to the document data (such as blob or url state) as well as with an _update_ function to trigger document re-rendering. Since document re-computation can be an expensive operation, this hook is perfect solution for those cases in where you need a fine control over when this happens. ```js import { usePDF, Document, Page } from '@react-pdf/renderer'; const MyDoc = ( // My document data ); const App = () => { const [instance, updateInstance] = usePDF({ document: MyDoc }); if (instance.loading) return
Loading ...
; if (instance.error) return
Something went wrong: {instance.error}
; return ( Download ); } ``` > **Protip:** You still have access to blob's data inside `instance.blob` if you need it --- # Orphan & widow protection URL: /docs/v4/advanced/orphans-and-widows When you layout text, orphans and widows can make the difference between a _good_ document and a _great_ one. That's why react-pdf has a built-in orphan and widow protection that you can use right out of the box. But react-pdf does not reserve this protection just for text. You can adjust this protection to your convenience by just setting some props to **any react-pdf primitive**: | Prop name | Description | Type | Default | | --------------------- | :------------------------------------------------------------------------------------------------------------------: | --------: | ------: | | minPresenceAhead | Hint that no page wrapping should occur between all sibling elements following the element within _n_ points | _Integer_ | 0 | | orphans _(text only)_ | Specifies the minimum number of lines in a text element that must be shown at the bottom of a page or its container. | _Integer_ | 2 | | widows _(text only)_ | Specifies the minimum number of lines in a text element that must be shown at the top of a page or its container. | _Integer_ | 2 | > **Protip:** You can use this API to ensure that headings do not get rendered at the bottom of a page ```jsx const styles = StyleSheet.create({ page: { padding: 60 }, text: { margin: 12, fontSize: 14, textAlign: 'justify', fontFamily: 'Times-Roman' }, }); const doc = ( Widows example. Try changing prop value En un lugar de la Mancha, de cuyo nombre no quiero acordarme, no ha mucho tiempo que vivía un hidalgo de los de lanza en astillero, adarga antigua, rocín flaco y galgo corredor. Una olla de algo más vaca que carnero, salpicón las más noches, duelos y quebrantos los sábados, lentejas los viernes, algún palomino de añadidura los domingos, consumían las tres partes de su hacienda. El resto della concluían sayo de velarte, calzas de velludo para las fiestas con sus pantuflos de lo mismo, los días de entre semana se honraba con su vellori de lo más fino. Tenía en su casa una ama que pasaba de los cuarenta, y una sobrina que no llegaba a los veinte, y un mozo de campo y plaza, que así ensillaba el rocín como tomaba la podadera. Frisaba la edad de nuestro hidalgo con los cincuenta años, era de complexión recia, seco de carnes, enjuto de rostro; gran madrugador y amigo de la caza. Quieren decir que tenía el sobrenombre de Quijada o Quesada (que en esto hay alguna diferencia en los autores que deste caso escriben), aunque por conjeturas verosímiles se deja entender que se llama Quijana; pero esto importa poco a nuestro cuento; basta que en la narración dél no se salga un punto de la verdad Orphans example. Try changing prop value En un lugar de la Mancha, de cuyo nombre no quiero acordarme, no ha mucho tiempo que vivía un hidalgo de los de lanza en astillero, adarga antigua, rocín flaco y galgo corredor. Una olla de algo más vaca que carnero, salpicón las más noches, duelos y quebrantos los sábados, lentejas los viernes, algún palomino de añadidura los domingos, consumían las tres partes de su hacienda. El resto della concluían sayo de velarte, calzas de velludo para las fiestas con sus pantuflos de lo mismo, los días de entre semana se honraba con su vellori de lo más fino. Tenía en su casa una ama que pasaba de los cuarenta, y una sobrina que no llegaba a los veinte, y un mozo de campo y plaza, que así ensillaba el rocín como tomaba la podadera. Frisaba la edad de nuestro hidalgo con los cincuenta años, era de complexión recia, seco de carnes, enjuto de rostro; gran madrugador y amigo de la caza. Quieren decir que tenía el sobrenombre de Quijada o Quesada (que en esto hay alguna diferencia en los autores que deste caso escriben), aunque por conjeturas verosímiles se deja entender que se llama Quijana; pero esto importa poco a nuestro cuento; basta que en la narración dél no se salga un punto de la verdad ); ReactPDF.render(doc); ``` [Open in Playground](/playground?example=orphans-and-widows) --- # Page wrapping URL: /docs/v4/advanced/page-wrapping Semantically, the `` component represents a single page in the rendered document. However, there are scenarios in which you would expect to have page breaks whenever the page contents exceed their limits, specially when handling big chunks of text. After all, PDFs are paged documents. React-pdf has a built-in wrapping engine that is enabled by default, so you can start creating paged documents right out of the box. If that's not what you need, you can disable this very easily by doing: ```jsx import { Document, Page } from '@react-pdf/renderer' const doc = () => ( // something pretty here ); ``` ```jsx const HR = () => ( ); const ChapterHeading = ({ number, children, ...props }) => ( {number} {children} ); const Quixote = () => ( Don Quijote de la Mancha Don Quijote de la Mancha
Miguel de Cervantes
Que trata de la condición y ejercicio del famoso hidalgo D. Quijote de la Mancha En un lugar de la Mancha, de cuyo nombre no quiero acordarme, no ha mucho tiempo que vivía un hidalgo de los de lanza en astillero, adarga antigua, rocín flaco y galgo corredor. Una olla de algo más vaca que carnero, salpicón las más noches, duelos y quebrantos los sábados, lentejas los viernes, algún palomino de añadidura los domingos, consumían las tres partes de su hacienda. El resto della concluían sayo de velarte, calzas de velludo para las fiestas con sus pantuflos de lo mismo, los días de entre semana se honraba con su vellori de lo más fino. Tenía en su casa una ama que pasaba de los cuarenta, y una sobrina que no llegaba a los veinte, y un mozo de campo y plaza, que así ensillaba el rocín como tomaba la podadera. Frisaba la edad de nuestro hidalgo con los cincuenta años, era de complexión recia, seco de carnes, enjuto de rostro; gran madrugador y amigo de la caza. Quieren decir que tenía el sobrenombre de Quijada o Quesada (que en esto hay alguna diferencia en los autores que deste caso escriben), aunque por conjeturas verosímiles se deja entender que se llama Quijana; pero esto importa poco a nuestro cuento; basta que en la narración dél no se salga un punto de la verdad. Es, pues, de saber, que este sobredicho hidalgo, los ratos que estaba ocioso (que eran los más del año) se daba a leer libros de caballerías con tanta afición y gusto, que olvidó casi de todo punto el ejercicio de la caza, y aun la administración de su hacienda; y llegó a tanto su curiosidad y desatino en esto, que vendió muchas hanegas de tierra de sembradura, para comprar libros de caballerías en que leer; y así llevó a su casa todos cuantos pudo haber dellos; y de todos ningunos le parecían tan bien como los que compuso el famoso Feliciano de Silva: porque la claridad de su prosa, y aquellas intrincadas razones suyas, le parecían de perlas; y más cuando llegaba a leer aquellos requiebros y cartas de desafío, donde en muchas partes hallaba escrito: la razón de la sinrazón que a mi razón se hace, de tal manera mi razón enflaquece, que con razón me quejo de la vuestra fermosura, y también cuando leía: los altos cielos que de vuestra divinidad divinamente con las estrellas se fortifican, y os hacen merecedora del merecimiento que merece la vuestra grandeza. "La razón de la sinrazón que a mi razón se hace, de tal manera mi razón enflaquece, que con razón me quejo de la vuestra fermosura." Con estas y semejantes razones perdía el pobre caballero el juicio, y desvelábase por entenderlas, y desentrañarles el sentido, que no se lo sacara, ni las entendiera el mismo Aristóteles, si resucitara para sólo ello. No estaba muy bien con las heridas que don Belianís daba y recibía, porque se imaginaba que por grandes maestros que le hubiesen curado, no dejaría de tener el rostro y todo el cuerpo lleno de cicatrices y señales; pero con todo alababa en su autor aquel acabar su libro con la promesa de aquella inacabable aventura, y muchas veces le vino deseo de tomar la pluma, y darle fin al pie de la letra como allí se promete; y sin duda alguna lo hiciera, y aun saliera con ello, si otros mayores y continuos pensamientos no se lo estorbaran. En resolución, él se enfrascó tanto en su lectura, que se le pasaban las noches leyendo de claro en claro, y los días de turbio en turbio, y así, del poco dormir y del mucho leer, se le secó el cerebro, de manera que vino a perder el juicio. Llenósele la fantasía de todo aquello que leía en los libros, así de encantamientos, como de pendencias, batallas, desafíos, heridas, requiebros, amores, tormentas y disparates imposibles, y asentósele de tal modo en la imaginación que era verdad toda aquella máquina de aquellas soñadas invenciones que leía, que para él no había otra historia más cierta en el mundo. Que trata de la primera salida que de su tierra hizo el ingenioso Don Quijote Hechas, pues, estas prevenciones, no quiso aguardar más tiempo a poner en efeto su pensamiento, apretándole a ello la falta que él pensaba que hacía en el mundo su tardanza, según eran los agravios que pensaba deshacer, tuertos que enderezar, sinrazones que emendar y abusos que mejorar y deudas que satisfacer. Y así, sin dar parte a persona alguna de su intención y sin que nadie le viese, una mañana, antes del día, que era uno de los calurosos del mes de Julio, se armó de todas sus armas, subió sobre Rocinante, puesta su mal compuesta celada, embrazó su adarga, tomó su lanza y por la puerta falsa de un corral salió al campo con grandísimo contento y alborozo de ver con cuánta facilidad había dado principio a su buen deseo. Yendo, pues, caminando nuestro flamante aventurero, iba hablando consigo mesmo, y diciendo: —¿Quién duda, sino que en los venideros tiempos, cuando salga a luz la verdadera historia de mis famosos hechos, que el sabio que los escribiere no ponga, cuando llegue a contar esta mi primera salida tan de mañana, desta manera?: Apenas había el rubicundo Apolo tendido por la faz de la ancha y espaciosa tierra las doradas hebras de sus hermosos cabellos, y apenas los pequeños y pintados pajarillos con sus arpadas lenguas habían saludado con dulce y meliflua armonía la venida de la rosada Aurora, que, dejando la blanda cama del celoso marido, por las puertas y balcones del manchego horizonte a los mortales se mostraba, cuando el famoso caballero don Quijote de la Mancha, dejando las ociosas plumas, subió sobre su famoso caballo Rocinante y comenzó a caminar por el antiguo y conocido Campo de Montiel. Casi todo aquel día caminó sin acontecerle cosa que de contar fuese, de lo cual se desesperaba, porque quisiera topar luego luego con quien hacer experiencia del valor de su fuerte brazo. Autores hay que dicen que la primera aventura que le avino fue la del Puerto Lápice, otros dicen que la de los molinos de viento; pero lo que yo he podido averiguar en este caso, y lo que he hallado escrito en los anales de la Mancha, es que él anduvo todo aquel día, y, al anochecer, su rocín y él se hallaron cansados y muertos de hambre, y que, mirando a todas partes por ver si descubriría algún castillo o alguna majada de pastores donde recogerse y adonde pudiese remediar su mucha hambre y necesidad, vio, no lejos del camino por donde iba, una venta, que fue como si viera una estrella que, no a los portales, sino a los alcázares de su redención le encaminaba. Diose priesa a caminar, y llegó a ella a tiempo que anochecía. ( `${pageNumber} / ${totalPages}` )} fixed />
); Font.register({ family: 'Oswald', src: 'https://fonts.gstatic.com/s/oswald/v13/Y_TKV6o8WovbUd3m_X9aAA.ttf' }); const styles = StyleSheet.create({ titleBlock: { alignItems: 'center', marginBottom: 8, }, title: { fontSize: 24, fontFamily: 'Oswald', textAlign: 'center', color: '#2c1810', letterSpacing: 2, textTransform: 'uppercase', }, hr: { borderBottomWidth: 1, borderBottomColor: '#8B4513', width: 60, marginVertical: 16, alignSelf: 'center', }, author: { fontSize: 13, textAlign: 'center', color: '#8B4513', fontFamily: 'Times-Roman', fontStyle: 'italic', }, body: { paddingTop: 50, paddingBottom: 65, paddingHorizontal: 65, }, header: { fontSize: 8, marginBottom: 24, textAlign: 'center', color: '#999', letterSpacing: 3, textTransform: 'uppercase', }, chapterHeading: { alignItems: 'center', marginBottom: 20, paddingTop: 20, }, chapterNumber: { fontSize: 36, fontFamily: 'Oswald', color: '#8B4513', marginBottom: 8, }, chapterRule: { borderBottomWidth: 0.5, borderBottomColor: '#8B4513', width: 40, marginVertical: 8, }, chapterTitle: { fontSize: 14, fontFamily: 'Times-Roman', fontStyle: 'italic', textAlign: 'center', color: '#555', maxWidth: 320, lineHeight: 1.6, }, text: { marginBottom: 10, fontSize: 11, textAlign: 'justify', fontFamily: 'Times-Roman', lineHeight: 1.7, color: '#333', }, pullQuote: { marginVertical: 16, marginHorizontal: 30, paddingLeft: 16, borderLeftWidth: 2, borderLeftColor: '#8B4513', }, pullQuoteText: { fontSize: 12, fontFamily: 'Times-Roman', fontStyle: 'italic', lineHeight: 1.7, color: '#555', }, chapterImage: { marginVertical: 16, marginHorizontal: 60, }, pageNumber: { position: 'absolute', fontSize: 9, bottom: 30, left: 0, right: 0, textAlign: 'center', color: '#999', }, }); ReactPDF.render(); ``` [Open in Playground](/playground?example=page-wrap) ## Breakable vs. unbreakable components We can identify two different types of components based on how they wrap: - `Breakable components` try to fill up the remaining space before jumping into a new page. By default, this group is composed by _View_, _Text_ and _Link_ components - `Unbreakable components` are indivisible, therefore if there isn't enough space for them they just get rendered in the following page. This group is composed by _Image_, _Svg_, _Canvas_ and _Note_. ```jsx const red = '#e82200'; const deep = '#8d1602'; const sand = '#c9c2b6'; const ink = '#3e3e3e'; const styles = StyleSheet.create({ page: { padding: 24, fontSize: 11, color: ink }, label: { fontFamily: 'Helvetica-Bold', fontSize: 8.5, letterSpacing: 1.2 }, intro: { fontSize: 11, lineHeight: 1.5, marginTop: 7, marginBottom: 16 }, columns: { flexDirection: 'row', justifyContent: 'space-between' }, caption: { fontSize: 8, letterSpacing: 1, marginBottom: 5 }, note: { fontSize: 8.5, lineHeight: 1.4, marginBottom: 6, color: deep }, band: { borderWidth: 0.75, borderColor: red }, mark: { fontSize: 9 }, row: { flexDirection: 'row', alignItems: 'center', height: 24, paddingHorizontal: 6, borderBottomWidth: 0.5, borderColor: sand, }, index: { fontFamily: 'Courier-Bold', color: red, marginRight: 7 }, }); const rows = Array.from({ length: 14 }, (_, i) => i + 1); const hairline = { width: 100, height: 0.5, fill: 'white', fillOpacity: 0.3 }; const doc = ( REACHING THE PAGE EDGE Both blocks below are taller than the room left for them. The View is breakable, the Svg is not. BREAKABLE VIEW Cut at the edge, resumed overleaf. {rows.map((n) => ( {String(n).padStart(2, '0')} table row ))} UNBREAKABLE SVG Cannot be cut, so none of it stays. {rows.map((n) => ( ))} ONE PIECE ); ReactPDF.render(doc); ``` [Open in Playground](/playground?example=breakable-unbreakable) ## Disabling component wrapping React-pdf also enables you to transform _breakable_ elements into their opposite, forcing them to always render in a new page. This can be done by simply setting the prop `wrap={false}` to any valid component: ```jsx import { Document, Page, View } from '@react-pdf/renderer' const doc = () => ( // fancy things here ); ``` Now, if the `` component happens to be at the bottom of the page without enough space, it will be rendered in a new page as it would be _unbreakable_. ```jsx const red = '#e82200'; const deep = '#8d1602'; const sand = '#c9c2b6'; const ink = '#3e3e3e'; const styles = StyleSheet.create({ page: { padding: 24, fontSize: 11, color: ink }, label: { fontFamily: 'Helvetica-Bold', fontSize: 8.5, letterSpacing: 1.2 }, intro: { fontSize: 11, lineHeight: 1.5, marginTop: 7, marginBottom: 16 }, caption: { fontSize: 8, letterSpacing: 1, marginBottom: 5 }, note: { fontSize: 8.5, lineHeight: 1.4, marginBottom: 6, color: deep }, band: { width: 118, borderWidth: 0.75, borderColor: red }, row: { flexDirection: 'row', alignItems: 'center', height: 24, paddingHorizontal: 6, borderBottomWidth: 0.5, borderColor: sand, }, index: { fontFamily: 'Courier-Bold', color: red, marginRight: 7 }, }); const rows = Array.from({ length: 14 }, (_, i) => i + 1); const doc = ( THE SAME BAND, MADE UNBREAKABLE This is the block that split down the middle in the previous example. With wrap turned off it moves the way an Image would. BREAKABLE VIEW — WRAP DISABLED Most of them fitted here. None stayed. {rows.map((n) => ( {String(n).padStart(2, '0')} table row ))} ); ReactPDF.render(doc); ``` [Open in Playground](/playground?example=disable-wrapping) ## Page breaks Page breaks are useful for separating concerns inside the document, or ensuring that a certain element will always show up on the top of the page. Adding page breaks in react-pdf is very simple: all you have to do is add the `break` prop to any primitive. This will force the wrapping algorithm to start a new page when rendering that element. ```jsx import { Document, Page, Text } from '@react-pdf/renderer' const doc = () => ( // fancy things here ); ``` ```jsx const red = '#e82200'; const deep = '#8d1602'; const sand = '#c9c2b6'; const ink = '#3e3e3e'; const styles = StyleSheet.create({ page: { padding: 24, fontSize: 11, color: ink }, label: { fontFamily: 'Helvetica-Bold', fontSize: 8.5, letterSpacing: 1.2 }, rule: { borderBottomWidth: 1, borderColor: sand, marginVertical: 8 }, heading: { fontFamily: 'Helvetica-Bold', fontSize: 19, letterSpacing: -0.4 }, body: { fontSize: 11, lineHeight: 1.6, marginTop: 10 }, note: { fontSize: 8.5, lineHeight: 1.4, marginTop: 22, color: deep }, }); const Chapter = ({ tone, number, title, children, ...props }) => ( CHAPTER {number} {title} {children} ); const doc = ( A chapter this short leaves most of the page unused, and nothing in it forces a break. Anything that followed would simply carry on below. Room to spare — and the next chapter takes a fresh page anyway. The break prop starts a new page before this chapter is laid out, so it opens at the top of one however much room was left on the page before. ); ReactPDF.render(doc); ``` [Open in Playground](/playground?example=page-breaks) ## Fixed components There is still another scenario we didn't talk about yet: what if you want to wrap pages but also be able to render a component on _all_ pages? This is where the `fixed` prop comes into play. ```jsx import { Document, Page, View } from '@react-pdf/renderer' const doc = () => ( // fancy things here ); ``` Just by that, the `` component will be placed repeatedly throughout all pages. > **Protip:** This feature can be very handy for creating nice headers, footers or page numbers, among other use cases. You can even absolutely position fixed elements on your page to create more complex layouts! ```jsx const red = '#e82200'; const deep = '#8d1602'; const sand = '#c9c2b6'; const ink = '#3e3e3e'; const styles = StyleSheet.create({ page: { padding: 24, paddingBottom: 44, fontSize: 11, color: ink }, header: { flexDirection: 'row', justifyContent: 'space-between', alignItems: 'baseline', borderBottomWidth: 1.5, borderColor: red, paddingBottom: 5, marginBottom: 12, }, brand: { fontFamily: 'Helvetica-Bold', fontSize: 15, letterSpacing: -0.4 }, small: { fontSize: 8, letterSpacing: 1.2, color: deep }, row: { flexDirection: 'row', alignItems: 'center', height: 24, paddingHorizontal: 6, borderBottomWidth: 0.5, borderColor: sand, }, index: { fontFamily: 'Courier-Bold', color: red, marginRight: 7 }, footer: { position: 'absolute', bottom: 24, left: 24, right: 24, fontSize: 8, letterSpacing: 1.2, color: deep, textAlign: 'center', }, }); const rows = Array.from({ length: 20 }, (_, i) => i + 1); const doc = ( Field manual REV 4 {rows.map((n) => ( {String(n).padStart(2, '0')} inspection point ))} `PAGE ${pageNumber} OF ${totalPages}` } fixed /> ); ReactPDF.render(doc); ``` [Open in Playground](/playground?example=fixed-components) --- # BlobProvider URL: /docs/v4/components/blob-provider Easy and declarative way of getting document's blob data without showing it on screen. Refer to [on the fly rendering](/docs/v4/advanced/on-the-fly-rendering) for more information. ```jsx import { BlobProvider, Document, Page, Text } from '@react-pdf/renderer'; const invoice = ( Invoice #42 ); const App = () => ( {({ url, loading }) => loading ? Rendering... : Open PDF } ); ``` ## Valid props | Prop name | Description | Type | Default | |-----------|:----------------------------------------------------------------:|-----------:|------------:| | document | PDF document implementation | _Document_ | _undefined_ | | children | Render prop with blob, url, error and loading state as arguments | _Function_ | _undefined_ | --- # Canvas URL: /docs/v4/components/canvas A React component for freely drawing any content on the page. ```jsx import { Canvas } from '@react-pdf/renderer'; const Bar = () => ( painter.rect(0, 0, availableWidth * 0.6, availableHeight).fill('tomato') } /> ); ``` ## Valid props | Prop name | Description | Type | Default | |-----------|:---------------------------------------------------------------------------:|------------------------------------------------:|------------:| | style | Defines view styles. [See more](/docs/v4/styling) | _Object_, _Array_ | _undefined_ | | paint | Painter function | _Function_ | _undefined_ | | debug | Enables debug mode on view bounding box. [See more](/docs/v4/advanced/debugging) | _Boolean_ | _false_ | | fixed | Renders component in all wrapped pages. [See more](/docs/v4/advanced/page-wrapping) | _Boolean_ | _false_ | | break | Forces the wrapping algorithm to start a new page when rendering this element. [See more](/docs/v4/advanced/page-wrapping#page-breaks) | _Boolean_ | _false_ | | minPresenceAhead | Hint that no page wrapping should occur between all sibling elements following the element within _n_ points. [See more](/docs/v4/advanced/orphans-and-widows) | _Number_ | _0_ | | bookmark | Attach bookmark to element. [See more](/docs/v4/advanced/document-navigation#bookmarks-v220) | _String_ or [Bookmark](/docs/v4/advanced/document-navigation#bookmark-type) | _undefined_ | React-pdf does not check how much space your drawing takes, so make sure you always define a `width` and `height` on the `style` prop. ### Painter function Prop used to perform drawings inside the Canvas. It takes 3 arguments: - `Painter object`: Wrapper around _pdfkit_ drawing methods. Use this to draw inside the Canvas - `availableWidth`: Width of the Canvas element. - `availableHeight`: Height of the Canvas element. ### Painter object Wrapper around _pdfkit_ methods you can use to draw inside the Canvas. All operations are chainable. For more information about how these methods work, please refer to [pdfkit documentation](http://pdfkit.org/). ### Shapes - `rect` - `roundedRect` - `circle` - `ellipse` - `polygon` ### Paths - `path` - `moveTo` - `lineTo` - `bezierCurveTo` - `quadraticCurveTo` ### Painting - `fill` - `stroke` - `clip` ### Color - `fillColor` - `strokeColor` - `opacity` - `fillOpacity` - `strokeOpacity` ### Strokes - `lineWidth` - `lineCap` - `lineJoin` - `miterLimit` - `dash` ### Gradients - `linearGradient` - `radialGradient` ### Text - `font` - `fontSize` - `text` ### Transform - `translate` - `scale` - `rotate` ### State - `save` - `restore` --- # Document URL: /docs/v4/components/document This component represents the PDF document itself. It _must_ be the root of your tree element structure, and under no circumstances should it be used as child of another react-pdf component. In addition, it should only have children of type ``. ```jsx import { Document, Page, Text } from '@react-pdf/renderer'; const MyDocument = () => ( First page Second page ); ``` ## Valid props | Prop name | Description | Type | Default | |------------|:-----------------------------------------------------------------------:|------------------------------------------:|--------------:| | title | Sets title info on the document's metadata | _String_ | _undefined_ | | author | Sets author info on the document's metadata | _String_ | _undefined_ | | subject | Sets subject info on the document's metadata | _String_ | _undefined_ | | keywords | Sets keywords associated info on the document's metadata | _String_ | _undefined_ | | creator | Sets creator info on the document's metadata | _String_ | _"react-pdf"_ | | producer | Sets producer info on the document's metadata | _String_ | _"react-pdf"_ | | pdfVersion | Sets PDF version for generated document | _String_ | _"1.3"_ | | conformance | Produces PDF/A output with the given conformance level. [See more](/docs/v4/components/document#conformance-type) | [PDFConformance](/docs/v4/components/document#conformance-type) | _undefined_ | | language | Sets PDF default language | _String_ | _undefined_ | | pageMode | Specifying how the document should be displayed when opened | [PageMode](/docs/v4/components/document#pagemode-type) | _useNone_ | | pageLayout | This controls how (some) PDF viewers choose to show pages | [PageLayout](/docs/v4/components/document#pagelayout-type) | _singlePage_ | | creationDate | Sets the creation date on the document's metadata | _Date_ | _undefined_ | | modificationDate | Sets the modification date on the document's metadata | _Date_ | _undefined_ | | ownerPassword | Sets an owner password on the document. Owner password is required for setting permissions | _String_ | _undefined_ | | userPassword | Sets a user password on the document. When set, viewers will ask for the password before opening the file | _String_ | _undefined_ | | permissions | Defines document permissions. Requires `ownerPassword` to be set. [See more](/docs/v4/components/document#permissions-type) | [Permissions](/docs/v4/components/document#permissions-type) | _undefined_ | | onRender | Callback after document renders. Receives document blob argument in web | _Function_ | _undefined_ | ### PageMode type `pageMode` prop can take one of the following values. Take into account some viewers might ignore this setting. | Value | Description | |----------------|:--------------------------------------------------------------------------------:| | useNone | Neither document bookmarks nor thumbnail images visible | | useOutlines | Document bookmarks visible | | useThumbs | Thumbnail images visible | | fullScreen | Full-screen mode, with no menu bar, window controls, or any other window visible | | useOC | Optional content group panel visible | | useAttachments | Attachments panel visible | ### Conformance type `conformance` produces an archival PDF/A file: the document gets XMP conformance metadata and an sRGB OutputIntent, and `pdfVersion` defaults to what the chosen level requires (`1.4` for PDF/A-1, `1.7` for PDF/A-2 and PDF/A-3) unless you set it yourself. | Value | Description | |------------|:---------------------------------------:| | PDF/A-1 | Alias of `PDF/A-1b`, based on PDF 1.4 | | PDF/A-1b | PDF/A-1 level B conformance | | PDF/A-2 | Alias of `PDF/A-2b`, based on PDF 1.7 | | PDF/A-2b | PDF/A-2 level B conformance | | PDF/A-3 | Alias of `PDF/A-3b`, based on PDF 1.7 | | PDF/A-3b | PDF/A-3 level B conformance | Only b-level (visual appearance) conformance is supported. PDF/A requires every font to be embedded, so register your own fonts with `Font.register` — documents using the built-in standard 14 fonts will not fully validate. ### Permissions type `permissions` prop accepts an object with the following optional boolean fields. All default to `true` when an owner password is set without specifying permissions. | Value | Description | |------------------------|:-------------------------------------------------------------------:| | printing | Whether the user can print the document | | modifying | Whether the user can modify the document | | copying | Whether the user can copy text and images | | annotating | Whether the user can add or modify annotations | | fillingForms | Whether the user can fill in form fields | | contentAccessibility | Whether content can be extracted for accessibility purposes | | documentAssembly | Whether the user can assemble the document (insert, rotate, delete pages) | ### PageLayout type `pageLayout` prop can take one of the following values. Take into account some viewers might ignore this setting. | Value | Description | |----------------|:----------------------------------------------------------------------:| | singlePage | Display one page at a time | | oneColumn | Display the pages in one column | | twoColumnLeft | Display the pages in two columns, with odd numbered pages on the left | | twoColumnRight | Display the pages in two columns, with odd numbered pages on the right | | twoPageLeft | Display the pages two at a time, with odd-numbered pages on the left | | twoPageRight | Display the pages two at a time, with odd-numbered pages on the right | --- # ImageBackground URL: /docs/v4/components/image-background A React component for displaying an image behind child content. It works like `Image` but acts as a container — any children are rendered on top of the image. ```jsx import { ImageBackground, Text } from '@react-pdf/renderer'; const Cover = () => ( Annual report ); ``` ## Valid props | Prop name | Description | Type | Default | |------------|:---------------------------------------------------------------------------:|------------------------------------------------:|------------:| | src | Source of the image. [See more](/docs/v4/components/image#source-object) | _Source object_ | _undefined_ | | source | Alias of _src_. [See more](/docs/v4/components/image#source-object) | _Source object_ | _undefined_ | | style | Defines view styles. [See more](/docs/v4/styling) | _Object_, _Array_ | _undefined_ | | imageStyle | Defines styles applied to the background image | _Object_, _Array_ | _undefined_ | | debug | Enables debug mode on view bounding box. [See more](/docs/v4/advanced/debugging) | _Boolean_ | _false_ | | fixed | Renders component in all wrapped pages. [See more](/docs/v4/advanced/page-wrapping) | _Boolean_ | _false_ | | break | Forces the wrapping algorithm to start a new page when rendering this element. [See more](/docs/v4/advanced/page-wrapping#page-breaks) | _Boolean_ | _false_ | | minPresenceAhead | Hint that no page wrapping should occur between all sibling elements following the element within _n_ points. [See more](/docs/v4/advanced/orphans-and-widows) | _Number_ | _0_ | | cache | Enables image caching between consecutive renders | _Boolean_ | _true_ | | srcSet | Responsive image sources for resolution-based selection | _String_ | _undefined_ | | sizes | Display width used for `srcSet` source selection | _String_, _Number_ | _undefined_ | | bookmark | Attach bookmark to element. [See more](/docs/v4/advanced/document-navigation#bookmarks-v220) | _String_ or [Bookmark](/docs/v4/advanced/document-navigation#bookmark-type) | _undefined_ | --- # Image URL: /docs/v4/components/image A React component for displaying network or local (Node only) JPG or PNG images, as well as base64 encoded image strings. ```jsx import { Image } from '@react-pdf/renderer'; const Logo = () => ( ); ``` ## Valid props | Prop name | Description | Type | Default | |-----------|:---------------------------------------------------------------------------:|------------------------------------------------:|------------:| | src | Source of the image. [See more](/docs/v4/components/image#source-object) | _Source object_ | _undefined_ | | source | Alias of _src_. [See more](/docs/v4/components/image#source-object) | _Source object_ | _undefined_ | | style | Defines view styles. [See more](/docs/v4/styling) | _Object_, _Array_ | _undefined_ | | debug | Enables debug mode on view bounding box. [See more](/docs/v4/advanced/debugging) | _Boolean_ | _false_ | | fixed | Renders component in all wrapped pages. [See more](/docs/v4/advanced/page-wrapping) | _Boolean_ | _false_ | | break | Forces the wrapping algorithm to start a new page when rendering this element. [See more](/docs/v4/advanced/page-wrapping#page-breaks) | _Boolean_ | _false_ | | minPresenceAhead | Hint that no page wrapping should occur between all sibling elements following the element within _n_ points. [See more](/docs/v4/advanced/orphans-and-widows) | _Number_ | _0_ | | cache | Enables image caching between consecutive renders | _Boolean_ | _true_ | | srcSet | Responsive image sources for resolution-based selection. E.g. `"small.jpg 300w, medium.jpg 600w"` | _String_ | _undefined_ | | sizes | Display width used for `srcSet` source selection | _String_, _Number_ | _undefined_ | | bookmark | Attach bookmark to element. [See more](/docs/v4/advanced/document-navigation#bookmarks-v220) | _String_ or [Bookmark](/docs/v4/advanced/document-navigation#bookmark-type) | _undefined_ | ### Source object Defines the source of an image. Can be in any of these four valid forms: | Form type | Description | Example | |-------------|:-----------------------------------------------------------------------------------------------------------------------------------:|------------------------------------------------------------| | String | Valid image URL or filesystem path (Node only) | `www.react-pdf.org/test.jpg` | | URL object | Enables to pass extra parameters on how to fetch images | `{ uri: valid-url, method: 'GET', headers: {}, body: '', credentials: 'include' }` | | Buffer | Renders image directly from Buffer. Image format (png or jpg) will be guessed based on Buffer. | `Buffer` | | Data buffer | Renders buffer image via the _data_ key. It's also recommended to provide the image _format_ so the engine knows how to proccess it | `{ data: Buffer, format: 'png' \| 'jpg' }` | | Function | A function that returns (can also return a promise that resolves to) any of the above formats | `() => String \| Promise` | --- # Components URL: /docs/v4/components React-pdf follows the [React primitives](https://github.com/lelandrichardson/react-primitives) specification, making the learning process very straightforward if you come from another React environment (such as react-native). Additionally, it implements custom Component types that allow you to structure your PDF document. - [Document](/docs/v4/components/document) - [Page](/docs/v4/components/page) - [View](/docs/v4/components/view) - [Image](/docs/v4/components/image) - [ImageBackground](/docs/v4/components/image-background) - [Text](/docs/v4/components/text) - [Link](/docs/v4/components/link) - [Note](/docs/v4/components/note) - [Canvas](/docs/v4/components/canvas) - [PDFViewer](/docs/v4/components/pdf-viewer) - [PDFDownloadLink](/docs/v4/components/pdf-download-link) - [BlobProvider](/docs/v4/components/blob-provider) --- # Link URL: /docs/v4/components/link A React component for displaying an hyperlink. Link’s can be nested inside a Text component, or being inside any other valid primitive. ```jsx import { Text, Link } from '@react-pdf/renderer'; const Footer = () => ( Built with react-pdf ); ``` ## Valid props | Prop name | Description | Type | Default | |-----------|:---------------------------------------------------------------------------------------------:|------------------------------------------------:|------------:| | src | Valid URL or destination ID. ID must be prefixed with `#`. [See more](/docs/v4/advanced/document-navigation#destinations-v200) | _String_ | _undefined_ | | href | Alias of _src_. Valid URL for external links | _String_ | _undefined_ | | wrap | Enable/disable page wrapping for element. [See more](/docs/v4/advanced/page-wrapping) | _Boolean_ | _true_ | | style | Defines view styles. [See more](/docs/v4/styling) | _Object_, _Array_ | _undefined_ | | debug | Enables debug mode on view bounding box. [See more](/docs/v4/advanced/debugging) | _Boolean_ | _false_ | | fixed | Render component in all wrapped pages. [See more](/docs/v4/advanced/page-wrapping) | _Boolean_ | _false_ | | break | Forces the wrapping algorithm to start a new page when rendering this element. [See more](/docs/v4/advanced/page-wrapping#page-breaks) | _Boolean_ | _false_ | | minPresenceAhead | Hint that no page wrapping should occur between all sibling elements following the element within _n_ points. [See more](/docs/v4/advanced/orphans-and-widows) | _Number_ | _0_ | | hitSlop | Expands the clickable area beyond the visible bounds of the link | _Number_ or _Object_ `{ top, bottom, left, right }` | _undefined_ | | bookmark | Attach bookmark to element. [See more](/docs/v4/advanced/document-navigation#bookmarks-v220) | _String_ or [Bookmark](/docs/v4/advanced/document-navigation#bookmark-type) | _undefined_ | --- # Note URL: /docs/v4/components/note A React component for displaying a note annotation inside the document. ```jsx import { View, Note } from '@react-pdf/renderer'; const Reviewed = () => ( Checked against the Q3 ledger. ); ``` ## Valid props | Prop name | Description | Type | Default | |-----------|:---------------------------------------------------------------------------:|------------------:|------------:| | style | Defines view styles. [See more](/docs/v4/styling) | _Object_, _Array_ | _undefined_ | | children | Note string content | _String_ | _undefined_ | | fixed | Renders component in all wrapped pages. [See more](/docs/v4/advanced/page-wrapping) | _Boolean_ | _false_ | | break | Forces the wrapping algorithm to start a new page when rendering this element. [See more](/docs/v4/advanced/page-wrapping#page-breaks) | _Boolean_ | _false_ | | minPresenceAhead | Hint that no page wrapping should occur between all sibling elements following the element within _n_ points. [See more](/docs/v4/advanced/orphans-and-widows) | _Number_ | _0_ | --- # Page URL: /docs/v4/components/page Represents single page inside the PDF documents, or a subset of them if using the wrapping feature. A `` can contain as many pages as you want, but ensures not rendering a page inside any component besides Document. ```jsx import { Document, Page, Text } from '@react-pdf/renderer'; const MyDocument = () => ( A landscape A4 page with a 40pt margin ); ``` ## Valid props | Prop name | Description | Type | Default | |-------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------:|------------------------------------------------:|-------------:| | size | Defines page size. If _String_, must be one of the [available page sizes](https://github.com/diegomura/react-pdf/blob/master/packages/layout/src/page/getSize.ts). Height is optional, if ommited it will behave as "auto". | _String_, _Array_, _Number_, _Object_ | _"A4"_ | | orientation | Defines page orientation. _Valid values: "portrait" or "landscape"_ | _String_ | _"portrait"_ | | wrap | Enables page wrapping for this page. [See more](/docs/v4/advanced/page-wrapping) | _Boolean_ | _true_ | | style | Defines page styles. [See more](/docs/v4/styling) | _Object_, _Array_ | _undefined_ | | debug | Enables debug mode on page bounding box. [See more](/docs/v4/advanced/debugging) | _Boolean_ | _false_ | | dpi | Enables setting a custom DPI for page contents. | _Number_ | _72_ | | id | Destination ID to be linked to. [See more](/docs/v4/advanced/document-navigation#destinations-v200) | _String_ | _undefined_ | | bookmark | Attach bookmark to element. [See more](/docs/v4/advanced/document-navigation#bookmarks-v220) | _String_ or [Bookmark](/docs/v4/advanced/document-navigation#bookmark-type) | _undefined_ | --- # PDFDownloadLink URL: /docs/v4/components/pdf-download-link Anchor tag to enable generate and download PDF documents on the fly. Refer to [on the fly rendering](/docs/v4/advanced/on-the-fly-rendering) for more information. ```jsx import { PDFDownloadLink, Document, Page, Text } from '@react-pdf/renderer'; const invoice = ( Invoice #42 ); const App = () => ( {({ loading }) => (loading ? 'Preparing document...' : 'Download')} ); ``` ## Valid props | Prop name | Description | Type | Default | |-----------|:-----------------------------:|-----------------------:|------------:| | document | PDF document implementation | _Document_ | _undefined_ | | fileName | Download PDF file name | _String_ | _undefined_ | | style | Defines anchor tag styles | _Object_, _Array_ | _undefined_ | | className | Defines anchor tag class name | _String_ | _undefined_ | | children | Anchor tag content | _DOM node_, _Function_ | _undefined_ | | onClick | Click handler. Receives click event and PDF instance as arguments | _Function_ | _undefined_ | --- # PDFViewer URL: /docs/v4/components/pdf-viewer Iframe PDF viewer for client-side generated documents. ```jsx import { PDFViewer, Document, Page, Text } from '@react-pdf/renderer'; const App = () => ( Rendered in the browser ); ``` ## Valid props | Prop name | Description | Type | Default | |-------------|:--------------------------------------------------------:|-------------------:|------------:| | style | Defines iframe styles | _Object_, _Array_ | _undefined_ | | className | Defines iframe class name | _String _ | _undefined_ | | children | PDF document implementation | _Document_ | _undefined_ | | width | Width of embedded PDF iframe | _String_, _Number_ | _undefined_ | | height | Height of embedded PDF iframe | _String_, _Number_ | _undefined_ | | innerRef | Ref to the underlying iframe element | _Ref_ | _undefined_ | | showToolbar | Render the toolbar. Supported on Chrome, Edge and Safari | _Boolean_ | _true_ | Other props are passed through to the iframe. --- # Text URL: /docs/v4/components/text A React component for displaying text. Text supports nesting of other Text or Link components to create inline styling. ```jsx import { Text } from '@react-pdf/renderer'; const Heading = () => ( Hello world ); ``` ## Valid props | Prop name | Description | Type | Default | |---------------------|:---------------------------------------------------------------------------------------:|------------------------------------------------:|------------:| | wrap | Enables/disables page wrapping for element. [See more](/docs/v4/advanced/page-wrapping) | _Boolean_ | _true_ | | render | Renders dynamic content based on context. [See more](/docs/v4/advanced/dynamic-content) | _Function_ | _undefined_ | | style | Defines view styles. [See more](/docs/v4/styling) | _Object_, _Array_ | _undefined_ | | debug | Enables debug mode on view bounding box. [See more](/docs/v4/advanced/debugging) | _Boolean_ | _false_ | | fixed | Renders component in all wrapped pages. [See more](/docs/v4/advanced/page-wrapping) | _Boolean_ | _false_ | | break | Forces the wrapping algorithm to start a new page when rendering this element. [See more](/docs/v4/advanced/page-wrapping#page-breaks) | _Boolean_ | _false_ | | minPresenceAhead | Hint that no page wrapping should occur between all sibling elements following the element within _n_ points. [See more](/docs/v4/advanced/orphans-and-widows) | _Number_ | _0_ | | hyphenationCallback | Specify hyphenation callback at a text level. See [hypthenation](/docs/v4/advanced/hyphenation) | _Function_ | _undefined_ | | hyphenationPenalty | Specify at what level words are hyphenated. [See more](/docs/v4/fonts#hyphenationpenalty) | _Number_ | _undefined_ | | id | Destination ID to be linked to. [See more](/docs/v4/advanced/document-navigation#destinations-v200) | _String_ | _undefined_ | | bookmark | Attach bookmark to element. [See more](/docs/v4/advanced/document-navigation#bookmarks-v220) | _String_ or [Bookmark](/docs/v4/advanced/document-navigation#bookmark-type) | _undefined_ | --- # View URL: /docs/v4/components/view The most fundamental component for building a UI and is designed to be nested inside other views and can have 0 to many children. ```jsx import { View, Text } from '@react-pdf/renderer'; const Row = () => ( Sidebar Content ); ``` ## Valid props | Prop name | Description | Type | Default | |-----------|:------------------------------------------------------------------------------:|------------------------------------------------:|------------:| | wrap | Enable/disable page wrapping for element. [See more](/docs/v4/advanced/page-wrapping) | _Boolean_ | _true_ | | style | Defines view styles. [See more](/docs/v4/styling) | _Object_, _Array_ | _undefined_ | | render | Render dynamic content based on context. [See more](/docs/v4/advanced/dynamic-content) | _Function_ | _undefined_ | | debug | Enables debug mode on view bounding box. [See more](/docs/v4/advanced/debugging) | _Boolean_ | _false_ | | fixed | Render component in all wrapped pages. [See more](/docs/v4/advanced/page-wrapping) | _Boolean_ | _false_ | | break | Forces the wrapping algorithm to start a new page when rendering this element. [See more](/docs/v4/advanced/page-wrapping#page-breaks) | _Boolean_ | _false_ | | minPresenceAhead | Hint that no page wrapping should occur between all sibling elements following the element within _n_ points. [See more](/docs/v4/advanced/orphans-and-widows) | _Number_ | _0_ | | id | Destination ID to be linked to. [See more](/docs/v4/advanced/document-navigation#destinations-v200) | _String_ | _undefined_ | | bookmark | Attach bookmark to element. [See more](/docs/v4/advanced/document-navigation#bookmarks-v220) | _String_ or [Bookmark](/docs/v4/advanced/document-navigation#bookmark-type) | _undefined_ | --- # Checkbox URL: /docs/v4/form/checkbox The `` element represents one of two states the user can toggle between. Some viewers behave differently based on wether the `name` prop is set or not and wether there are name duplicates or not. This can result in inconsistencies which makes the `name` prop recommendable to use and to achieve a consistent result across various viewers. ```jsx import { View, Text, Checkbox } from '@react-pdf/renderer'; const box = { width: 12, height: 12, borderWidth: 1, borderColor: '#c9c2b6' }; const label = { fontSize: 9, color: '#3e3e3e' }; const Consent = () => ( I accept the terms ); ``` ## Valid props | Prop name | Description | Type | Default | | --------------- | :--------------------------------------------------------------------------: | --------: | ----------: | | backGroundColor | It defines the color of the inside of the checkbox it applies to | _String_ | _undefined_ | | borderColor | Defines the color used to paint the outline of the checkbox | _String_ | _undefined_ | | checked | If set to true the checkbox is checked | _Boolean_ | _false_ | | onState | If set to true tells the pdf viewer to not spellcheck the text | _String_ | _Yes_ | | offState | Defines the format the textinput should be formatted to | _String_ | _No_ | | xMark | If set to true the onState appears as a X otherwise a checkmark is displayed | _Boolean_ | _false_ | See also [Common Form Attributes](/docs/v4/form/common-form-attributes) --- # Common Form Attributes URL: /docs/v4/form/common-form-attributes Common form attributes are attributes that are shared by a variety of elements. ```jsx import { View, Text, TextInput } from '@react-pdf/renderer'; const field = { height: 18, borderWidth: 1, borderColor: '#c9c2b6' }; const label = { fontSize: 9, color: '#3e3e3e', marginBottom: 4 }; const Reference = () => ( Reference ); ``` ## Supported attributes | Prop name | Description | Type | Default | | ------------ | :----------------------------------------------------------------------------------------------------: | -----------------: | ----------: | | name | Describes the name of the specific element when submitting the form | _String_ | _empty_ | | required | Describes if the specific element needs to have a value when submitting the form | _Boolean_ | _false_ | | noExport | If set to true the specific element is not exported at a form submission | _Boolean_ | _false_ | | readOnly | Defines if the specific element is editable or not. If set to true, the user shall not edit the value. | _Boolean_ | _false_ | | value | Defines the value of the specific element. For further information look at the element. | _String_, _Number_ | _undefined_ | | defaultValue | Describes what the default state for the value is. Can be used when resetting the form. | _String_, _Number_ | _undefined_ | --- # FieldSet URL: /docs/v4/form/field-set The `
` element is used to group other form elements together. On the form level this creates a hierarchical structure most important for data extraction and naming clearance. It is fully invisible. The usage of this element is optional and not required by any other element. Because of not being an element on its own the FieldSet is the only element not sharing the common form attributes. ```jsx import { FieldSet, View, Text, TextInput } from '@react-pdf/renderer'; const field = { height: 18, borderWidth: 1, borderColor: '#c9c2b6' }; const label = { fontSize: 9, color: '#3e3e3e', marginBottom: 4 }; const Address = () => (
Street City
); ``` ## Valid props | Prop name | Description | Type | Default | | --------- | :------------------------: | -------: | ----------: | | name | The name of the FieldSet | _String_ | _undefined_ | --- # Forms URL: /docs/v4/form React-pdf includes the ability to use [AcroForm](https://experienceleague.adobe.com/en/docs/experience-manager-learn/forms/document-services/pdf-forms-and-documents#acroforms)-Forms in pdfs. AcroForm is part of interactive pdfs and includes annotations for e.g. text fields, checkboxes. The AcroForm is automatically initialized as soon as one of the form elements is used. - [TextInput](/docs/v4/form/text-input) - [Checkbox](/docs/v4/form/checkbox) - [Select](/docs/v4/form/select) - [List](/docs/v4/form/list) - [Select and List Attributes](/docs/v4/form/select-and-list-attributes) - [FieldSet](/docs/v4/form/field-set) - [Common Form Attributes](/docs/v4/form/common-form-attributes) --- # List URL: /docs/v4/form/list The `` element represents a scrollable list for the selection of predefined options. ```jsx import { View, Text, List } from '@react-pdf/renderer'; const field = { height: 54, borderWidth: 1, borderColor: '#c9c2b6' }; const label = { fontSize: 9, color: '#3e3e3e', marginBottom: 4 }; const Countries = () => ( Countries ); ``` ## Valid props For attributes head to [Select and List Attributes](/docs/v4/form/select-and-list-attributes). --- # Select and List Attributes URL: /docs/v4/form/select-and-list-attributes These attributes are shared by the Select and List elements. ## Valid props | Prop name | Description | Type | Default | | ----------- | :-----------------------------------------------------------: | ---------: | ------: | | sort | Defines if the options shall be sorted alphabetically | _Boolean_ | _false_ | | multiSelect | If set to true the user is allowed to select multiple options | _Boolean_ | _false_ | | select | Defines the options to show inside the field as an array | _String[]_ | _[]_ | See also [Common Form Attributes](/docs/v4/form/common-form-attributes) --- # Select URL: /docs/v4/form/select The ` ); ``` ## Valid props | Prop name | Description | Type | Default | | --------- | :---------------------------------------------------------------------------------------: | --------: | ------: | | edit | If set to true allows the user to enter a value in the field | _Boolean_ | _false_ | | noSpell | If set to true and edit is set to true it tells the pdf viewer to not spellcheck the text | _Boolean_ | _false_ | For more attributes head to [Select and List Attributes](/docs/v4/form/select-and-list-attributes). --- # TextInput URL: /docs/v4/form/text-input The `` element represents a text field for inputting single- or multiline text. ```jsx import { View, Text, TextInput } from '@react-pdf/renderer'; const field = { height: 18, borderWidth: 1, borderColor: '#c9c2b6' }; const label = { fontSize: 9, color: '#3e3e3e', marginBottom: 4 }; const NameField = () => ( Full name ); ``` ## Valid props | Prop name | Description | Type | Default | | --------- | :----------------------------------------------------------------: | ------------------------------------------: | ----------: | | align | Defines the alignment of text | _String_ | _left_ | | multiline | Defines if the user is allowed to input more than one line of text | _Boolean_ | _false_ | | password | If set to true the text will be masked with e. g. * | _Boolean_ | _false_ | | noSpell | If set to true tells the pdf viewer to not spellcheck the text | _Boolean_ | _false_ | | format | Defines the format the textinput should be formatted to | [TextInputFormatting](#textinputformatting) | _undefined_ | | fontSize | Defines the font size for the text input. Set to `0` for auto-size | _Number_ | _undefined_ | | maxLength | Defines the maximum number of characters | _Number_ | _undefined_ | See also [Common Form Attributes](/docs/v4/form/common-form-attributes) ### TextInputFormatting `format` is a definition how the value shall be formatted by the viewer. Take into account that not all viewers support this feature because it involves javascript execution. | Prop name | Description | Type | Default | | --------------- | :--------------------------------------------------: | ------------------------------------------: | ----------: | | type | Defines the alignment of text | [TextInputFormatType](#textinputformattype) | _undefined_ | | param | Defines a format for certain types | _String_ | _undefined_ | | nDec | Defines the number of places after the decimal point | _Number_ | _undefined_ | | sepComma | Defines if the seperator shall be a comma or not | _Boolean_ | _false_ | | negStyle | Defines style for negative numbers | _String_ | _undefined_ | | currency | Defines the symbol to be placed as currency sign | _String_ | _undefined_ | | currencyPrepend | If set to true the currency sign is prepended | _Boolean_ | _false_ | ### TextInputFormatType `type` prop can take one of the following values. | Value | Description | | -------- | :-----------------------------------------------------------------: | | date | Expects the param prop to be a valid date format. | | time | Expects the param prop to be a valid time format. | | percent | Uses the props nDec, sepComma, negStyle, currency, currencyPrepend. | | number | Uses the props nDec, sepComma, negStyle, currency, currencyPrepend. | | zip | Formats for the zip-code standard | | zipPlus4 | Formats for the zip+4 standard | | phone | Formats for a phone number | | ssn | Formats for a ssn number | For deeper knowledge into the formatting you might want to look into the [pdfkit doc](https://pdfkit.org/docs/forms.html#text_field_formatting) and into the [API Reference for Forms](https://experienceleague.adobe.com/docs/experience-manager-learn/assets/FormsAPIReference.pdf) Page 119. --- # Circle URL: /docs/v4/svg/circle The `` element is used to create a circle. ```jsx import { Svg, Circle } from '@react-pdf/renderer'; const Rings = () => ( ); ``` ## Valid props | Prop name | Description | Type | Default | | --------- | :------------------------------------------------: | -----------------: | ----------: | | cx | The x-axis coordinate of the center of the circle. | _String_, _Number_ | _undefined_ | | cy | The y-axis coordinate of the center of the circle. | _String_, _Number_ | _undefined_ | | r | The radius of the circle. | _String_, _Number_ | _undefined_ | See also [Presentation Attributes](/docs/v4/svg/presentation-attributes) --- # ClipPath URL: /docs/v4/svg/clip-path The `` SVG element defines a clipping path, to be used by the `clipPath` property. A clipping path restricts the region to which paint can be applied. Conceptually, parts of the drawing that lie outside of the region bounded by the clipping path are not drawn. ```jsx import { Svg, Defs, ClipPath, Rect, Circle } from '@react-pdf/renderer'; const Window = () => ( ); ``` --- # Defs URL: /docs/v4/svg/defs The `` element is used to store graphical objects that will be used at a later time. Objects created inside a `` element are not rendered directly. To display them you have to reference them ```jsx import { Svg, Defs, LinearGradient, Stop, Rect } from '@react-pdf/renderer'; const Reused = () => ( ); ``` --- # Ellipse URL: /docs/v4/svg/ellipse The `` element is used to create an ellipse. An ellipse is closely related to a circle. The difference is that an ellipse has an x and a y radius that differs from each other, while a circle has equal x and y radius. ```jsx import { Svg, Ellipse } from '@react-pdf/renderer'; const Lenses = () => ( ); ``` ## Valid props | Prop name | Description | Type | Default | | --------- | :--------------------------------------: | -----------------: | ----------: | | cx | The x position of the ellipse. | _String_, _Number_ | _undefined_ | | cy | The y position of the ellipse. | _String_, _Number_ | _undefined_ | | rx | The radius of the ellipse on the x axis. | _String_, _Number_ | _undefined_ | | ry | The radius of the ellipse on the y axis. | _String_, _Number_ | _undefined_ | See also [Presentation Attributes](/docs/v4/svg/presentation-attributes) --- # G URL: /docs/v4/svg/g The `` SVG element is a container used to group other SVG elements. Transformations applied to the `` element are performed on its child elements, and its attributes are inherited by its children. ```jsx import { Svg, G, Rect, Circle } from '@react-pdf/renderer'; const Tilted = () => ( ); ``` ## Valid props This element only includes [Presentation Attributes](/docs/v4/svg/presentation-attributes) --- # SVG Images URL: /docs/v4/svg - [Svg](/docs/v4/svg/svg) - [Line](/docs/v4/svg/line) - [Polyline](/docs/v4/svg/polyline) - [Polygon](/docs/v4/svg/polygon) - [Path](/docs/v4/svg/path) - [Rect](/docs/v4/svg/rect) - [Circle](/docs/v4/svg/circle) - [Ellipse](/docs/v4/svg/ellipse) - [Text](/docs/v4/svg/text) - [Tspan](/docs/v4/svg/tspan) - [G](/docs/v4/svg/g) - [Stop](/docs/v4/svg/stop) - [Defs](/docs/v4/svg/defs) - [ClipPath](/docs/v4/svg/clip-path) - [Marker](/docs/v4/svg/marker) - [LinearGradient](/docs/v4/svg/linear-gradient) - [RadialGradient](/docs/v4/svg/radial-gradient) - [Presentation Attributes](/docs/v4/svg/presentation-attributes) --- # Line URL: /docs/v4/svg/line The `` element is used to create a line. ```jsx import { Svg, Line } from '@react-pdf/renderer'; const Rules = () => ( ); ``` ## Valid props | Prop name | Description | Type | Default | | --------- | :-------------------------------------------------------: | -----------------: | ----------: | | x1 | Defines the x-axis coordinate of the line starting point. | _String_, _Number_ | _undefined_ | | x2 | Defines the x-axis coordinate of the line ending point. | _String_, _Number_ | _undefined_ | | y1 | Defines the y-axis coordinate of the line starting point. | _String_, _Number_ | _undefined_ | | y2 | Defines the y-axis coordinate of the line ending point. | _String_, _Number_ | _undefined_ | See also [Presentation Attributes](/docs/v4/svg/presentation-attributes) --- # LinearGradient URL: /docs/v4/svg/linear-gradient The `` element lets authors define linear gradients that can be applied to fill or stroke of graphical elements. ```jsx import { Svg, Defs, LinearGradient, Stop, Rect } from '@react-pdf/renderer'; const Ember = () => ( ); ``` ## Valid props | Prop name | Description | Type | Default | | ----------------- | :-------------------------------------------------------------------------------------------------------------: | -----------------: | ----------: | | x1 | Defines the x coordinate of the starting point of the vector gradient along which the linear gradient is drawn. | _String_, _Number_ | _undefined_ | | x2 | Defines the x coordinate of the ending point of the vector gradient along which the linear gradient is drawn. | _String_, _Number_ | _undefined_ | | y1 | Defines the y coordinate of the starting point of the vector gradient along which the linear gradient is drawn. | _String_, _Number_ | _undefined_ | | y2 | Defines the y coordinate of the ending point of the vector gradient along which the linear gradient is drawn. | _String_, _Number_ | _undefined_ | | xlinkHref | Reference to another gradient to inherit its stops and attributes from. | _String_ | _undefined_ | | gradientTransform | Defines a transformation to be applied to the gradient. | _String_ | _undefined_ | | gradientUnits | Defines the coordinate system for the gradient attributes. _Valid values: "userSpaceOnUse" or "objectBoundingBox"_ | _String_ | _undefined_ | --- # Marker URL: /docs/v4/svg/marker The `` element defines a graphic drawn on the vertices of a ``, ``, `` or ``, typically an arrowhead or a data point. Declare it inside a `` element and reference it from the shape through the `markerStart`, `markerMid` and `markerEnd` attributes, which paint it on the first vertex, every intermediate vertex and the last vertex respectively. ```jsx import { Svg, Defs, Marker, Path, Circle, Line, Polyline, } from '@react-pdf/renderer'; const Flow = () => ( ); ``` ## Valid props | Prop name | Description | Type | Default | | ------------ | :---------------------------------------------------------------------------------------------------: | -----------------: | --------------: | | id | Unique identifier used to reference the marker from a shape. | _String_ | _undefined_ | | viewBox | Defines the coordinate system of the marker contents, as `"minX minY maxX maxY"`. | _String_ | _undefined_ | | markerWidth | Width of the marker viewport. Only applied when `viewBox` is present. | _String_, _Number_ | _3_ | | markerHeight | Height of the marker viewport. Only applied when `viewBox` is present. | _String_, _Number_ | _3_ | | refX | Position of the marker point on its x-axis, aligned to the vertex. | _String_, _Number_ | _0_ | | refY | Position of the marker point on its y-axis, aligned to the vertex. | _String_, _Number_ | _0_ | | orient | Rotation applied to the marker. `auto` follows the direction of the shape, `auto-start-reverse` also flips the start marker, and a number sets a fixed angle in degrees. | _String_, _Number_ | _0_ | | markerUnits | Coordinate system for the marker. `strokeWidth` scales it with the shape's `strokeWidth`, `userSpaceOnUse` keeps its size constant. | _String_ | _strokeWidth_ | See also [Presentation Attributes](/docs/v4/svg/presentation-attributes) --- # Path URL: /docs/v4/svg/path The `` element is the most powerful element in the SVG library of basic shapes. It can be used to create lines, curves, arcs, and more. ```jsx import { Svg, Path } from '@react-pdf/renderer'; const Curve = () => ( ); ``` ## Valid props | Prop name | Description | Type | Default | | --------- | :--------------------------------------------------------------------------------------------------------------------: | -------: | ----------: | | d | This attribute defines the shape of the path. [See more](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/d) | _String_ | _undefined_ | See also [Presentation Attributes](/docs/v4/svg/presentation-attributes) --- # Polygon URL: /docs/v4/svg/polygon The `` element is used to create a graphic that contains at least three sides. Polygons are made of straight lines, and the shape is "closed" (all the lines connect up). ```jsx import { Svg, Polygon } from '@react-pdf/renderer'; const Area = () => ( ); ``` ## Valid props | Prop name | Description | Type | Default | | --------- | :--------------------------------------------------------------------------------------------------------: | -------: | ----------: | | points | This attribute defines the list of points (pairs of x,y absolute coordinates) required to draw the polygon | _String_ | _undefined_ | See also [Presentation Attributes](/docs/v4/svg/presentation-attributes) --- # Polyline URL: /docs/v4/svg/polyline The `` element is used to create any shape that consists of only straight lines (that is connected at several points). ```jsx import { Svg, Polyline } from '@react-pdf/renderer'; const Trend = () => ( ); ``` ## Valid props | Prop name | Description | Type | Default | | --------- | :---------------------------------------------------------------------------------------------------------: | -------: | ----------: | | points | This attribute defines the list of points (pairs of x,y absolute coordinates) required to draw the polyline | _String_ | _undefined_ | See also [Presentation Attributes](/docs/v4/svg/presentation-attributes) --- # Presentation Attributes URL: /docs/v4/svg/presentation-attributes SVG presentation attributes are CSS properties that can be used as attributes on SVG elements. This means it can be passed either inside a `style` object or directly by element's props. ```jsx import { Svg, Circle, Rect } from '@react-pdf/renderer'; const Attributes = () => ( ); ``` ## Supported attributes | Prop name | Description | Type | Default | | ---------------- | :------------------------------------------------------------------------------------------------: | -----------------: | ----------: | | color | Provides a potential indirect value for the fill or stroke attributes. | _String_ | _undefined_ | | dominantBaseline | Defines the baseline used to align the box’s text and inline-level contents. | _String_ | _auto_ | | fill | It defines the color of the inside of the graphical element it applies to. | _String_ | _undefined_ | | fillOpacity | It specifies the opacity of the color or the content the current object is filled with. | _String_, _Number_ | _1_ | | fillRule | It indicates how to determine what side of a path is inside a shape. | _String_ | _nonzero_ | | opacity | It specifies the transparency of an object or a group of objects. | _String_, _Number_ | _1_ | | stroke | Defines the color used to paint the outline of the shape. | _String_ | _undefined_ | | strokeWidth | Defines the width of the stroke to be applied to the shape. | _String_, _Number_ | _1_ | | strokeOpacity | Defines the opacity of the stroke of a shape. | _String_, _Number_ | _1_ | | strokeLinecap | Defines the shape to be used at the end of open subpaths when they are stroked. | _String_ | _butt_ | | strokeLinejoin | Defines the shape to be used at the corners of paths when they are stroked. | _String_ | _miter_ | | strokeDasharray | Defines the pattern of dashes and gaps used to paint the outline of the shape. | _String_ | _undefined_ | | transform | Defines a list of transform definitions that are applied to an element and the element's children. | _String_ | _undefined_ | | textAnchor | Defines the horizontal alignment of a string of text. | _String_ | _undefined_ | | visibility | Lets you control the visibility of graphical elements. | _String_ | _visible_ | | clipPath | References a [ClipPath](/docs/v4/svg/clip-path) restricting where paint is applied. | _String_ | _undefined_ | | markerStart | References a [Marker](/docs/v4/svg/marker) drawn on the first vertex of the shape. | _String_ | _undefined_ | | markerMid | References a [Marker](/docs/v4/svg/marker) drawn on every intermediate vertex of the shape. | _String_ | _undefined_ | | markerEnd | References a [Marker](/docs/v4/svg/marker) drawn on the last vertex of the shape. | _String_ | _undefined_ | --- # RadialGradient URL: /docs/v4/svg/radial-gradient The `` element lets authors define radial gradients that can be applied to fill or stroke of graphical elements. ```jsx import { Svg, Defs, RadialGradient, Stop, Rect } from '@react-pdf/renderer'; const Glow = () => ( ); ``` ## Valid props | Prop name | Description | Type | Default | | ----------------- | :-----------------------------------------------------------------------------------------------------------------------------------------------------------------: | -----------------: | ----------: | | cx | Defines the x coordinate of the end circle of the radial gradient. | _String_, _Number_ | _undefined_ | | cy | Defines the y coordinate of the end circle of the radial gradient. | _String_, _Number_ | _undefined_ | | r | Defines the radius of the end circle of the radial gradient. | _String_, _Number_ | _undefined_ | | fr | Defines the radius of the start circle of the radial gradient. The gradient will be drawn such that the 0% `` is mapped to the perimeter of the start circle. | _String_, _Number_ | _undefined_ | | fx | Defines the x coordinate of the start circle of the radial gradient. | _String_, _Number_ | _undefined_ | | fy | Defines the y coordinate of the start circle of the radial gradient. | _String_, _Number_ | _undefined_ | | xlinkHref | Reference to another gradient to inherit its stops and attributes from. | _String_ | _undefined_ | | gradientTransform | Defines a transformation to be applied to the gradient. | _String_ | _undefined_ | | gradientUnits | Defines the coordinate system for the gradient attributes. _Valid values: "userSpaceOnUse" or "objectBoundingBox"_ | _String_ | _undefined_ | --- # Rect URL: /docs/v4/svg/rect The `` element is used to create a rectangle and variations of a rectangle shape. ```jsx import { Svg, Rect } from '@react-pdf/renderer'; const Swatches = () => ( ); ``` ## Valid props | Prop name | Description | Type | Default | | --------- | :---------------------------------------: | -----------------: | ----------: | | x | The x coordinate of the rect. | _String_, _Number_ | _undefined_ | | y | The y coordinate of the rect. | _String_, _Number_ | _undefined_ | | width | The width of the rect. | _String_, _Number_ | _undefined_ | | height | The height of the rect. | _String_, _Number_ | _undefined_ | | rx | The horizontal corner radius of the rect. | _String_, _Number_ | _undefined_ | | ry | The vertical corner radius of the rect. | _String_, _Number_ | _undefined_ | See also [Presentation Attributes](/docs/v4/svg/presentation-attributes) --- # Stop URL: /docs/v4/svg/stop The SVG `` element defines a color and its position to use on a gradient. This element is always a child of a `` or `` element ```jsx import { Svg, Defs, LinearGradient, Stop, Rect } from '@react-pdf/renderer'; const Ramp = () => ( ); ``` ## Valid props | Prop name | Description | Type | Default | | ----------- | :-------------------------------------------------------------------------: | -----------------: | ----------: | | offset | Defines where the gradient stop is placed along the gradient vector. | _String_, _Number_ | _undefined_ | | stopColor | Defines the color of the gradient stop. It can be used as a CSS property. | _String_ | _undefined_ | | stopOpacity | Defines the opacity of the gradient stop. It can be used as a CSS property. | _String_, _Number_ | _1_ | --- # Svg URL: /docs/v4/svg/svg The `` element is a container that defines a new coordinate system and viewport. It is used as the outermost element of SVG documents. ```jsx import { Svg, Rect, Circle } from '@react-pdf/renderer'; const Canvas = () => ( ); ``` ## Valid props | Prop name | Description | Type | Default | | ------------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: | -----------------: | ----------: | | width | The displayed width of the rectangular viewport | _String_, _Number_ | _undefined_ | | height | The displayed height of the rectangular viewport | _String_, _Number_ | _undefined_ | | viewBox | The SVG viewport coordinates for the current SVG fragment | _String_ | _undefined_ | | preserveAspectRatio | How the svg fragment must be deformed if it is displayed with a different aspect ratio. [See more](https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/preserveAspectRatio) | _String_ | _undefined_ | | style | Defines SVG styles. [See more](/docs/v4/styling) | _Object_, _Array_ | _undefined_ | --- # Text URL: /docs/v4/svg/text The `` element draws a graphics element consisting of text. ```jsx import { Svg, Text } from '@react-pdf/renderer'; const heading = { fontSize: 16 }; const caption = { fontSize: 9 }; const Label = () => ( React-pdf draws text inside SVG ); ``` ## Valid props | Prop name | Description | Type | Default | | --------- | :----------------------------------------------------------: | -----------------: | ----------: | | x | The x coordinate of the starting point of the text baseline. | _String_, _Number_ | _undefined_ | | y | The y coordinate of the starting point of the text baseline. | _String_, _Number_ | _undefined_ | See also [Presentation Attributes](/docs/v4/svg/presentation-attributes) --- # Tspan URL: /docs/v4/svg/tspan The SVG `` element defines a subtext within a `` element or another `` element. It allows for adjustment of the style and/or position of that subtext as needed. ```jsx import { Svg, Text, Tspan } from '@react-pdf/renderer'; const heading = { fontSize: 16 }; const Label = () => ( React pdf ); ``` ## Valid props | Prop name | Description | Type | Default | | --------- | :----------------------------------------------------------: | -----------------: | ----------: | | x | The x coordinate of the starting point of the text baseline. | _String_, _Number_ | _undefined_ | | y | The y coordinate of the starting point of the text baseline. | _String_, _Number_ | _undefined_ | See also [Presentation Attributes](/docs/v4/svg/presentation-attributes)