# Table of Contents - [React-pdf](#react-pdf) - [React-pdf](#react-pdf) - [React-pdf](#react-pdf) - [React-pdf](#react-pdf) - [React-pdf](#react-pdf) - [React-pdf](#react-pdf) - [React-pdf](#react-pdf) - [React-pdf](#react-pdf) - [React-pdf](#react-pdf) - [React-pdf](#react-pdf) - [React-pdf](#react-pdf) --- # React-pdf [Edit](https://github.com/react-pdf/site/blob/master/docs/quick-start.md) ![](https://react-pdf.org/images/logo.png) React-pdf ========= React-pdf ========= #### React renderer for creating PDF files on the browser and server. ![](https://react-pdf.org/images/document-graphic.png)Try it out! ### 1\. Install React and react-pdf Starting with react-pdf is extremely simple. #### Using npm npm install @react-pdf/renderer --save #### Using Yarn yarn add @react-pdf/renderer #### Using pnpm pnpm add @react-pdf/renderer #### Using Bun 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: import React from 'react'; import { Page, Text, View, Document, StyleSheet } from '@react-pdf/renderer'; // Create styles const styles = StyleSheet.create({ page: { flexDirection: 'row', backgroundColor: '#E4E4E4' }, section: { margin: 10, padding: 10, flexGrow: 1 } }); // Create Document Component const MyDocument = () => ( Section #1 Section #2 ); This will produce a PDF document with a single page. Inside, two different blocks, each of them rendering a different text. These are not the only valid 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 import ReactPDF from '@react-pdf/renderer'; ReactPDF.render(, `${__dirname}/example.pdf`); #### Render to a stream import ReactPDF from '@react-pdf/renderer'; ReactPDF.renderToStream(); #### Render in DOM 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! Compatibility → ![](https://react-pdf.org/images/corner-graphics.png) Generating PDFs in bulk? [Talk to us](https://axxy020tu5c.typeform.com/to/eU21hXDy) --- # React-pdf ### 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: 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: 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: __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`: 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`: await esbuild.build({ // … inject: ['cjs-shim.ts'], }); And you should be good to go! Rendering process → ![](https://react-pdf.org/images/corner-graphics.png) Generating PDFs in bulk? [Talk to us](https://axxy020tu5c.typeform.com/to/eU21hXDy) --- # React-pdf [Edit](https://github.com/react-pdf/site/blob/master/docs/rendering-process.md) Rendering process overview -------------------------- At a high level, the document creation process is composed by 6 concrete steps. 1. Internal structures creation 2. Resolve styles 3. Fetching assets 4. Layout text 5. Wrapping pages 6. Rendering ### 1\. Internal structures creation The first step involves transforming the _React element tree_ into the appropriate internal instances for each component type. This involves saving the relationship between these (parent-child) nodes. Besides **Document**, all nodes will represent a block inside a document, with a height, width, paddings and margins (yet to be discovered). From now on, react-pdf works over this data structure to start inferring where each block goes inside the final document. ### 2\. Resolve styles This step involves pre-processing node styles, as well as defining default values for the needed properties that were not provided by the user. This way, all successive steps can work on the basis that all required styles are defined in the tree. Part of the pre-processing involves unit conversion, style inheritance and styles expansion. ### 3\. Fetching assets Time to ask for all needed resources! We traverse the internal nodes tree fetching any required _font_, _image_ or _emoji_. We run all these requests asynchronously, but we won't move forward until all requests are finished (with success or failure). ### 4\. Layout text Now that we have all fonts loaded, we can layout text into paragraphs. This is a critical and complex step: we first convert characters into glyphs using the appropriate font family and size, embed images or emoji images if present and ultimately break them into lines either on whitespaces or by breaking words based on language (or custom) rules. ### 5\. Wrapping pages This is the most time-consuming step, since it involves not just calculating where each element is in the document and how much space it will need, but also splitting these elements into different pages. We internally use [Yoga layout](https://yogalayout.com/) to compute node's size and coordinates inside the document, and perform page breaking based on a set of customizable heuristics. ### 6\. Rendering The creation of the PDF document itself. For this task, we use the awesome [pdfkit](https://github.com/devongovett/pdfkit) . Once in this stage, we have our internal tree structure with all the needed data to generate our document. All it remains is deciding what we want to do with this data. This will vary depending on the binding you are using, but basically it means either displaying or saving it. ← Compatibility Components → ![](https://react-pdf.org/images/corner-graphics.png) Generating PDFs in bulk? [Talk to us](https://axxy020tu5c.typeform.com/to/eU21hXDy) --- # React-pdf [Edit](https://github.com/react-pdf/site/blob/master/docs/components.md) 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 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 ``. #### 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"_ | | language | Sets PDF default language | _String_ | _undefined_ | | pageMode | Specifying how the document should be displayed when opened | [PageMode](https://react-pdf.org/components#pagemode-type) | _useNone_ | | pageLayout | This controls how (some) PDF viewers choose to show pages | [PageLayout](https://react-pdf.org/components#pagelayout-type) | _singlePage_ | | 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 | ##### 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 | * * * ### 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. #### 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.js)
. 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](https://react-pdf.org/advanced#page-wrapping) | _Boolean_ | _true_ | | style | Defines page styles. [See more](https://react-pdf.org/styling) | _Object_, _Array_ | _undefined_ | | debug | Enables debug mode on page bounding box. [See more](https://react-pdf.org/advanced#debugging) | _Boolean_ | _false_ | | dpi | Enables setting a custom DPI for page contents. | _Number_ | _72_ | | id | Destination ID to be linked to. [See more](https://react-pdf.org/advanced#destinations) | _String_ | _undefined_ | | bookmark | Attach bookmark to element. [See more](https://react-pdf.org/advanced#bookmarks) | _String_ or [Bookmark](https://react-pdf.org/advanced#bookmark-type) | _undefined_ | * * * ### 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. #### Valid props | Prop name | Description | Type | Default | | --- | --- | --- | --- | | wrap | Enable/disable page wrapping for element. [See more](https://react-pdf.org/advanced#page-wrapping) | _Boolean_ | _true_ | | style | Defines view styles. [See more](https://react-pdf.org/styling) | _Object_, _Array_ | _undefined_ | | render | Render dynamic content based on context. [See more](https://react-pdf.org/advanced#dynamic-content) | _Function_ | _undefined_ | | debug | Enables debug mode on view bounding box. [See more](https://react-pdf.org/advanced#debugging) | _Boolean_ | _false_ | | fixed | Render component in all wrapped pages. [See more](https://react-pdf.org/advanced#page-wrapping) | _Boolean_ | _false_ | | id | Destination ID to be linked to. [See more](https://react-pdf.org/advanced#destinations) | _String_ | _undefined_ | | bookmark | Attach bookmark to element. [See more](https://react-pdf.org/advanced#bookmarks) | _String_ or [Bookmark](https://react-pdf.org/advanced#bookmark-type) | _undefined_ | * * * ### Image A React component for displaying network or local (Node only) JPG or PNG images, as well as base64 encoded image strings. #### Valid props | Prop name | Description | Type | Default | | --- | --- | --- | --- | | src | Source of the image. [See more](https://react-pdf.org/components#source-object) | _Source object_ | _undefined_ | | source | Alias of _src_. [See more](https://react-pdf.org/components#source-object) | _Source object_ | _undefined_ | | style | Defines view styles. [See more](https://react-pdf.org/styling) | _Object_, _Array_ | _undefined_ | | debug | Enables debug mode on view bounding box. [See more](https://react-pdf.org/advanced#debugging) | _Boolean_ | _false_ | | fixed | Renders component in all wrapped pages. [See more](https://react-pdf.org/advanced#page-wrapping) | _Boolean_ | _false_ | | cache | Enables image caching between consecutive renders | _Boolean_ | _true_ | | bookmark | Attach bookmark to element. [See more](https://react-pdf.org/advanced#bookmarks) | _String_ or [Bookmark](https://react-pdf.org/advanced#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` | * * * ### Text A React component for displaying text. Text supports nesting of other Text or Link components to create inline styling. #### Valid props | Prop name | Description | Type | Default | | --- | --- | --- | --- | | wrap | Enables/disables page wrapping for element. [See more](https://react-pdf.org/advanced#page-wrapping) | _Boolean_ | _true_ | | render | Renders dynamic content based on context. [See more](https://react-pdf.org/advanced#dynamic-content) | _Function_ | _undefined_ | | style | Defines view styles. [See more](https://react-pdf.org/styling) | _Object_, _Array_ | _undefined_ | | debug | Enables debug mode on view bounding box. [See more](https://react-pdf.org/advanced#debugging) | _Boolean_ | _false_ | | fixed | Renders component in all wrapped pages. [See more](https://react-pdf.org/advanced#page-wrapping) | _Boolean_ | _false_ | | hyphenationCallback | Specify hyphenation callback at a text level. See [hypthenation](https://react-pdf.org/advanced#hyphenation) | _Function_ | _undefined_ | | id | Destination ID to be linked to. [See more](https://react-pdf.org/advanced#destinations) | _String_ | _undefined_ | | bookmark | Attach bookmark to element. [See more](https://react-pdf.org/advanced#bookmarks) | _String_ or [Bookmark](https://react-pdf.org/advanced#bookmark-type) | _undefined_ | * * * ### Link A React component for displaying an hyperlink. Link’s can be nested inside a Text component, or being inside any other valid primitive. #### Valid props | Prop name | Description | Type | Default | | --- | --- | --- | --- | | src | Valid URL or destination ID. ID must be prefixed with `#`. [See more](https://react-pdf.org/advanced#destinations) | _String_ | _undefined_ | | wrap | Enable/disable page wrapping for element. [See more](https://react-pdf.org/advanced#page-wrapping) | _Boolean_ | _true_ | | style | Defines view styles. [See more](https://react-pdf.org/styling) | _Object_, _Array_ | _undefined_ | | debug | Enables debug mode on view bounding box. [See more](https://react-pdf.org/advanced#debugging) | _Boolean_ | _false_ | | fixed | Render component in all wrapped pages. [See more](https://react-pdf.org/advanced#page-wrapping) | _Boolean_ | _false_ | | bookmark | Attach bookmark to element. [See more](https://react-pdf.org/advanced#bookmarks) | _String_ or [Bookmark](https://react-pdf.org/advanced#bookmark-type) | _undefined_ | * * * ### Note A React component for displaying a note annotation inside the document. #### Valid props | Prop name | Description | Type | Default | | --- | --- | --- | --- | | style | Defines view styles. [See more](https://react-pdf.org/styling) | _Object_, _Array_ | _undefined_ | | children | Note string content | _String_ | _undefined_ | | fixed | Renders component in all wrapped pages. [See more](https://react-pdf.org/advanced#page-wrapping) | _Boolean_ | _false_ | * * * ### Canvas A React component for freely drawing any content on the page. #### Valid props | Prop name | Description | Type | Default | | --- | --- | --- | --- | | style | Defines view styles. [See more](https://react-pdf.org/styling) | _Object_, _Array_ | _undefined_ | | paint | Painter function | _Function_ | _undefined_ | | debug | Enables debug mode on view bounding box. [See more](https://react-pdf.org/advanced#debugging) | _Boolean_ | _false_ | | fixed | Renders component in all wrapped pages. [See more](https://react-pdf.org/advanced#page-wrapping) | _Boolean_ | _false_ | | bookmark | Attach bookmark to element. [See more](https://react-pdf.org/advanced#bookmarks) | _String_ or [Bookmark](https://react-pdf.org/advanced#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/) . Available methods: * dash * clip * save * path * fill * font * text * rect * scale * moveTo * lineTo * stroke * rotate * circle * lineCap * opacity * ellipse * polygon * restore * lineJoin * fontSize * fillColor * lineWidth * translate * miterLimit * strokeColor * fillOpacity * roundedRect * strokeOpacity * bezierCurveTo * quadraticCurveTo * linearGradient * radialGradient * * * ### PDFViewer `Web only` Iframe PDF viewer for client-side generated documents. #### 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_ | | showToolbar | Render the toolbar. Supported on Chrome, Edge and Safari | _Boolean_ | _true_ | Other props are passed through to the iframe. * * * ### PDFDownloadLink `Web only` Anchor tag to enable generate and download PDF documents on the fly. Refer to [on the fly rendering](https://react-pdf.org/advanced#on-the-fly-rendering) for more information. #### 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_ | * * * ### BlobProvider `Web only` Easy and declarative way of getting document's blob data without showing it on screen. Refer to [on the fly rendering](https://react-pdf.org/advanced#on-the-fly-rendering) for more information. #### 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_ | * * * ← Rendering process SVG → ![](https://react-pdf.org/images/corner-graphics.png) Generating PDFs in bulk? [Talk to us](https://axxy020tu5c.typeform.com/to/eU21hXDy) --- # React-pdf [Edit](https://github.com/react-pdf/site/blob/master/docs/svg.md) SVG Images ---------- ### Svg The `` element is a container that defines a new coordinate system and viewport. It is used as the outermost element of SVG documents. #### 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](https://react-pdf.org/styling) | _Object_, _Array_ | _undefined_ | See it in action → * * * ### Line The `` element is used to create a line. #### 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](https://react-pdf.org/svg#presentation-attributes) See it in action → * * * ### Polyline The `` element is used to create any shape that consists of only straight lines (that is connected at several points). #### 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](https://react-pdf.org/svg#presentation-attributes) See it in action → * * * ### 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). #### 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](https://react-pdf.org/svg#presentation-attributes) See it in action → * * * ### 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. #### 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](https://react-pdf.org/svg#presentation-attributes) See it in action → * * * ### Rect The `` element is used to create a rectangle and variations of a rectangle shape. #### 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](https://react-pdf.org/svg#presentation-attributes) See it in action → * * * ### Circle The `` element is used to create a circle. #### 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](https://react-pdf.org/svg#presentation-attributes) See it in action → * * * ### 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. #### 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](https://react-pdf.org/svg#presentation-attributes) See it in action → * * * ### Text The `` element draws a graphics element consisting of text. #### 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](https://react-pdf.org/svg#presentation-attributes) See it in action → * * * ### 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. #### 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](https://react-pdf.org/svg#presentation-attributes) * * * ### 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. #### Valid props This element only includes [Presentation Attributes](https://react-pdf.org/svg#presentation-attributes) See it in action → * * * ### 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 #### 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_ | * * * ### 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 * * * ### ClipPath 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. See it in action → * * * ### LinearGradient The `` element lets authors define linear gradients that can be applied to fill or stroke of graphical elements. #### 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_ | See it in action → * * * ### RadialGradient The `` element lets authors define radial gradients that can be applied to fill or stroke of graphical elements. #### 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_ | | 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_ | See it in action → * * * ### 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. #### 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_ | ← Components Hooks → ![](https://react-pdf.org/images/corner-graphics.png) Generating PDFs in bulk? [Talk to us](https://axxy020tu5c.typeform.com/to/eU21hXDy) --- # React-pdf [Edit](https://github.com/react-pdf/site/blob/master/docs/styling.md) 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() Create a stylesheet. This method expects a valid JS object as only argument (containing as much css definitions as you want) and returns an object that you can pass down to components via the `style` prop import React from 'react'; import { Page, Text, View, Document, StyleSheet } from '@react-pdf/renderer'; const styles = StyleSheet.create({ page: { backgroundColor: 'tomato' }, section: { color: 'white', textAlign: 'center', margin: 30 } }); const doc = ( Section #1 ); ReactPDF.render(doc); See it in action → #### Inline styling There's no need to call `StyleSheet.create` in order to style components. You can also just pass a plain JS object to the `style` prop and react-pdf will get the job done. import React from 'react'; import { Page, Text, View, Document } from '@react-pdf/renderer'; const MyDocument = () => ( Section #1 ); See it in action → #### Mixing both solutions The `style` prop also accepts an Array as value, containing any possible combination of the last two alternatives import React from 'react'; import { Page, Text, View, Document, StyleSheet } from '@react-pdf/renderer'; const styles = StyleSheet.create({ page: { backgroundColor: 'tomato' }, section: { textAlign: 'center', margin: 30 } }); const MyDocument = () => ( Section #1 ); > **Protip:** This can be useful when you want to apply both predefined styles, and styles based on props See it in action → * * * ### 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`: import React from 'react'; import { Page, Text, View, Document, StyleSheet } from '@react-pdf/renderer'; const styles = StyleSheet.create({ section: { width: 200, '@media max-width: 400': { width: 300, }, '@media orientation: landscape': { width: 400, }, } }); const MyDocument = () => ( Section #1 ); See it in action → * * * ### Valid units `pt` _(default. Based on the standard 72 dpi PDF document)_ `in` inches `mm` millimeters `cm` centimeters `%` percentage `vw` viewport/page width `vh` viewport/page height * * * ### Valid CSS properties #### Flexbox * alignContent * alignItems * alignSelf * flex * flexDirection * flexWrap * flexFlow * flexGrow * flexShrink * flexBasis * justifyContent * gap * rowGap * columnGap #### Layout * bottom * display * left * position * right * top * overflow * zIndex #### Dimension * height * maxHeight * maxWidth * minHeight * minWidth * width #### Color * backgroundColor * color * opacity #### Text * fontSize * fontFamily * fontStyle * fontWeight * letterSpacing * lineHeight * maxLines * textAlign * textDecoration * textDecorationColor * textDecorationStyle * textIndent * textOverflow * textTransform #### Sizing/positioning * object-fit * object-position #### Margin/padding * margin * marginHorizontal * marginVertical * marginTop * marginRight * marginBottom * marginLeft * padding * paddingHorizontal * paddingVertical * paddingTop * paddingRight * paddingBottom * paddingLeft #### Transformations * transform:rotate * transform:scale * transform:scaleX * transform:scaleY * transform:translate * transform:translateX * transform:translateY * transform:skew * transform:skewX * transform:skewY * transform:matrix * transformOrigin #### Borders * border * borderColor * borderStyle * borderWidth * borderTop * borderTopColor * borderTopStyle * borderTopWidth * borderRight * borderRightColor * borderRightStyle * borderRightWidth * borderBottom * borderBottomColor * borderBottomStyle * borderBottomWidth * borderLeft * borderLeftColor * borderLeftStyle * borderLeftWidth * borderTopLeftRadius * borderTopRightRadius * borderBottomRightRadius * borderBottomLeftRadius ← Hooks Fonts → ![](https://react-pdf.org/images/corner-graphics.png) Generating PDFs in bulk? [Talk to us](https://axxy020tu5c.typeform.com/to/eU21hXDy) --- # React-pdf [Edit](https://github.com/react-pdf/site/blob/master/docs/hooks.md) 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 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](https://react-pdf.org/advanced#using-the-usepdf-hook) > section * * * ← SVG Images Styling → ![](https://react-pdf.org/images/corner-graphics.png) Generating PDFs in bulk? [Talk to us](https://axxy020tu5c.typeform.com/to/eU21hXDy) --- # React-pdf [Edit](https://github.com/react-pdf/site/blob/master/docs/node.md) Node API -------- ### renderToFile Helper function to render a PDF into a file. #### Usage 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 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 ### renderToStream Helper function to render a PDF into a Node Stream. #### Usage 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 ← Fonts Advanced → ![](https://react-pdf.org/images/corner-graphics.png) Generating PDFs in bulk? [Talk to us](https://axxy020tu5c.typeform.com/to/eU21hXDy) --- # React-pdf [Edit](https://github.com/react-pdf/site/blob/master/docs/fonts.md) 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) . import { StyleSheet, Font } from '@react-pdf/renderer' // Register font Font.register({ family: 'Roboto', src: source }); // Reference font const styles = StyleSheet.create({ title: { fontFamily: 'Roboto' } }) * * * ### `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. 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) See it in action → #### 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: 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: import { Font } from '@react-pdf/renderer' const hyphenationCallback = (word) => { // Return word parts in an array } Font.registerHyphenationCallback(hyphenationCallback); See it in action → #### Disabling hyphenation You can easily disable word hyphenation by just returning the same word as it is passed to the hyphenation callback Font.registerHyphenationCallback(word => [word]); See it in action → * * * ### `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: 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 See it in action → ← Styling Node API → ![](https://react-pdf.org/images/corner-graphics.png) Generating PDFs in bulk? [Talk to us](https://axxy020tu5c.typeform.com/to/eU21hXDy) --- # React-pdf CodePDF const Quixote = () => ( ~ Created with react-pdf ~ Don Quijote de la Mancha Miguel de Cervantes Capítulo I: 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. 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 Belianis 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. Tuvo muchas veces competencia con el cura de su lugar (que era hombre docto graduado en Sigüenza), sobre cuál había sido mejor caballero, Palmerín de Inglaterra o Amadís de Gaula; mas maese Nicolás, barbero del mismo pueblo, decía que ninguno llegaba al caballero del Febo, y que si alguno se le podía comparar, era don Galaor, hermano de Amadís de Gaula, porque tenía muy acomodada condición para todo; que no era caballero melindroso, ni tan llorón como su hermano, y que en lo de la valentía no le iba en zaga. 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. Capítulo II: 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. Mas apenas se vio en el campo cuando le asaltó un pensamiento terrible, y tal, que por poco le hiciera dejar la comenzada empresa; y fue que le vino a la memoria que no era armado caballero, y que, conforme a ley de caballería, ni podía ni debía tomar armas con ningún caballero; y puesto que lo fuera, había de llevar armas blancas, como novel caballero, sin empresa en el escudo, hasta que por su esfuerzo la ganase. Estos pensamientos le hicieron titubear en su propósito; mas pudiendo más su locura que otra razón alguna, propuso de hacerse armar caballero del primero que topase, a imitación de otros muchos que así lo hicieron, según él había leído en los libros que tal le tenían. En lo de las armas blancas, pensaba limpiarlas de manera, en teniendo lugar, que lo fuesen más que un arminio; y con esto se quietó18 y prosiguió su camino, sin llevar otro que aquel que su caballo quería, creyendo que en aquello consistía la fuerza de las aventuras 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. Y era la verdad que por él caminaba; y añadió diciendo: —Dichosa edad y siglo dichoso aquel adonde saldrán a luz las famosas hazañas mías, dignas de entallarse en bronces, esculpirse en mármoles y pintarse en tablas, para memoria en lo futuro. ¡Oh tú, sabio encantador, quienquiera que seas, a quien ha de tocar el ser coronista desta peregrina historia! Ruégote que no te olvides de mi buen Rocinante, compañero eterno mío en todos mis caminos y carreras. Luego volvía diciendo, como si verdaderamente fuera enamorado: —¡Oh princesa Dulcinea, señora deste cautivo corazón! Mucho agravio me habedes fecho en despedirme y reprocharme con el riguroso afincamiento de mandarme no parecer ante la vuestra fermosura. Plégaos, señora, de membraros deste vuestro sujeto corazón, que tantas cuitas por vuestro amor padece. Con estos iba ensartando otros disparates, todos al modo de los que sus libros le habían enseñado, imitando en cuanto podía su lenguaje. Con esto caminaba tan despacio, y el sol entraba tan apriesa y con tanto ardor, que fuera bastante a derretirle los sesos, si algunos tuviera 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({ body: { paddingTop: 35, paddingBottom: 65, paddingHorizontal: 35, }, title: { fontSize: 24, textAlign: 'center', fontFamily: 'Oswald' }, author: { fontSize: 12, textAlign: 'center', marginBottom: 40, }, subtitle: { fontSize: 18, margin: 12, fontFamily: 'Oswald' }, text: { margin: 12, fontSize: 14, textAlign: 'justify', fontFamily: 'Times-Roman' }, image: { marginVertical: 15, marginHorizontal: 100, }, header: { fontSize: 12, marginBottom: 20, textAlign: 'center', color: 'grey', }, pageNumber: { position: 'absolute', fontSize: 12, bottom: 30, left: 0, right: 0, textAlign: 'center', color: 'grey', }, }); ReactPDF.render(); xxxxxxxxxx 1 const Quixote \= () \=> ( 2 3 4 5 ~ Created with react-pdf ~ 6 7 Don Quijote de la Mancha 8 Miguel de Cervantes 9 13 14 Capítulo I: Que trata de la condición y ejercicio del famoso hidalgo D. 15 Quijote de la Mancha 16 17 18 En un lugar de la Mancha, de cuyo nombre no quiero acordarme, no ha 19 mucho tiempo que vivía un hidalgo de los de lanza en astillero, adarga 20 antigua, rocín flaco y galgo corredor. Una olla de algo más vaca que 21 carnero, salpicón las más noches, duelos y quebrantos los sábados, 22 lentejas los viernes, algún palomino de añadidura los domingos, 23 consumían las tres partes de su hacienda. El resto della concluían sayo 24 de velarte, calzas de velludo para las fiestas con sus pantuflos de lo 25 mismo, los días de entre semana se honraba con su vellori de lo más 26 fino. Tenía en su casa una ama que pasaba de los cuarenta, y una sobrina 27 que no llegaba a los veinte, y un mozo de campo y plaza, que así 28 ensillaba el rocín como tomaba la podadera. Frisaba la edad de nuestro 29 hidalgo con los cincuenta años, era de complexión recia, seco de carnes, 30 enjuto de rostro; gran madrugador y amigo de la caza. Quieren decir que 31 tenía el sobrenombre de Quijada o Quesada (que en esto hay alguna 32 diferencia en los autores que deste caso escriben), aunque por 33 conjeturas verosímiles se deja entender que se llama Quijana; pero esto 34 importa poco a nuestro cuento; basta que en la narración dél no se salga 35 un punto de la verdad 36 37 38 Es, pues, de saber, que este sobredicho hidalgo, los ratos que estaba 39 ocioso (que eran los más del año) se daba a leer libros de caballerías 40 con tanta afición y gusto, que olvidó casi de todo punto el ejercicio de 41 la caza, y aun la administración de su hacienda; y llegó a tanto su 42 curiosidad y desatino en esto, que vendió muchas hanegas de tierra de 43 sembradura, para comprar libros de caballerías en que leer; y así llevó 44 a su casa todos cuantos pudo haber dellos; y de todos ningunos le Rendering PDF... You are not rendering a valid document No PDF file specified. React-PDF Repl -------------- 4.2.3 Share Copy Generating PDFs in bulk? [Talk to us](https://axxy020tu5c.typeform.com/to/eU21hXDy) --- # React-pdf [Edit](https://github.com/react-pdf/site/blob/master/docs/advanced.md) 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: import { Document, Page } from '@react-pdf/renderer' const doc = () => ( // something pretty here ); See it in action → #### 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. In this group by default we only find _Image_. See it in action → #### 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: 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_. See it in action → #### 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. import { Document, Page, Text } from '@react-pdf/renderer' const doc = () => ( // fancy things here ); See it in action → #### 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. 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! See it in action → * * * ### 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](https://react-pdf.org/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: 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](https://react-pdf.org/components) ), and can take the form of either a _String_ or a _Bookmark_ type 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_ | * * * ### On the fly rendering `Web only` 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. 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 ``. 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). 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. 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 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 See it in action → * * * ### 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. 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 See it in action → * * * ### 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. Content Padding Margin See it in action → * * * ### 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. If you need more fine-grained control over how words break, you can pass your own callback and handle all that logic by yourself: import { Font } from '@react-pdf/renderer' const hyphenationCallback = (word) => { // Return word syllables in an array } Font.registerHyphenationCallback(hyphenationCallback); You can use the [default hyphenation callback](https://github.com/diegomura/react-pdf/blob/master/packages/textkit/src/engines/wordHyphenation/index.js) as a starting point. > **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](https://react-pdf.org/fonts#registerhyphenationcallback) See it in action → ### Usage with Express.js `node only` 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.')); ### Rendering large documents in the browser If you need to render documents with 30 pages or more in the browser, using react-pdf directly in React can occupy the browser's main thread for a long time. This can lead to unresponsive UI and browsers offering the user to abort the script. To avoid this, you should render large documents inside a web worker. Web workers are executed in separate threads, and therefore do not block the main thread of the browser. This way, the UI can stay responsive while the PDF is being rendered. For an example on how to run react-pdf in a web worker, see this [blog post](https://dev.to/simonhessel/creating-pdf-files-without-slowing-down-your-app-a42) . ← Styling REPL → ![](https://react-pdf.org/images/corner-graphics.png) Generating PDFs in bulk? [Talk to us](https://axxy020tu5c.typeform.com/to/eU21hXDy) ---