### Install React-pdf with npm Source: https://react-pdf.org/ Install the react-pdf package using npm. This is the initial step before creating PDF documents. ```bash npm install @react-pdf/renderer --save ``` -------------------------------- ### Install React-pdf with Yarn Source: https://react-pdf.org/ Install the react-pdf package using Yarn. This is an alternative to npm for package management. ```bash yarn add @react-pdf/renderer ``` -------------------------------- ### Install @react-pdf/math Package Source: https://react-pdf.org/advanced Install the math package using npm. This package is required for rendering LaTeX expressions. ```bash npm install @react-pdf/math ``` -------------------------------- ### Install React-pdf with pnpm Source: https://react-pdf.org/ Install the react-pdf package using pnpm. This is another package manager option. ```bash pnpm add @react-pdf/renderer ``` -------------------------------- ### Install React-pdf with Bun Source: https://react-pdf.org/ Install the react-pdf package using Bun. This is a fast JavaScript runtime and package manager. ```bash bun add @react-pdf/renderer ``` -------------------------------- ### Create a Basic PDF Document with React-pdf Source: https://react-pdf.org/ Defines a simple PDF document component using react-pdf primitives like Page, Text, View, and StyleSheet. This example demonstrates basic document structure and styling. ```jsx 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 ); ``` -------------------------------- ### Custom German Hyphenation Example Source: https://react-pdf.org/advanced An example of registering a custom hyphenation callback for German words using the 'hyphen/de' library. ```javascript import { Font } from "@react-pdf/renderer"; import { hyphenateSync as hyphenateDE } from "hyphen/de"; const hyphenationCallback = (word) => { return hyphenateDE(word).split("\u00AD"); }; Font.registerHyphenationCallback(hyphenationCallback); ``` -------------------------------- ### Force Page Break Source: https://react-pdf.org/advanced Insert a page break before an element by adding the 'break' prop. This ensures the element starts on a new page, useful for separating content sections. ```javascript import { Document, Page, Text } from '@react-pdf/renderer' const doc = () => ( // fancy things here ); ``` -------------------------------- ### Registering a Font with Style and Weight Options Source: https://react-pdf.org/fonts Shows the basic syntax for registering a font, specifying its family name, source, and optionally its style and weight. This is useful for custom fonts not included by default. ```javascript import { Font } from '@react-pdf/renderer' Font.register({ family: 'FamilyName', src: source, fontStyle: 'normal', fontWeight: 'normal', fonts?: [] }); ``` -------------------------------- ### Registering and Referencing a Font Source: https://react-pdf.org/fonts Demonstrates how to register a custom font using Font.register and then reference it in StyleSheet definitions. ```APIDOC ## Registering and Referencing a Font ### Description This example shows how to load a font from a source and assign it a family name for use in your document's styles. ### Method `Font.register(options)` ### Parameters #### Request Body - **family** (string) - Required - Name to which the font will be referenced on styles definition. - **src** (string) - Required - Specifies the source of the font (URL or path). - **fontStyle** (string) - Optional - Specifies to which font style the registered font refers to (normal, italic, oblique). Defaults to 'normal'. - **fontWeight** (string | number) - Optional - Specifies the registered font weight (thin, ultralight, light, normal, medium, semibold, bold, ultrabold, heavy, or a number between 0 and 1000). Defaults to 'normal'. - **fonts** (array) - Optional - An array of font objects to register multiple sources for the same font family at once. ### Request Example ```javascript import { StyleSheet, Font } from '@react-pdf/renderer' // Register font Font.register({ family: 'Roboto', src: source }); // Reference font const styles = StyleSheet.create({ title: { fontFamily: 'Roboto' } }) ``` ``` -------------------------------- ### Registering and Referencing a Custom Font Source: https://react-pdf.org/fonts Demonstrates how to register a custom font using its source and then reference it in your StyleSheet. Ensure the font source is correctly provided. ```javascript import { StyleSheet, Font } from '@react-pdf/renderer' // Register font Font.register({ family: 'Roboto', src: source }); // Reference font const styles = StyleSheet.create({ title: { fontFamily: 'Roboto' } }) ``` -------------------------------- ### Registering a Font with Multiple Sources Source: https://react-pdf.org/fonts Shows how to register multiple font files (e.g., normal, italic, bold) for the same font family using the `fonts` property. ```APIDOC ## Registering a Font with Multiple Sources ### Description This example demonstrates registering multiple font variations (like different styles and weights) for a single font family using the `fonts` array within `Font.register`. ### Method `Font.register(options)` ### Parameters #### Request Body - **family** (string) - Required - Name to which the font will be referenced on styles definition. - **fonts** (array) - Required - An array of font objects, where each object specifies a `src` and optionally `fontStyle` and `fontWeight`. - **src** (string) - Required - Specifies the source of the font (URL or path). - **fontStyle** (string) - Optional - Specifies the font style (normal, italic, oblique). - **fontWeight** (string | number) - Optional - Specifies the font weight (thin, ultralight, light, normal, medium, semibold, bold, ultrabold, heavy, or a number between 0 and 1000). ### Request Example ```javascript Font.register({ family: 'Roboto', fonts: [ { src: source1 }, // font-style: normal, font-weight: normal { src: source2, fontStyle: 'italic' }, { src: source3, fontStyle: 'italic', fontWeight: 700 }, ] }); ``` ``` -------------------------------- ### esbuild Configuration with cjs-shim Source: https://react-pdf.org/compatibility Integrate the 'cjs-shim.ts' into your esbuild build process by specifying it in the 'inject' option to resolve '__dirname is not defined' errors. ```javascript await esbuild.build({ // … inject: ['cjs-shim.ts'], }); ``` -------------------------------- ### Registering Multiple Font Sources for a Family Source: https://react-pdf.org/fonts Illustrates how to register multiple font sources for a single font family using the 'fonts' array. This allows defining different styles (italic) and weights for the same family efficiently. ```javascript Font.register({ family: 'Roboto', fonts: [ { src: source1 }, // font-style: normal, font-weight: normal { src: source2, fontStyle: 'italic' }, { src: source3, fontStyle: 'italic', fontWeight: 700 }, ]}) ``` -------------------------------- ### Create Stylesheet with StyleSheet.create() Source: https://react-pdf.org/styling Use StyleSheet.create() to define a stylesheet object that can be passed to components via the style prop. This is useful for organizing and reusing styles. ```javascript 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); ``` -------------------------------- ### Create Document Destinations and Links Source: https://react-pdf.org/advanced Define navigation destinations using the 'id' prop on an element and link to them using the 'src' prop with a '#' prefix on a Link component. This enables internal document navigation. ```javascript 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 ); ``` -------------------------------- ### Use usePDF Hook in React Source: https://react-pdf.org/hooks Initialize the usePDF hook to access PDF creation functionalities. It returns an instance object and an update function. ```javascript const [instance, update] = usePDF({ document }); ``` -------------------------------- ### Media Queries for Conditional Styling Source: https://react-pdf.org/styling Apply styles conditionally based on document context like width, height, or orientation using media queries within StyleSheet.create(). This is similar to web CSS media queries. ```javascript 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 ); ``` -------------------------------- ### esbuild cjs-shim for React-PDF Source: https://react-pdf.org/compatibility When using esbuild to bundle react-pdf in ESM mode and encountering '__dirname is not defined', use this 'cjs-shim.ts' file to provide global '__dirname' and '__filename'. ```typescript 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); ``` -------------------------------- ### Mixing StyleSheet and Inline Styles Source: https://react-pdf.org/styling Combine predefined styles from StyleSheet.create() with inline styles by passing an array to the style prop. This allows for flexible styling, such as applying prop-based styles to predefined ones. ```javascript 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 ); ``` -------------------------------- ### renderToFile Source: https://react-pdf.org/node Helper function to render a PDF into a file. It takes a React document element and a file path as arguments, and optionally accepts a callback function to be executed after rendering. ```APIDOC ## renderToFile ### Description Helper function to render a PDF into a file. It takes a React document element and a file path as arguments, and optionally accepts a callback function to be executed after rendering. ### Method Asynchronous function (implied by `await` in usage example) ### Parameters #### Arguments - **document** (React Element) - Required - Document's root element to be rendered - **path** (string) - Required - File system path where the document will be created - **callback** (function) - Optional - Function to be called after rendering is finished ### Request Example ```javascript const MyDocument = () => ( React-pdf ); await renderToFile(, `${__dirname}/my-doc.pdf`); ``` ``` -------------------------------- ### Basic Document Structure with React-PDF Source: https://react-pdf.org/repl This snippet shows the fundamental structure of a PDF document using React-PDF, including Document, Page, Text, View, and Image components. It also includes custom components like HR and ChapterHeading. ```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 ( // My document data ); const App = () => (
} fileName="somename.pdf"> {({ blob, url, loading, error }) => loading ? 'Loading document...' : 'Download now!' }
); ``` -------------------------------- ### Chapter Heading Component Source: https://react-pdf.org/repl Renders a chapter heading with a number and title. ```jsx Que trata de la condición y ejercicio del famoso hidalgo D. Quijote de la Mancha ``` -------------------------------- ### Render Inline Math Expressions Source: https://react-pdf.org/advanced Use the `inline` prop on the Math component to render compact equations suitable for embedding within text. Adjust the `height` prop as needed for alignment. ```jsx The equation {"E = mc^2"} is famous. ``` -------------------------------- ### Dynamic Content Rendering with Functions Source: https://react-pdf.org/advanced Render dynamic text or views based on context like page numbers. The render prop accepts a function that receives arguments such as pageNumber and totalPages. Note that for Text components, the render function is called twice. ```javascript import { Document, Page } from '@react-pdf/renderer' const doc = () => ( ( `${pageNumber} / ${totalPages}` )} fixed /> ( pageNumber % 2 === 0 && ( I'm only visible in odd pages! ) )} /> ); ``` -------------------------------- ### Text Content Component Source: https://react-pdf.org/repl Renders standard text content within the document. ```jsx 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. ``` ```jsx 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 ``` -------------------------------- ### Document Component Source: https://react-pdf.org/repl The root component for a PDF document. ```jsx ``` -------------------------------- ### Registering a Hyphenation Callback Source: https://react-pdf.org/fonts Explains how to provide a custom callback function to control word hyphenation behavior. ```APIDOC ## Registering a Hyphenation Callback ### Description This function allows you to define custom logic for how words are broken into parts for hyphenation. ### Method `Font.registerHyphenationCallback(callback)` ### Parameters #### Request Body - **callback** (function) - Required - A function that takes a `word` (string) as input and should return an array of strings representing the parts of the word for hyphenation. ### Request Example ```javascript import { Font } from '@react-pdf/renderer' const hyphenationCallback = (word) => { // Return word parts in an array return word.split('-'); // Example: splitting by hyphen } Font.registerHyphenationCallback(hyphenationCallback); ``` ``` -------------------------------- ### Registering a Custom Hyphenation Callback Source: https://react-pdf.org/fonts Explains how to provide a custom function to control word hyphenation. The callback receives a word and should return an array of its parts. ```javascript import { Font } from '@react-pdf/renderer' const hyphenationCallback = (word) => { // Return word parts in an array } Font.registerHyphenationCallback(hyphenationCallback); ``` -------------------------------- ### React-PDF Document Structure Source: https://react-pdf.org/repl Basic structure for a React-PDF document, including Document, Page, and Text components. ```jsx 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
); ``` -------------------------------- ### Save PDF Document to a File Source: https://react-pdf.org/ Renders the React-pdf document and saves it to a specified file path on the server. Requires the __dirname global variable for path resolution. ```javascript import ReactPDF from '@react-pdf/renderer'; ReactPDF.render(, `${__dirname}/example.pdf`); ``` -------------------------------- ### Render Fixed Component on All Pages Source: https://react-pdf.org/advanced Use the 'fixed' prop to render a component on every page of the document. This is ideal for headers, footers, or page numbers. ```javascript import { Document, Page, View } from '@react-pdf/renderer' const doc = () => ( // fancy things here ); ``` -------------------------------- ### Header Text Component Source: https://react-pdf.org/repl Renders fixed header text on the page. ```jsx Don Quijote de la Mancha ``` -------------------------------- ### View Component Source: https://react-pdf.org/repl A basic View component, often used for layout and structure. ```jsx ``` -------------------------------- ### Render PDF to Buffer using Node API Source: https://react-pdf.org/node Employ `renderToBuffer` to generate a Node.js Buffer from a React PDF document. Buffers are efficient for handling binary data, making this suitable for direct file writing or network transmission. ```javascript const MyDocument = () => ( React-pdf ); const buffer = await renderToBuffer(); ``` -------------------------------- ### renderToString Source: https://react-pdf.org/node Helper function to render a PDF into a string. It accepts a React document element and returns a string representation of the PDF. ```APIDOC ## renderToString ### Description Helper function to render a PDF into a string. It accepts a React document element and returns a string representation of the PDF. ### Method Asynchronous function (implied by `await` in usage example) ### Parameters #### Arguments - **document** (React Element) - Required - Document's root element to be rendered ### Returns - **string** - String representation of PDF document ### Request Example ```javascript const MyDocument = () => ( React-pdf ); const value = await renderToString(); ``` ``` -------------------------------- ### Chapter Image Component Source: https://react-pdf.org/repl Renders an image within a chapter. ```jsx ``` -------------------------------- ### Font.registerEmojiSource Source: https://react-pdf.org/fonts Allows you to specify a CDN URL from which React-PDF can download emoji images. This is necessary because PDF documents do not natively support color emoji fonts. React-PDF handles the embedding of these images. ```APIDOC ## Font.registerEmojiSource ### Description PDF documents do not support color emoji fonts. This function allows you to register a source (like a CDN) from which React-PDF can download emoji images to be embedded in the PDF. This is useful for displaying emojis that would otherwise not render correctly. ### Method `Font.registerEmojiSource(options)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options** (object) - Required - An object containing the configuration for the emoji source. - **format** (string) - Required - The format of the emoji images (e.g., 'png'). - **url** (string) - Required - The URL of the CDN where emoji images can be found. React-PDF recommends using Twemoji. ### Request Example ```javascript import { Font } from '@react-pdf/renderer' Font.registerEmojiSource({ format: 'png', url: 'https://cdnjs.cloudflare.com/ajax/libs/twemoji/14.0.2/72x72/', }); ``` ### Response This method does not return a value. #### Success Response (N/A) N/A #### Response Example (N/A) N/A ### Notes React-PDF requires an internet connection to download emoji images at render time when using this API. ``` -------------------------------- ### Chapter Title Component Source: https://react-pdf.org/repl Renders the chapter title using a Text component. ```jsx {children} ``` -------------------------------- ### Render PDF to File using Node API Source: https://react-pdf.org/node Use `renderToFile` to save a React PDF document to a specified file path. Ensure the document component is correctly defined and the path is valid. ```javascript const MyDocument = () => ( React-pdf ); await renderToFile(, `${__dirname}/my-doc.pdf`); ``` -------------------------------- ### Access PDF Blob Data with BlobProvider Source: https://react-pdf.org/advanced Utilize the BlobProvider component to gain direct access to the document's blob data for various use cases. The component exposes blob, url, loading, and error states. ```javascript 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
; }}
); ``` -------------------------------- ### Title Block Component Source: https://react-pdf.org/repl A container for the main title, author, and a horizontal rule. ```jsx Don Quijote de la Mancha
Miguel de Cervantes
``` -------------------------------- ### Render LaTeX Math Expressions Source: https://react-pdf.org/advanced Import and use the Math component to render LaTeX expressions within your PDF document. Ensure proper escaping for LaTeX special characters. ```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}"} ); ``` -------------------------------- ### Chapter Number Component Source: https://react-pdf.org/repl Renders the chapter number using a Text component with specific styling. ```jsx {number} ``` -------------------------------- ### renderToBuffer Source: https://react-pdf.org/node Helper function to render a PDF into a Node Buffer. It takes a React document element and returns a Buffer representation of the PDF. ```APIDOC ## renderToBuffer ### Description Helper function to render a PDF into a Node Buffer. It takes a React document element and returns a Buffer representation of the PDF. ### Method Asynchronous function (implied by `await` in usage example) ### Parameters #### Arguments - **document** (React Element) - Required - Document's root element to be rendered ### Returns - **Buffer** - Buffer representation of PDF document ### Request Example ```javascript const MyDocument = () => ( React-pdf ); const buffer = await renderToBuffer(); ``` ``` -------------------------------- ### View Component Props Source: https://react-pdf.org/components The View component is a fundamental building block for structuring content. It supports various props for layout, styling, and behavior. ```APIDOC ## View Component ### Description A fundamental component for structuring content, similar to a `div`. ### Props #### Valid Props - **wrap** (_Boolean_) - Optional - Enables/disables page wrapping for the element. Defaults to `true`. - **render** (_Function_) - Optional - Renders dynamic content based on context. - **style** (_Object_ or _Array_) - Optional - Defines view styles. - **debug** (_Boolean_) - Optional - Enables debug mode on the view bounding box. Defaults to `false`. - **fixed** (_Boolean_) - Optional - Renders the component in all wrapped pages. Defaults to `false`. - **hyphenationCallback** (_Function_) - Optional - Specify hyphenation callback at a text level. - **id** (_String_) - Optional - Destination ID to be linked to. - **bookmark** (_String_ or _Bookmark_) - Optional - Attach a bookmark to the element. ``` -------------------------------- ### PDFDownloadLink Component Source: https://react-pdf.org/components The PDFDownloadLink component provides an anchor tag to generate and download PDF documents on the fly. ```APIDOC ## PDFDownloadLink Component `Web only` ### Description Anchor tag to enable generate and download PDF documents on the fly. Refer to on the fly rendering for more information. ``` -------------------------------- ### Note Component Props Source: https://react-pdf.org/components The Note component is designed for displaying annotation notes within the PDF document. ```APIDOC ## Note Component ### Description A React component for displaying a note annotation inside the document. ### Props #### Valid Props - **style** (_Object_ or _Array_) - Optional - Defines view styles. - **children** (_String_) - Optional - Note string content. - **fixed** (_Boolean_) - Optional - Renders component in all wrapped pages. Defaults to `false`. ``` -------------------------------- ### PDF Streaming with Express.js Source: https://react-pdf.org/advanced Stream a generated PDF document directly to an Express.js response. This is efficient for large documents as it avoids loading the entire PDF into memory. ```javascript 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.')); ``` -------------------------------- ### Page Component Source: https://react-pdf.org/repl Represents a single page within the PDF document. ```jsx ``` -------------------------------- ### Inline Styling Source: https://react-pdf.org/styling Apply styles directly to components by passing a plain JavaScript object to the style prop. This is a quick way to style individual elements without creating a separate stylesheet. ```javascript import React from 'react'; import { Page, Text, View, Document } from '@react-pdf/renderer'; const MyDocument = () => ( Section #1 ); ``` -------------------------------- ### Control PDF Rendering with usePDF Hook Source: https://react-pdf.org/advanced Employ the usePDF hook for direct access to document data like blob and URL, and to manage document re-rendering. This hook is ideal for scenarios requiring fine-grained control over when document updates occur. ```javascript 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 ); } ``` -------------------------------- ### Disabling Hyphenation Source: https://react-pdf.org/fonts Demonstrates how to disable word hyphenation by returning the original word from the hyphenation callback. ```APIDOC ## Disabling Hyphenation ### Description To disable automatic word hyphenation, you can register a callback that simply returns the word as is, preventing any splitting. ### Method `Font.registerHyphenationCallback(callback)` ### Parameters #### Request Body - **callback** (function) - Required - A function that takes a `word` (string) and returns an array containing only that word, effectively disabling hyphenation. ### Request Example ```javascript import { Font } from '@react-pdf/renderer' Font.registerHyphenationCallback(word => [word]); ``` ``` -------------------------------- ### Registering Emoji Font Source Source: https://react-pdf.org/fonts Use `Font.registerEmojiSource` to specify the format and URL for emoji images. React-pdf will use this to embed emoji glyphs as images. Requires an internet connection at render time. ```javascript import { Font } from '@react-pdf/renderer' Font.registerEmojiSource({ format: 'png', url: 'https://cdnjs.cloudflare.com/ajax/libs/twemoji/14.0.2/72x72/', }); ``` -------------------------------- ### renderToStream Source: https://react-pdf.org/node Helper function to render a PDF into a Node Stream. It accepts a React document element and returns a PDF document Stream. ```APIDOC ## renderToStream ### Description Helper function to render a PDF into a Node Stream. It accepts a React document element and returns a PDF document Stream. ### Method Asynchronous function (implied by `await` in usage example) ### Parameters #### Arguments - **document** (React Element) - Required - Document's root element to be rendered ### Returns - **Stream** - PDF document Stream ### Request Example ```javascript const MyDocument = () => ( React-pdf ); const stream = await renderToStream(); ``` ``` -------------------------------- ### Render PDF Document in DOM with PDFViewer Source: https://react-pdf.org/ Renders the React-pdf document within a PDFViewer component in the browser's DOM. This allows for interactive viewing of the PDF. ```jsx import React from 'react'; import ReactDOM from 'react-dom'; import { PDFViewer } from '@react-pdf/renderer'; const App = () => ( ); ReactDOM.render(, document.getElementById('root')); ``` -------------------------------- ### Link Component Props Source: https://react-pdf.org/components The Link component is used to create hyperlinks within the document, supporting both internal and external URLs. ```APIDOC ## Link Component ### Description A React component for displaying a hyperlink. Links can be nested inside a Text component or any other valid primitive. ### Props #### Valid Props - **src** (_String_) - Optional - Valid URL or destination ID. ID must be prefixed with `#`. - **href** (_String_) - Optional - Alias of `src`. Valid URL for external links. - **wrap** (_Boolean_) - Optional - Enable/disable page wrapping for the element. Defaults to `true`. - **style** (_Object_ or _Array_) - Optional - Defines view styles. - **debug** (_Boolean_) - Optional - Enables debug mode on the view bounding box. Defaults to `false`. - **fixed** (_Boolean_) - Optional - Render component in all wrapped pages. Defaults to `false`. - **hitSlop** (_Number_ or _Object_ `{ top, bottom, left, right }`) - Optional - Expands the clickable area beyond the visible bounds of the link. - **bookmark** (_String_ or _Bookmark_) - Optional - Attach bookmark to element. ``` -------------------------------- ### Next.js Configuration for React-PDF Source: https://react-pdf.org/compatibility If encountering a 'TypeError: ba.Component is not a constructor' with Next.js App Router before version 14.1.1, update your Next.js config to include '@react-pdf/renderer' in serverComponentsExternalPackages. ```javascript const nextConfig = { // … experimental: { // … serverComponentsExternalPackages: ['@react-pdf/renderer'], }, }; ``` -------------------------------- ### Imperatively Generate PDF Blob Source: https://react-pdf.org/advanced Obtain PDF blob data imperatively using the pdf function, which is useful for non-React frontends. This method allows for direct PDF generation without React component rendering. ```javascript import { pdf, Document, Page } from '@react-pdf/renderer'; const MyDoc = ( // My document data ); const blob = pdf(MyDoc).toBlob(); ``` -------------------------------- ### Render PDF Document to a Stream Source: https://react-pdf.org/ Renders the React-pdf document to a stream, which is useful for server-side processing or sending the PDF data over a network. ```javascript import ReactPDF from '@react-pdf/renderer'; ReactPDF.renderToStream(); ``` -------------------------------- ### Render PDF to String using Node API Source: https://react-pdf.org/node Utilize `renderToString` to convert a React PDF document into its string representation. This is useful for scenarios where the PDF content needs to be transmitted or stored as text. ```javascript const MyDocument = () => ( React-pdf ); const value = await renderToString(); ``` -------------------------------- ### Render PDF to Stream using Node API Source: https://react-pdf.org/node Leverage `renderToStream` to create a Node.js readable stream from a React PDF document. Streams are ideal for processing large documents or when piping data through a pipeline. ```javascript const MyDocument = () => ( React-pdf ); const stream = await renderToStream(); ``` -------------------------------- ### Chapter Rule Component Source: https://react-pdf.org/repl Renders a horizontal rule for visual separation within a chapter. ```jsx ``` -------------------------------- ### Disabling Hyphenation Source: https://react-pdf.org/fonts Demonstrates how to disable word hyphenation by implementing a hyphenation callback that simply returns the original word. This ensures words are not broken. ```javascript Font.registerHyphenationCallback(word => [word]); ```