- 8 Dependencies
- 803 Dependents
- 144 Versions
Display PDFs in your React app as easily as if they were images.
This package is used to display existing PDFs. If you wish to create PDFs using React, you may be looking for @react-pdf/renderer .
- Install by executing npm install react-pdf or yarn add react-pdf .
- Import by adding import { Document } from 'react-pdf' .
- Use by adding <Document file="..." /> . file can be a URL, base64 content, Uint8Array, and more.
- Put <Page /> components inside <Document /> to render pages.
A minimal demo page can be found in sample directory.
Online demo is also available!
![](http://academicwritinghelp.pw/777/templates/cheerup1/res/banner1.gif)
Before you continue
React-PDF is under constant development. This documentation is written for React-PDF 7.x branch. If you want to see documentation for other versions of React-PDF, use dropdown on top of GitHub page to switch to an appropriate tag. Here are quick links to the newest docs from each branch:
Getting started
Compatibility, browser support.
React-PDF supports all modern browsers. It is tested with the latest versions of Chrome, Edge, Safari, Firefox, and Opera.
The following browsers are supported out of the box in React-PDF v9:
- Chrome ≥119
- Safari ≥17.4
- Firefox ≥121
You may extend the list of supported browsers by providing additional polyfills (e.g. for Array.prototype.at , Promise.allSettled or Promise.withResolvers ) and either configuring your bundler to transpile pdfjs-dist and using legacy PDF.js worker .
If you need to support older browsers, you will need to use React-PDF v6 or earlier.
To use the latest version of React-PDF, your project needs to use React 16.8 or later.
If you use an older version of React, please refer to the table below to a find suitable React-PDF version.
React-PDF may be used with Preact.
Installation
Add React-PDF to your project by executing npm install react-pdf or yarn add react-pdf .
If you use Next.js without Turbopack enabled, add the following to your next.config.js :
If you use Next.js with Turbopack enabled, add empty-module.ts file:
and add the following to your next.config.js :
Configure PDF.js worker
For React-PDF to work, PDF.js worker needs to be provided. You have several options.
Import worker (recommended)
For most cases, the following example will work:
[!NOTE] In Next.js: Using App Router, make sure to add 'use client'; to the top of the file. Using Pages Router, make sure to disable SSR when importing the component you're using this code in.
[!NOTE] pnpm requires an .npmrc file with public-hoist-pattern[]=pdfjs-dist for this to work.
For Parcel 2, you need to use a slightly different code:
Copy worker to public directory
You will have to make sure on your own that pdf.worker.mjs file from pdfjs-dist/build is copied to your project's output folder.
For example, you could use a custom script like:
Use external CDN
Legacy pdf.js worker.
If you need to support older browsers, you may use legacy PDF.js worker. To do so, follow the instructions above, but replace /build/ with legacy/build/ in PDF.js worker import path, for example:
Here's an example of basic usage:
Check the sample directory in this repository for a full working example. For more examples and more advanced use cases, check Recipes in React-PDF Wiki .
Support for annotations
If you want to use annotations (e.g. links) in PDFs rendered by React-PDF, then you would need to include stylesheet necessary for annotations to be correctly displayed like so:
Support for text layer
If you want to use text layer in PDFs rendered by React-PDF, then you would need to include stylesheet necessary for text layer to be correctly displayed like so:
Support for non-latin characters
If you want to ensure that PDFs with non-latin characters will render perfectly, or you have encountered the following warning:
then you would also need to include cMaps in your build and tell React-PDF where they are.
Copying cMaps
First, you need to copy cMaps from pdfjs-dist (React-PDF's dependency - it should be in your node_modules if you have React-PDF installed). cMaps are located in pdfjs-dist/cmaps .
Add vite-plugin-static-copy by executing npm install vite-plugin-static-copy --save-dev or yarn add vite-plugin-static-copy --dev and add the following to your Vite config:
Add copy-webpack-plugin by executing npm install copy-webpack-plugin --save-dev or yarn add copy-webpack-plugin --dev and add the following to your Webpack config:
Other tools
If you use other bundlers, you will have to make sure on your own that cMaps are copied to your project's output folder.
Setting up React-PDF
Now that you have cMaps in your build, pass required options to Document component by using options prop, like so:
[!NOTE] Make sure to define options object outside of your React component, and use useMemo if you can't.
Alternatively, you could use cMaps from external CDN:
Support for standard fonts
If you want to support PDFs using standard fonts (deprecated in PDF 1.5, but still around), ot you have encountered the following warning:
then you would also need to include standard fonts in your build and tell React-PDF where they are.
Copying fonts
First, you need to copy standard fonts from pdfjs-dist (React-PDF's dependency - it should be in your node_modules if you have React-PDF installed). Standard fonts are located in pdfjs-dist/standard_fonts .
If you use other bundlers, you will have to make sure on your own that standard fonts are copied to your project's output folder.
Now that you have standard fonts in your build, pass required options to Document component by using options prop, like so:
Alternatively, you could use standard fonts from external CDN:
Loads a document passed using file prop.
Displays a page. Should be placed inside <Document /> . Alternatively, it can have pdf prop passed, which can be obtained from <Document /> 's onLoadSuccess callback function, however some advanced functions like rendering annotations and linking between pages inside a document may not be working correctly.
Displays an outline (table of contents). Should be placed inside <Document /> . Alternatively, it can have pdf prop passed, which can be obtained from <Document /> 's onLoadSuccess callback function.
Displays a thumbnail of a page. Does not render the annotation layer or the text layer. Does not register itself as a link target, so the user will not be scrolled to a Thumbnail component when clicked on an internal link (e.g. in Table of Contents). When clicked, attempts to navigate to the page clicked (similarly to a link in Outline). Should be placed inside <Document /> . Alternatively, it can have pdf prop passed, which can be obtained from <Document /> 's onLoadSuccess callback function.
Props are the same as in <Page /> component, but certain annotation layer and text layer-related props are not available:
- customTextRenderer
- onGetAnnotationsError
- onGetAnnotationsSuccess
- onGetTextError
- onGetTextSuccess
- onRenderAnnotationLayerError
- onRenderAnnotationLayerSuccess
- onRenderTextLayerError
- onRenderTextLayerSuccess
- renderAnnotationLayer
- renderForms
- renderTextLayer
On top of that, additional props are available:
Useful links
- React-PDF Wiki
The MIT License.
This project wouldn't be possible without the awesome work of Niklas Närhinen who created its original version and without Mozilla, author of pdf.js . Thank you!
Thank you to all our sponsors! Become a sponsor and get your image on our README on GitHub.
Thank you to all our backers! Become a backer and get your image on our README on GitHub.
Top Contributors
Thank you to all our contributors that helped on this project!
Package Sidebar
npm i react-pdf
Git github.com/wojtekmaj/react-pdf
github.com/wojtekmaj/react-pdf#readme
Downloads Weekly Downloads
Unpacked size, total files, last publish, collaborators.
Advisory boards aren’t only for executives. Join the LogRocket Content Advisory Board today →
![pdf export react LogRocket blog logo](https://blog.logrocket.com/wp-content/themes/logrocket/assets/logrocket-logo.png)
- Product Management
- Solve User-Reported Issues
- Find Issues Faster
- Optimize Conversion and Adoption
- Start Monitoring for Free
Generating PDFs in React with react-pdf
![pdf export react pdf export react](https://blog.logrocket.com/wp-content/uploads/2021/05/Hussain-Arif-Author.jpeg?w=131&h=131&crop=1)
Editor’s note : This article was updated by David Omotayo on 11 March 2024 to outline some example use cases for generating PDFs in React, discuss the pros and cons of implementing this feature from scratch, update the react-pdf library’s stats, and compare react-pdf to other libraries.
![pdf export react Generating Pdfs In React With The React Pdf Library](https://blog.logrocket.com/wp-content/uploads/2021/12/Generating-PDFs-react-pdf.png)
There are several reasons why you might want to incorporate a PDF document generator feature in your application. Fortunately, the React ecosystem provides a wealth of tools offering simple ways to generate PDF documents directly within React applications.
One such tool is the react-pdf library, which simplifies the PDF generation process within your React project. In this article, we’ll explore why you might want to implement a PDF document generation feature, the fundamentals of react-pdf, and advanced concepts. We’ll also compare react-pdf to other libraries .
Why generate PDFs in a React application?
There are many use cases for a PDF generator feature in a React application, such as offline access to the application’s content, report generation, and more. However, the most common use case for such a feature in modern apps is data exports — for example, invoices or brochures.
To put it into perspective, consider a thriving online business. Every sale means generating an invoice, a process that can quickly become tedious. In order to create a receipt for each customer, you would need to follow steps such as:
- Open your word processor and paste the user’s personal information
- Write the user’s purchases in a table and calculate the total
- Download this file and convert it to PDF format
- Email this document to the user
Sure, that might work. But consider this: what if the business get hundreds of customers in a single day? This situation could result in a substantial waste of time and energy, as the same process would need to be repeated for each customer. So, how do we mitigate this problem?
The best way to solve this issue is to automate this operation by using an API. This is where react-pdf and other similar libraries comes in.
Building a PDF generator from scratch vs. using a library
While building a PDF generator from the ground up is technically possible, it’s crucial to weigh the pros and cons before diving in. Let’s explore both approaches to see which aligns better with your project goals.
Pros of building from scratch include:
- Valuable learning experience : The process itself can be an excellent learning opportunity, deepening your understanding of PDF generation and potentially other related technologies
- Customization : You have complete control over every aspect of the generator, allowing you to tailor features, functionalities, and design to your exact needs. This can be valuable for highly specialized use cases
However, crafting a PDF document generator from the ground up can be tedious and time-consuming. You would need to consider implementing the following features:
- Support for various content types : Enable the inclusion of various content types such as text, images, tables, and charts within the PDF documents
- Integration with existing libraries or frameworks : Offer compatibility and integration with other React libraries or frameworks, allowing you to leverage additional functionalities if needed
- Customization options : Flexibility to customize the appearance and layout of the PDF documents according to specific requirements, including headers, footers, page numbering, and margins
- Cross-browser compatibility : Ensure compatibility with major web browsers and guaranteeing consistent rendering of PDF documents across different platforms and devices
- Performance optimization : Optimize performance to efficiently generate PDF documents, especially when dealing with large datasets or complex content structures
- Maintenance burden : Beyond the initial development effort, maintaining a custom PDF generator requires ongoing upkeep. Bug fixes, compatibility updates, and potential security vulnerabilities all become your responsibility.
As you can tell, this can be quite tedious. Additionally, beyond the initial development effort, maintaining a custom PDF generator requires ongoing upkeep. Bug fixes, compatibility updates, and potential security vulnerabilities all become your responsibility.
Although the customization and learning experience can be valuable, the time investment and ongoing maintenance burden can be significant. Using a library like react-pdf relieves you of the burden of implementing all these features, allowing you to focus on the core logic of your application.
Installing react-pdf
To install the react-pdf package, run the following terminal command:
Simple usage of react-pdf
The following block of code renders a basic PDF document in the browser:
In this code:
- The StyleSheet module allows developers to apply CSS code on their PDF documents. Here, we are telling React to change the background color and the font color of our pages
- Furthermore, in the viewer object, we are using the width and height properties. As a result, this will tell react-pdf that we want the browser’s PDF viewer to take up all of the space on the page
- As the name suggests, the PDFViewer component will render a PDF viewer on the browser
Let’s test it out! As the next step, render the BasicDocument component to the DOM like so:
You should see the following:
![pdf export react Demo Of A Simple Pdf Viewer Built With React Pdf](https://blog.logrocket.com/wp-content/uploads/2021/12/img1-Demo-simple-PDF-viewer.png)
We can even reduce the viewer’s available space:
In this snippet, we restricted the viewport’s width and height properties. This will decrease their available sizes on the page:
![pdf export react Pdf Viewer With Restricted Width And Height Properties](https://blog.logrocket.com/wp-content/uploads/2021/12/img2-PDF-viewer-restricted-width-height-properties.png)
Fundamental components of the react-pdf package
The react-pdf library offers various components we can display in our generated PDF. Let’s discuss and demonstrate these components now.
Embedding links
We can display anchor links using the Link component . This is handy for cases where you want to redirect the user to a website:
Here, we are assigning the src prop to Facebook’s website. When the user clicks on this piece of text, the app will redirect them to the page:
Displaying annotations
To attach annotations in your document, use the Note component . One critical use case for this element is when you need to display comments in a file:
Hovering over this annotation will display the text we set:
Displaying graphics in a Canvas
The Canvas component lets users draw content on the page. This is suitable for displaying simple diagrams and logos in SVG format.
This code snippet renders a triangle on the page:
In the above snippet, we used the Canvas component to display a diagram. The paint prop is a callback function. One of its parameters is a painterObject argument, which gives us access to drawing methods:
![pdf export react Displaying Graphics Created In A Canvas On A Generated Pdf](https://blog.logrocket.com/wp-content/uploads/2021/12/img5-Displaying-graphics-canvas-PDF.png)
Displaying SVG images
react-pdf also bundles an SVG component to render SVG diagrams . Just like Canvas , we can use this for rendering simple diagrams.
This piece of code renders a line on the page:
Here, we used Line to render a line in the document . Notice that Line is a child of the Svg component.
![pdf export react Displaying Svgs In A Pdf: Rendering A Line](https://blog.logrocket.com/wp-content/uploads/2021/12/img6-Displaying-SVGs-PDF-render-line.png)
We can also use the Polygon component to render closed shapes like so:
The points prop accepts a dataset of coordinates. This will help the app render the graphic:
Rendering JPG or PNG photos
The Image component gives us the ability to insert images over the network or on a local disk. This is great for displaying complex diagrams or screenshots.
This block of code renders a 500 by 500 pixel image on the PDF:
The src prop contains the source URL of the image that we want to render:
![pdf export react Rendering Images In A Pdf](https://blog.logrocket.com/wp-content/uploads/2021/12/img8-Render-images-PDF.png)
Advanced react-pdf concepts
Now that we’ve gone through the fundamentals, let’s discuss some advanced concepts related to using react-pdf to generate PDFs in a React project.
Using flexboxes
Just like CSS, react-pdf lets developers use the flex property, which allows for responsive design. This is handy for cases where you want your documents to scale up or down depending on the device’s screen size:
In this piece of code, we used the flex property on both of our View components. This means that half the page will have a background color of black and the other half will have a pink colored background:
![pdf export react Using Flexboxes In A Pdf](https://blog.logrocket.com/wp-content/uploads/2021/12/img9-Using-flexboxes-PDF.png)
Page breaks
Page breaks are useful for ensuring that a certain element will always show up on the top of the page. We can enable page breaks via the break prop like so:
The result will appear as shown below:
Dynamic page content
With react-pdf, we can render dynamic text using the render prop of the Text component like so:
Here, the render prop has two arguments:
- pageNumber : the current index of the page
- totalPages : the total number of pages that this document contains
We are displaying both of their values to the client:
Note that the render function is executed twice for <Text /> elements: once for layout on the page wrapping process, and again after it knows how many pages the document will have. Therefore, use it in cases where app performance is not a problem.
We can also use the render prop on our View element:
Other React PDF libraries to consider
The react-pdf library is just one of the various tools available in the React ecosystem that you can use to generate, render, annotate, or style PDF documents in a React application. Let’s explore other tools that you can use either in place of or alongside the react-pdf library and discuss their unique features and the ideal use cases.
wojtekmaj/react-pdf
At the top of the list is the wojtekmaj/react-pdf package , an easy-to-use PDF reader that enables you to display PDF documents in your React application. The package is designed solely for displaying or rendering PDF documents, making it suitable for use alongside a PDF generator such as the react-pdf package.
wojtekmaj/react-pdf has excellent community support and undergoes constant updates. Additionally, it boasts over 8K+ stars on Github and 900K+ weekly downloads on npm. With such popularity, you can be assured that it is suitable for use in your applications.
![pdf export react pdf export react](https://blog.logrocket.com/wp-content/uploads/2022/11/Screen-Shot-2022-09-22-at-12.50.47-PM.png)
Over 200k developers use LogRocket to create better digital experiences
![pdf export react pdf export react](https://blog.logrocket.com/wp-content/uploads/2022/08/rocket-button-icon.png)
Features of the wojtekmaj/react-pdf library:
- Multiple rendering methods
- Text selection
- Annotations
Quickstart command:
react-pdf-highlighter
react-pdf-highlighter is a lightweight PDF annotation library built on the PDF.js package by Mozilla. You can use this package alongside other libraries that generate or render PDF documents (such as react-pdf) by integrating annotation features such as highlighting text in PDF documents after generating them.
The react-pdf-highlighter package undergoes regular updates and has 900+ stars on GitHub and 5K+ weekly downloads on npm.
Features of react-pdf-highlighter :
- Text and rectangular highlights
- Independent highlight data format
- Custom events and interactions
react-pdf-tailwind
react-pdf-tailwind is not exactly a PDF generator or renderer. It’s more of a utility tool that allows you to style PDF documents created with libraries such as the react-pdf library using Tailwind utility classes.
Since it’s built on Tailwind, it undergoes constant updates. It has over 400 stars on GitHub and 6K+ weekly downloads on npm. The react-pdf-tailwind library is basically a wrapper for Tailwind, so it doesn’t have any distinct features other than to style PDF documents using Tailwind utility classes.
react-print-pdf
react-print-pdf is an across-the-board solution for creating PDF documents in a React application. Unlike other solutions, react-print-pdf gives you full control over your document’s layout. You can design complex and customized layouts with features like footnotes, headers, margins, and more.
This open source package has good community support, undergoes constant updates, and has over 400+ stars on GitHub.
Features of react-print-pdf:
- Latex support
- Tailwind integration
- Markdown support
- Display dynamic values
In this article, we covered the fundamentals of the react-pdf library. Not only is it secure and robust, but it is also lightweight, thus bringing performance to the table.
Thank you so much for reading! Happy coding!
Get set up with LogRocket's modern React error tracking in minutes:
- Visit https://logrocket.com/signup/ to get an app ID
Install LogRocket via npm or script tag. LogRocket.init() must be called client-side, not server-side
Share this:
- Click to share on Twitter (Opens in new window)
- Click to share on Reddit (Opens in new window)
- Click to share on LinkedIn (Opens in new window)
- Click to share on Facebook (Opens in new window)
![pdf export react pdf export react](https://blog.logrocket.com/wp-content/uploads/2022/06/footer-cta-dots-left.png)
Stop guessing about your digital experience with LogRocket
Recent posts:.
![pdf export react Biome Adoption Guide: Overview, Examples, And Alternatives](https://blog.logrocket.com/wp-content/uploads/2024/05/Biome-adoption-guide-Overview-examples-alternatives.png?w=420)
Biome adoption guide: Overview, examples, and alternatives
Biome combines linters and formatters into one tools, helping developers write better code faster and with less setup and configuration.
![pdf export react pdf export react](https://blog.logrocket.com/wp-content/uploads/2022/02/pelumi-akintokun.jpg?w=150&h=150&crop=1)
React Native layout management with Yoga 3.0
Explore layout management in your React Native apps with the latest release of React Native v0.74 and Yoga 3.0.
![pdf export react pdf export react](https://blog.logrocket.com/wp-content/uploads/2021/04/andrew-baisden.jpeg?w=150&h=150&crop=1)
A guide to JavaScript parser generators
Explore three JavaScript parser generator libraries and the benefits of creating custom parsers for specific project needs.
![pdf export react pdf export react](https://blog.logrocket.com/wp-content/uploads/2022/04/github-profile-image.png?w=150&h=150&crop=1)
Using Rust and Axum to build a JWT authentication API
Learn to build a basic JWT authentication system with Rust and Axum, including setting up the routes, handlers, and the middleware system.
3 Replies to "Generating PDFs in React with react-pdf"
What is better jsPdf or react-pdf renderer!?
i think React-pdf is better.
and what then? Do I have to generate pdf using browser?
Leave a Reply Cancel reply
![pdf export react PureCode](https://blogs.purecode.ai/blogs/wp-content/uploads/2024/01/pc-latest-logo.png)
- UI Elements
![pdf export react pdf export react](https://purecode.ai/blogs/wp-content/uploads/2024/01/pc-latest-logo.png)
Type to generate UI components from text
Browse thousands of MUI, Tailwind, React components that are fully customizable and responsive.
- 14 Feb 2024
- 10 min read
React PDF: A Step-by-Step Guide on How to Generate PDFs
In this step-by-step guide, we delve into the world of React PDF, exploring how to render and generate dynamic Portable Document Format (PDF) files within a React application.
By the conclusion of this article, you will acquire the knowledge needed to develop a PDF generator, as demonstrated below (See the live demo here ).
The article provides a comprehensive breakdown of various methods and third-party libraries, including but not limited to react-pdf, react-pdf-viewer, React PDF (Renderer), and PDFme.
Whether you need to display an existing document file in your React application or create a new one from scratch, this guide has got you covered.
Let’s dive in!
What is a PDF document?
A PDF (Portable Document Format) is a universal file format developed by Adobe. It maintains the integrity of a document’s formatting, fonts, images, and layout, irrespective of the software or hardware used to open or print it.
PDF files, which can house a combination of text and images, can be generated from a variety of sources, including word processors, desktop publishing applications, or even scanned documents.
Working with PDF documents in React
Working with PDFs in React can involve creating a document using code or displaying an existing PDF document within a codebase. This is typically accomplished through third-party libraries, as the functionality is not readily available in standard web APIs.
Give Purecode AI a try today to instantly generate thousands of customizable, styled Bootstrap and JavaScript components to accelerate your web development projects.
Setting up React Application
We’re going to make use of Next.js, a React framework, follow the guide below to set up a Next.js Application.
Step 1: Run the command below in your terminal to bootstrap a new Next.js app, called pdf-app-playground.
Step 2: Select the options below from the terminal prompts and wait for the installation to be completed.
![pdf export react pdf export react](https://blogs.purecode.ai/blogs/wp-content/uploads/2024/02/5cbccd23-2c9c-4c60-994b-ad7e83170817.png)
Then, Step 3: After a successful installation, run the command below to navigate into the newly created folder.
Step 4: Open up the directory in your preferred code editor. If you’re using Visual Studio Code (VSCode), you can easily open the folder by entering the command below in your terminal:
Step 5: Start your server by running the following command in your terminal:
After successfully starting the server, it will be accessible on port http://localhost:3000 or any available port on your computer.
Your screen should display a webpage similar to the one shown below:
![pdf export react pdf export react](https://blogs.purecode.ai/blogs/wp-content/uploads/2024/02/99828934-9e54-4e62-b344-c075412b28f7.png)
Step 6: Remove other CSS declarations and update your globals.css file with the following.
Step 7: Update the /page.tsx with the following code:
Upon successful implementation, your browser should render an output that resembles the following example:
![pdf export react pdf export react](https://blogs.purecode.ai/blogs/wp-content/uploads/2024/02/8ad49e97-fc41-4469-bc9b-62638d43b182.png)
As we progress through this article, we will be developing individual pages corresponding to each route button. These pages will be designed to showcase the specific functionality associated with their respective buttons.
Rendering a PDF file in React
Rendering a PDF file within a React application opens up a realm of possibilities, allowing developers to seamlessly integrate rich and dynamic PDF content into their web experiences.
We’ll explore different ways of rendering PDFs in a React application
Using an Iframe Tag
The easiest method for rendering a PDF in any front-end project is by using the iframe tag. We can display a format file using the JSX iframe tag in React by following the steps below.
1: Add a pdf file to your public folder. You can download one from here.
2: Create a new view-pdf-using-iframe folder inside the app folder.
3: Create a new page.tsx file inside the new folder with the following code.
Step 4: Click the “View PDF using Iframe” button and you should be redirected to the PDF page as demonstrated below.
You can find the completed code for this article in this repository .
Here are some disadvantages of using an iframe tag to render PDF files:
React Packages for Rendering PDF files in React
In this section, we’ll explore some dedicated React packages that offer advanced features and functionalities for rendering files, providing more versatility and customization options compared to the traditional iframe tag.
react-pdf is a popular library in the React ecosystem that allows developers to render files within React applications. It provides components and utilities to easily display, navigate, and interact with PDF documents using components.
This library enables seamless integration of format files into React-based projects, offering features like page navigation, zooming, and rendering text and images from format file documents.
React-pdf Installation
Step 1: Run the command below to install the react-pdf package in your project.
Step 2: Since we’re using Next.js, update your next.config.js file with the webpack settings below.
React-pdf Usage
Step 1: Create a new view-pdf-using-react-pdf folder in the app folder
Step 2: Create a new page.tsx file inside the new folder with the following code.
Then, Step 3: Click the “View PDF using React PDF” button and you should be redirected to the PDF page as demonstrated below.
The code is already compatible with multi-page PDFs. Simply replace the current PDF file URL with a multi-page one, and it should function as demonstrated below.
React-pdf-viewer
react-pdf-viewer is a versatile library designed to render and interact with PDF documents within applications. It offers a wide range of features including displaying PDF files, navigating through pages, zooming in and out, searching for text, and accessing annotations.
![pdf export react pdf export react](https://blogs.purecode.ai/blogs/wp-content/uploads/2024/02/a5bb0abe-29e1-4bb7-a953-570ccd6f908e.png)
This library provides developers with customizable components and hooks, enabling seamless integration of PDF viewing functionality into their React projects while offering a smooth and intuitive user experience for handling documents.
Discover more about the powerful installation process and the versatile basic usage of react-pdf-viewer.
PSPDFKit is a comprehensive PDF SDK (Software Development Kit) that enables developers to integrate powerful PDF functionality into their applications. It offers a wide range of features for viewing, annotating, editing, and processing PDF documents across various platforms and devices.
![pdf export react pdf export react](https://blogs.purecode.ai/blogs/wp-content/uploads/2024/02/289526bb-1307-4985-b078-4fdd7bb88ad7.png)
PSPDFKit provides developers with a robust set of tools and APIs to customize and extend PDF capabilities within their applications, ensuring a seamless and efficient user experience for working with PDF
Learn more about the PSPDFKit guide and its features by visiting here .
Creating a PDF file in React
Creating a PDF file in React can be accomplished by leveraging a variety of libraries that have been specifically designed to handle file generation and manipulation within the framework. Two popular options among these libraries are React PDF (Renderer) and PDFme, which we’ll discuss in the next sections.
React Packages for Creating PDF files in React
Below, we’ll delve into exploring a selection of packages specifically designed for generating PDF files. These packages offer a range of features and capabilities to help developers efficiently generate PDF documents within their React applications.
By leveraging these libraries, developers can ensure a seamless and user-friendly experience when working with PDF files, ultimately enhancing the overall functionality of their applications.
React PDF (Renderer)
React PDF (Renderer) is a robust tool that allows you to generate PDF files directly from your React components. You can define the structure and style of your document using familiar syntax, and the library will convert it into a PDF file.
React PDF (Renderer) Installation
Step 1: Run the command below in your terminal to install react-pdf renderer in your app.
React PDF (Renderer) Usage
Step 1: Create a new create-pdf-using-react-pdf-renderer folder in the app folder.
From the code above, we create a component named PDFCreatorPage that allows users to input their details, generates a document based on the input, and provides a download link for the generated PDF.
Step 4: Click the “Create PDF using React PDF renderer” button and you should be redirected to a page where you can enter some data for the pdf as demonstrated below.
Steps in the demo:
1: Fill out the form fields and select the “Generate PDF” button.
2: You will be directed to the PDF view of the completed form.
3: Click the “Download PDF file” link to open the PDF in your preferred PDF application.
You can find the completed code for this section in this repository and see the live demo here .
PDFme is a free and open-source PDF generator library written in TypeScript. It includes a React-based UI template editor called Designer, which allows users to easily create and modify PDF templates.
![pdf export react pdf export react](https://blogs.purecode.ai/blogs/wp-content/uploads/2024/02/46c8654f-05ea-4c21-afec-a6b2a67eb147.png)
The library is designed to be fast and versatile, capable of generating PDFs with no complex operations required.
Additionally, PDF templates are represented as structured JSON data, making them easy to understand and work with. The library can be used both in Node.js and in web browsers, and it offers features such as text, image, and barcode generation. PDFme is developed by the community and is licensed under the MIT license.
Discover more about the PDFme guide and its extensive features by visiting the Getting Started documentation.
Wrapping Up React PDF
In conclusion, working with PDF files in React is a versatile and necessary skill for many web applications. Whether you’re rendering existing PDFs with libraries like react-pdf and react-pdf-viewer, or creating dynamic ones with React PDF (Renderer) and PDFme, there’s a range of tools at your disposal.
Each library offers unique features and capabilities, but all share the common goal of making PDF manipulation more accessible.
By understanding how to use these tools, you can enhance your web applications and provide more value to your users.
Check out Purecode AI !
I recommend you try out Purecode AI , an AI tool that can generate custom HTML, CSS, and JavaScript components. Here are some of its features:
- It uses an AI assistant to generate thousands of responsive pre-made components for you.
- The components come with default styling using CSS, Tailwind CSS, or your own custom styles so you can match your brand’s design.
- You can easily customize the generated components to suit your specific needs – change colors, spacing, paddings, margins, etc.
- It generates both the HTML markup and CSS styles for the components, saving you development time.
- It also includes some JavaScript functionality within the components to make them interactive
Share this:
- Click to share on Facebook (Opens in new window)
- Click to share on X (Opens in new window)
- Click to share on LinkedIn (Opens in new window)
- Click to share on Reddit (Opens in new window)
- Click to share on Twitter (Opens in new window)
Ayodele Samuel Adebayo
![pdf export react pdf export react](https://blogs.purecode.ai/blogs/wp-content/uploads/2024/03/CRA-alternative-1.png)
Top Create React App Alternative Solutions for Improved Workflows
![pdf export react pdf export react](https://blogs.purecode.ai/blogs/wp-content/uploads/2024/03/react-cheat-sheet-23.png)
Enhancing Your React Slider for A Remarkable User Experience
![pdf export react pdf export react](https://blogs.purecode.ai/blogs/wp-content/uploads/2024/03/react-cheat-sheet-22.png)
Top Picks for React CMS: Better Your Development
![pdf export react pdf export react](https://v1.react-pdf.org/images/logo.png)
React renderer for creating PDF files on the browser, mobile and server.
![pdf export react pdf export react](https://v1.react-pdf.org/images/document-graphic.png)
1. Install React and react-pdf
Starting with react-pdf is extremely simple.
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:
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 three different environments: web , server and mobile (under development) . The process is essentially the same, but catered to needs of each environment.
![](http://academicwritinghelp.pw/777/templates/cheerup1/res/banner1.gif)
Save in a file
Render in dom, render in mobile.
In progress...
4. Have fun!
Maybe the most important step — make use of all react-pdf capabilities to create beautiful and awesome documents!
![pdf export react pdf export react](https://v1.react-pdf.org/images/corner-graphics.png)
![pdf export react DEV Community](https://dev-to-uploads.s3.amazonaws.com/uploads/logos/resized_logo_UQww2soKuUsjaOGNB38o.png)
DEV Community
![pdf export react Nero Adaware](https://media.dev.to/cdn-cgi/image/width=50,height=50,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F46239%2F761e437e-be91-4883-a547-f93197e3f6a4.png)
Posted on Jul 22, 2019 • Updated on Aug 8, 2019
React PDF Generating Pdf documents in React Using React-pdf
This post was originally published on my Blog , check it out for more contents.
Introduction
I was working on a project recently and I got a unique(for me) requirement that needed me to generate pdf file from an array of values in the Browser, usually in my little experience in software development Pdf files are generated in the backend using Puppeteer for node js and FPDF for PHP e.t.c. So I had to look for a React library that could work for my use case, lucky for me I found React-pdf . I found other libraries like @progress/kendo-react-pdf but I decided to go with React-pdf because of its developer-friendly documentation. The library was built by Diego Muracciole and also maintained by him. So in the tutorial/ blog post, I will try to explain briefly how react-pdf works and also walk you through how to generate PDf from an array of objects coming from the Moviedb Api .
While going through the documentation when I was trying to pick the appropriate library for my use-case there were some features of React-pdf that convinced me to use it, I will briefly talk about them:
React-Pdf uses React-Primitives spec to create custom components that you can use to create and structure your PDF documents. These components include:
- PDFDownloadLink
- BlobProvider
You can checkout the docs for more details on what each component above does, Basically the components about help you create pdf using JSXesques syntax.
Now that we have an idea of how to create the PDF document how do we style it? React-pdf provides powerful styling solution using the StyleSheet API which helps you style your document using CSS, Media queries and Flexbox. Check the docs for the CSS properties they support. What if you are a big fan of CSS-in-JS? well, they also support the entire styled-components API.
React-Pdf has a Font API that helps you load fonts from different sources and use in your PDF document.
Those were some of the features that made me pick React-pdf. Also when I checked the Github Repository the maintainer Diego Muracciole is quite active and tries to respond to most issues opened.
So I will briefly work you through a simple example of generating pdf from the MoviesDB API. This demo is going to demonstrate generating the best movies of the year.
Folder Structure
index.js(entry)
The index.js is the entry point of the application. It renders the <MovieList/> which is the parent component of our application.
MovieList.jsx
The MovieList.jsx component contains most of the logic in this application. we import PDFDownloadLink from @react-pdf/renderer , this is basically an anchor tag that enables us to generate and download PDF documents. PDFDownloadLink accepts a document props which are the PDF template we will be creating soon using some of the React-primitives listed early in this post. It also accepts a filename prop that can be used to define the filename of the PDF document, a style prop to add inline styling to the link tag, a className prop if you prefer using classes to style and children prop which is the anchor tag contents.
This Movie.jsx component is the template of the PDF we are generating, Here we define how the structure of the PDF using React-primitives(VIEW, DOCUMENT) and also style. So I'd briefly talk about the some of React-pdf API's I used here.
StyleSheet.create() : It helps you define the styles you want to use in the document, It accepts an object containing all the CSS you want to use in the Document and it returns an object which you can apply to any of the PDF elements via the style prop.
Document : The PDFDownloadLink document prop accepts only a component of type Document so this must be the root of your components when creating the PDF template and accepts only child of type Page , The Document is simply a wrapper around your PDF template and it accepts some optional props
Page : This indicates a Page in the document and you can have multiple Pages in a document. It accepts some props to define the size of the page, orientation or if you want page wrapping wrap . props
View : I will like to compare this component to the HTML div , it helps you section or divide the document. props
Text : This component is used for displaying text on the document and applying styles to it. props
Image : This component is used for displaying images(network or local) on the document, these images could be PNG, JPG or base64.
Demo Application
Before I used this library I never thought it was possible to generate PDF on the client-side, Not only does react-pdf allow you do that but get to use JSXesque syntax to structure and design the PDF document. I know the demo is quite trivial but I think this library might be useful in some use cases.
Top comments (24)
![pdf export react pic](https://media.dev.to/cdn-cgi/image/width=256,height=,fit=scale-down,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8j7kvp660rqzt99zui8e.png)
Templates let you quickly answer FAQs or store snippets for re-use.
![pdf export react unionindesign profile image](https://media.dev.to/cdn-cgi/image/width=50,height=50,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F228008%2F685564ad-fb0f-484b-a1b4-772377c0e147.png)
- Location Denver
- Joined Sep 11, 2019
Thanks for this! If anyone is curious about a real-life use case, I'm doing the same thing at work right now...
- Digital mktg team: We need to generate a 35 page PDF SEO report with all the stats!
- Seo team: OK! Go to our SEO service provider, and get the data you need from their GUI!
- Digital mktg team: Umm, that's a lot of steps and takes a long time/not very efficient way to generate such a lengthy report! And we need to make a lot them!
- Business Intelligence (Me): Say no more! I'll build a react app, and make an API call to get the data we need, and generate the report on the fly so you can download it!
![pdf export react lexiebkm profile image](https://media.dev.to/cdn-cgi/image/width=50,height=50,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F161045%2Ffca7caa0-9e77-4b8a-851f-911affa89d72.png)
- Location Batam, Indonesia
- Education Associate Degree in Physics Engineering (Applied Physics)
- Work Full Stack Web Developer
- Joined Apr 26, 2019
I probably have visited React-pdf site several months ago, I am not sure. But then I found pdfmake, I tried it and it met my requirements, so I have been using it until now. However, maybe I will give React-Pdf a try.
![pdf export react retzion profile image](https://media.dev.to/cdn-cgi/image/width=50,height=50,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F400570%2F660ef9de-4a00-4abb-b795-ccd993cdd12c.jpeg)
- Joined Jun 2, 2020
Could not find module in path: '@react-pdf/unicode-properties' relative to '/node_modules/@react-pdf/fontkit/dist/fontkit.browser.es.js'
![pdf export react esperantkela profile image](https://media.dev.to/cdn-cgi/image/width=50,height=50,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F994211%2Fd6887b0c-14a4-4dce-a3b1-9d8f272ed757.jpeg)
- Work CEO at wake up tech
- Joined Dec 21, 2022
I am using @react-pdf render for my react application.
it generated the component in pdf, the problem now is at the level of display of the data coming from my api which are saved in html tags. it displays like this:
or I would like it to display without the tags. there is also no way to use dangerouslySetInnerHTML
please kindly help me. I'm stuck on it
![pdf export react kirlisakal profile image](https://media.dev.to/cdn-cgi/image/width=50,height=50,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F253271%2F1028371c-7c1e-434c-b28b-a4ebb5828471.jpeg)
- Joined Oct 19, 2019
In this example, I can quickly get PDF doc, however, on my project, I want to get data-table report, and it is too slow... after 5 minutes, I canceled. Do you think is there a reason for this?
Here is my code:
![pdf export react finallynero profile image](https://media.dev.to/cdn-cgi/image/width=50,height=50,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F46239%2F761e437e-be91-4883-a547-f93197e3f6a4.png)
- Location Nigeria
- Joined Nov 23, 2017
Can you a simple demo in codesandbox
Hi Nero, There are PDF Render codes on my question post, jsFiddle, HTML section. fields and records array, and this is simple structure.
I guess, for each styling property, renderer works too much. When try to minimize styling it renders quicker.
![pdf export react airtonix profile image](https://media.dev.to/cdn-cgi/image/width=50,height=50,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F98784%2F948665de-f0ad-4aa0-a2a9-9430715d46dc.jpg)
- Joined Sep 5, 2018
- you're not include react or react-pdf in that fiddle. ( jsfiddle.net/y2nu9ek7 )
- you've just put the jsx in the html section.
Like Nero says.... if you want help from anyone put your example up on a sandbox that properly supports playing with react.
![pdf export react alexand72192972 profile image](https://media.dev.to/cdn-cgi/image/width=50,height=50,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F752336%2Fa9041d3f-cbb1-4edb-b65f-37392cbff4de.png)
- Joined Nov 13, 2021
What is the proper way to reference the source for images stored as a byte array? I get a PDF to generate just fine, but only with URLs, not using my incoming byte arrays.
Currently looking at something like this:
![pdf export react siddharth0x profile image](https://media.dev.to/cdn-cgi/image/width=50,height=50,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F637336%2F23ea990c-39e5-4e6f-b26a-f190fe5cc373.jpeg)
- Location India
- Joined May 25, 2021
I am using a similar logic, but it's making my page unresponsive. Can someone help this.state.prescription - is the state variable where api response is stored
![pdf export react sagar1987 profile image](https://media.dev.to/cdn-cgi/image/width=50,height=50,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F403303%2Fa8db9f9a-b2a5-4237-bdf6-2a01b593b4b7.png)
- Joined Jun 6, 2020
Hello Nero its a wonderful solution , Thanks for that , I have a requirement where i have a download button in a table rows , so on click of download button of a specific row of table i need make a API call to get the details which need to be displayed in PDF, How can we achieve this using this solution . Thanks . Waiting for the reply :)
![pdf export react kritikgarg profile image](https://media.dev.to/cdn-cgi/image/width=50,height=50,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F907946%2Fa67673e0-7911-4950-8e12-a36cc88b14d2.png)
- Joined Aug 13, 2022
👏 Thank you for sharing an excellent post, Nero! It's amazing to see how React-pdf simplifies the process of generating PDF documents in React. 👨💻 As a developer, I found this very helpful for those who want to incorporate PDF generation into their React applications. 📄💻
👉 Along with this, I recently came across an informative article on Effortlessly Generate PDF Quotes with Salesforce that provides a complete guide on how to generate PDF quotes with Salesforce . It's a great resource for those who are looking to generate quote PDFs in Salesforce. 📄💻
I have tried it yesterday. Seeing that the document used JSX, I thought it could contain HTML element. But I was disappointed, because it didn't support HTML element at all. My goal is to use HTML table in this react-pdf library, because my app deals with data records that will be displayed in tabular format, like in HTML table. This means I still have to find my own way in order to display my data in tabular format, using only available features in this library : view, text and styles.
You'd have to do something around the use of the Text component and some awesome styling to implement your own table
![pdf export react revskill10 profile image](https://media.dev.to/cdn-cgi/image/width=50,height=50,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F89054%2F9d7ed786-6b65-4790-a3ab-ad9198b07689.jpeg)
- Joined Aug 2, 2018
I tried downloading pdf from your codesandbox but the pdf is empty. Is there anything wrong here ?
Did you select a year first? I just modified it to hide the download tag until you have selected a year. If it still doesnt work then tell me
I tried to install using webpack (with Razzle.js), but keep getting error:
Do you know how to fix this ?
![pdf export react pam8351 profile image](https://media.dev.to/cdn-cgi/image/width=50,height=50,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F334066%2F08efad74-1cb6-41cf-9084-dae633e541e5.png)
- Joined Feb 11, 2020
I selected year, but the page still shows "Loading please wait". I also, developed the similar page and seeing the same response when the content is more than 1 page of PDF.
Can you please help me to resolve this issue?
![pdf export react gavtin profile image](https://media.dev.to/cdn-cgi/image/width=50,height=50,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F709510%2F8afcf2a2-3adb-4ebd-b91d-4a4c8b2f9947.jpg)
- Joined Sep 20, 2021
I need one help here. I have been using html2canvas and jspdf to grab the current page and then convert to PDF but I am having unexpected page breaks in middle of image or graphs in the page. Is there a way to implement customized pdf with fixed header and footer in each page and at the same time avoid page breaks like described above. Please let me know if you have delt with such a scenario.
![pdf export react kazmiali profile image](https://media.dev.to/cdn-cgi/image/width=50,height=50,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F195930%2F5a48d331-fbaa-47bc-bdb5-5edf1333097f.jpeg)
- Location Hyderabad, Pakistan
- Work Full Stack Developer
- Joined Jul 15, 2019
I was stuck really bad. You save me big time. Thank you so much !!!
![pdf export react aquasar profile image](https://media.dev.to/cdn-cgi/image/width=50,height=50,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F238544%2Fa87450fc-e849-454f-a69e-52f414c1aa83.png)
- Location Edmonton
- Education WordPress Expert | Developer | React | BSc
- Work Partner at The Order Guys
- Joined Sep 29, 2019
I am trying to make this work with Gatsby. Anyone had any luck with this?
![pdf export react bkrahul profile image](https://media.dev.to/cdn-cgi/image/width=50,height=50,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F120526%2F185df2ef-ccf6-42e2-88cb-abc569611738.jpeg)
- Work Student
- Joined Dec 8, 2018
Thanks for the detailed explanantion, Is there any way i can use input tag as custom components? because when i try i get this error
Error: Invalid element of type input passed to PDF renderer
you missed this part:
React-Pdf uses React-Primitives spec to create custom components that you can use to create and structure your PDF documents.
github.com/lelandrichardson/react-...
If you read that repo, you'll discover that it's not rendering with the default set of html components that react normally understands.
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink .
Hide child comments as well
For further actions, you may consider blocking this person and/or reporting abuse
![pdf export react palomino profile image](https://media.dev.to/cdn-cgi/image/width=100,height=100,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1022880%2F107a5146-e292-4c7e-baa5-3a15110efbd3.jpeg)
Integrating with WordPress for Authorization
Palomino - May 24
![pdf export react antd-ts-admin-pro profile image](https://media.dev.to/cdn-cgi/image/width=100,height=100,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1478196%2F0971de17-bdbd-4a13-bf9e-dd75376dbac9.jpeg)
Open Source Admin Dashboard Starter: Ant Design v5, TypeScript, MongoDB
antd-ts-admin - May 15
![pdf export react pachicodes profile image](https://media.dev.to/cdn-cgi/image/width=100,height=100,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F180359%2Fb05421d9-4279-4479-9f5c-eeb692ce45cf.jpg)
Speed Up Your Site with 3 Simple JavaScript Performance Optimization Tips
Pachi 🥑 - May 29
![pdf export react jucheng925 profile image](https://media.dev.to/cdn-cgi/image/width=100,height=100,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1058062%2F191a5783-b374-4f33-a5e4-221bc702da53.png)
React - Persisting Data on Page Refresh
Julie Cheng - May 15
![pdf export react DEV Community](https://media.dev.to/cdn-cgi/image/width=190,height=,fit=scale-down,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8j7kvp660rqzt99zui8e.png)
We're a place where coders share, stay up-to-date and grow their careers.
How to Create PDF Documents With Your React Components Using React-pdf
Create PDFs with ease using this React library and some simple code.
React is a popular JavaScript library for building user interfaces. It's possible to create PDF files from React components using the react-pdf library.
Here you will learn how to create PDF documents with React components using react-pdf.
What Is React-pdf?
React-pdf is a library that allows you to create PDF documents from React components. It provides a set of components that you can use to build your PDF document and uses a virtual DOM to render the components to PDF.
Installing React-pdf
To install react-pdf using the node package manager, run the following terminal command in your project’s directory:
To install it with the yarn package manager instead, run this command:
Creating a PDF Document
To create a PDF document, you will use react-pdf's Document, Page, and Text components. The Document component is responsible for creating a new PDF document and rendering its content. The Page component creates a new page within the PDF document and renders its content. Finally, the Text component renders texts within the PDF document.
Here’s an example of how you can create a PDF document using all three of these components:
In this example, you create a PDF document with a single page containing a single line of text, “Hello There.” After creating a PDF document, you must render it in your React application.
To render the PDF document in your application, use the PDFViewer component, which generates the PDF document.
Import the PDFViewer component and wrap your document in it:
Upon rendering your application, it will look something like this:
Adding Styles to the PDF Document
To add styles to your PDF document, you can use react-pdf’s StyleSheet component. The StyleSheet component allows you to define custom styles for your PDF document.
To use the Stylesheet component, import it from the react-pdf library and define your styles for the PDF document.
For example:
In the code block above, you are adding styles to your PDF component. You define the styles using the Stylesheet.create function. The Stylesheet.create function creates a stylesheet object containing the page and text styles.
Using the style prop, you pass the page and text styles to your Page and Text components. This ensures that your styles apply to the Page and Text components.
Adding Layouts to the PDF Document
To add layouts to your PDF document, you use the View component. The View component is a container component provided by the react-pdf library.
The View component acts like an HTML div — a fundamental HTML element . With it, you wrap up other components, such as the Text component, and define your layouts by adding styles to the View component.
In this example, you use the View components to group other components.
Adding Images to the PDF Document
You can also render images in the PDF document with the Image component provided by the react-pdf library. The Image component allows you to display images in various formats such as JPEG, PNG, SVG, and many more.
The Image component takes a src prop that specifies the URL of the image and a style prop to add custom styles to your images.
In this example, you are creating a PDF document with a single page that contains an image. The Image component displays an image with a width styling of 300 pixels and a height style of 200 pixels.
Adding Links to the PDF Document
You’ll probably want to include links in your PDF document. Links direct the user to a designated URL, which may offer supplementary information unavailable in the PDF document. The Link component of the react-pdf library enables you to create links within your PDF documents.
The Link component takes a src prop to redirect users when they click on the link. They will be redirected to the URL specified in the component's src prop if you define one.
To use the Link component, you first need to import it from the react-pdf library. You can then add it to your PDF document like this:
The above example creates a PDF document with one page and one view. Within the view, you’re displaying a Link component which, when clicked, redirects the user to the specified URL, “https://example.com.”
Now You Can Create PDF Documents Using React
React-pdf is a powerful library that lets you generate PDF documents from your React components. You can create PDF files using react-pdf, then add text, images, and links to them.
By using this library, you can easily generate professional-looking PDF files with custom styling and layout.
- React/React Native
- Vue.js/Nuxt.js
- Django/Flask
- Methodology
Theodo France
How to generate beautiful pdfs with react and puppeteer.
Wed Oct 27 2021 Clément Marcilhacy 8 min read
![pdf export react puppeteer](https://blog.theodo.com/_astro/react_css_puppeteer_pdf.D2A5eTQE_Z1nPJzs.webp)
I recently had to provide a new functionality on my project: the “download as PDF” one. The first thing I wondered was why should we provide this functionality? Doesn’t it already exist natively with pretty much all web browsers with a right mouse click / print / “save as pdf” option? Well I tried on my webpage and the result was really disappointing:
- I had page breaks in the middle of my data tables, graphs, or any React component which aren’t supposed to be split on different pages
- I didn’t have any title, header, page number except the ugly default ones provided by the browser options
- I had many other UX/UI pain points that made the PDF quite unreadable
Example on a Boursorama random page , that looks like:
![pdf export react boursorama example](https://blog.theodo.com/_astro/boursorama_example.CDLicuRE_Z1VTmFi.webp)
That’s when I said “ok this feature may be worth it”, but how should I do it? There are many open source libraries that can generate PDFs. But my choice went naturally to the well-known, google-developed library: Puppeteer. According to me, it is the easiest way to deal with PDF generation of Single Page Applications. It may not be so if you don’t deal with javascript bundles but with plain HTML/CSS. Indeed, there are easier solutions for this use case like wkhtmltopdf, html-pdf-node or jspdf for example.
In this article, I want to give you a few tips to generate beautiful PDFs of SPAs with Puppeteer. Firstly, I will explain to you how you can create a printable version of your page with React and Puppeteer. Then, I will show you how to use Puppeteer for the generation of your new printable page.
Render a printable version of your page
For this part you don’t actually need to have Puppeteer or any other printer service set up. You can make your changes to your code as usual, and then ctrl+P on your page to see what it looks likes:
![pdf export react boursorama_print_chrome](https://blog.theodo.com/_astro/boursorama_print_chrome.Vo3_7E1J_1scwrq.webp)
However, the feedback loop is not as quick as usual.
To adapt your code for printing, you have to bypass the 2 main differences between a web page and a PDF:
- The components of a React application are dynamic whereas a PDF is a static file
- A PDF has page breaks and a fixed size whereas a webpage is a “one page” app with a variable viewport size
From dynamic webpage to static rendering
Create the “printable version” of your SPA with React. To create the printable version of our page, you will have to add/remove/modify the different components that make up the page.
You basically have 2 solutions for this part:
- create a whole new custom design for your page
- adapt your current page
If you opt for the second solution (that is less costly), you will have to adapt your existing components. For example, if you have a table with 3 tabs, you will probably want to display the content of all the tabs. Something like displaying the tabs one after the other may do the trick:
Only dynamic:
Dynamic and Static:
In this case, the isPrintable props will determine whether to display the 3 tabs, or just the first one. You may pass this props to every dynamic component of your page, that needs to be adapted for printing.
Deal with page breaks and fixed size with CSS
As you can see with the Boursorama example, your components may be cut off between 2 pages when trying to print your page. It happens because your web browser has no idea where to break page if you don’t tell him. This is where the break-inside CSS property steps in. You obviously don’t want your previous set of tabs to be cut off in the middle. Neither your graphs or almost any component on your page. Then you would have to adapt the previous code to add this CSS property. It would work with inline-css but you probably don’t want to add the style={{ breakInside: 'avoid' }} everywhere in your jsx/tsx files.
You would rather use stylesheets. And instead of adding this property on every CSS class already existing, you’ll want to use the media @print option. This will let you custom your webpage for printing only! For example, you may want your text to be a bit bigger or to have a smooth grey color on the printable version, for any esthetic reason or convenience.
We’ll just add this in the @media object in your css file:
These few CSS tips should help you improve a lot the rendering of your webpage.
How to use Puppeteer to generate your PDFs
Now, your page is ready for printing. You know it when you pass the isPrintable props to your page, right click + print on your browser, and you are quite comfortable with what you seeing. Here comes the part of printing. You now have a printable version of your webpage, but the users have no idea of it, and even if the ctrl + P on the website, they will see the “dynamic” version of the webpage. To let them generate the PDF version and automate the generation of the latest, you probably want to add a button that will directly generate the PDF server side, and even add some customization. This is what, among other things, Puppeteer is used for.
How Puppeteer works?
Puppeteer is a common and natural way to control Chrome. It provides full access to browser features and, most importantly, can run Chrome in fully headless mode on a remote server [...]
Generation of the React app is done by a web browser. We need the minimal environnement able to execute javascript to render a DOM. Puppeteer will do it by launching a headless chromium. From now on, and since the generation is done on the server, the web browser doesn’t need to have a graphical user interface (GUI). Chromium with generate the printable version: the same page the user sees on his web browser but with the isPrintable props activated. Then Puppeteer will execute the pdf function on the page with some custom options that will trigger the printing of the page.
Just add the button with the URL that calls the printer service:
The downloadUrl is actually a GET request on your server that will execute Puppeteer on the server and return content with content-type application/pdf
So what does this Puppeteer code look like?
How to use it?
To be able to actually download the PDF, you just need a few code lines.
The minimal code would then look like:
These are the common steps you’ll need to generate the PDF. Depending on your backend, you probably don’t want not to download the PDF on the server but to render it on a response object, to send it back to the client (the web browser of the user). You should then adapt the page.pdf() method with const buffer = await page.pdf({ format: 'a4'}); and return this buffer on the _blank page the user opened on his browser, waiting for a response.
Add some options to customize the PDF
You can of course adapt the options your naturally have on your browser, like the paper size, the scale, the margins, etc. with the help of the official documentation: https://github.com/puppeteer/puppeteer/blob/v10.4.0/docs/api.md#pagepdfoptions .
One cool option that I recommend, mainly because the default one provided by Google Chrome is really ugly, is the header or footer template. Just read a HTML file template and pass it through the data you want to display such as the current date, the page number for each page, or even an image/logo:
using a html template
You now have provided to your PDF a fully customized footer.
There are a lot of other options regarding, the PDF generation, but also for the previous steps of launching the browser, opening a new page, going to the URL, that will let you fully customize your PDF generation on the server.
Finally, by adapting your React/CSS code and using Puppeteer, you can easily provide a fully custom PDF of your page. Moreover, Puppeteer is doing all the stuff server side. Which makes this feature fully transparent, quite fast for the end user, and with the same result for every user on any browser! Puppeteer is really powerful and has a lot of options that make the PDF generation quite easy for the developers, and with a rendering much more custom and beautiful than the default one on users’ browsers.
![pdf export react Clément Marcilhacy](https://blog.theodo.com/_astro/clementm.Cu6evGw2.png)
Clément Marcilhacy
Developer @ theodo, liked this article.
![pdf export react Drawing of a Blender stickman riding a Lambda function in the clouds and another Blender stickman with Google Cloud Run's logo as its trunk.](https://blog.theodo.com/_astro/thumbnail.ComL9gxA_Z1tBqVE.webp)
Getting started
- Basic usage
Minimum requirements
Installing packages, problem with installation on apple m1, using the latest version of pdfjs-dist.
How to Create PDF Reports in React
![pdf export react Adebola Adeniran](https://www.freecodecamp.org/news/content/images/size/w60/2021/02/a083a61f-971a-40cb-8a98-0745a01c3fb7.jpeg)
In this article, we'll be building a button that generates a PDF document (like you see above) based on data from an API call.
A couple of days ago, I built a full stack CRM application to manage communication between customers and support agents.
I needed a way for agents to generate a summary of closed tickets as a PDF file. After searching across the internet for an EASY way to do this, I dare say this article will show you the easiest way out there.
Let's get into it, shall we?
Setup packages
First, let's install the packages we need.
Define a function to generate the PDFs
Next, let's define a function that we can call anywhere to generate a PDF for us. I've added a lot of comments to help you understand what is going on with each line.
Create a component to save the tickets to be rendered
Now, let's create a simple Component that fetches and saves the ticket to state.
A few points about our <Tickets /> component. When our component loads, we make a request to http://localhost:3000/tickets to fetch all our tickets. We then save them to the tickets state. And finally, we pass them as a prop to the <TicketsComponent /> to render the tickets in the DOM.
We also have a reportTickets variable that filters our tickets to get only the tickets that have the status of completed .
Notice that we also created the Generate Monthly Report button that calls the generatePDF() function that we defined earlier when clicked.
Create a component to display the tickets in a table
Next, let's define our <TicketsComponent /> that will be responsible for displaying our tickets in a nice looking table. Remember that it accepts the tickets to be displayed as a prop from the <Tickets /> component.
Now, let's see what our application currently looks like. We have 10 tickets in our state but I'll show 6 here for convenience.
![pdf export react image-51](https://www.freecodecamp.org/news/content/images/2020/06/image-51.png)
As you can see, we have a number of tickets at different statuses. We also have our Generate monthly report button that, when clicked, will export the PDF file.
And that's it. You should end up with a PDF file with the filename in the form report_dddmmyyyy downloaded in your browser.
If this article helped you out, say hello on twitter .
I'm a Ruby-on-Rails/Node.js/React full-stack developer passionate about jollof rice and plantain.
If you read this far, thank the author to show them you care. Say Thanks
Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started
![pdf export react Newsletter Screenshot](https://w3collective.com/wp-content/uploads/2023/03/ipad-screen.png)
Join more than 1,300 web developers who are subscribed to w3collective email newsletter. Simply drop your email address below to get actionable tips, free tools, tutorials, and more to help you grow as a developer.
No Spam. We Respect Your Privacy. Unsubscribe at any Time.
Exporting a React component to a PDF file on click
![pdf export react GitHub](https://w3collective.com/wp-content/themes/w3c/img/icon-github.png)
In this tutorial we’ll covering the process of exporting a React component to a PDF file.
We’ll be using jsPDF to generate the PDF which can be installed by running:
For the purposes of this tutorial we’ll create a simple “shipping label” component which will contain an address and barcode image. Here’s what the basic structure of our ShippingLabel.js component will look like:
We’ve used an asynchronous function here so we can use the await keyword which will allow us to wait until all the HTML markup has been captured from the component before moving onto the generation of the PDF document.
Now let’s complete the return statement with the HTML markup that we’ll export to the PDF along with a button that’ll generate the PDF when clicked:
Anything outside <div id="pdf"> will not be exported to the PDF.
We can now complete the createPDF function:
This creates a new jsPDF object and set’s the orientation ( portrait ), base unit to be used when coordinates are specified ( pt ), and the document size ( a4 ). You can view the full range of options available in the official documentation here .
If you test what we’ve created so far you’ll notice CSS from external style sheets are not captured in the PDF. If you do want external CSS styles to appear in the PDF you’ll either need to use CSS in JS or another library called html2canvas which captures the HTML as image before exporting to PDF.
Let modify our component to capture external CSS by first installing html2canvas :
And then import into our component:
We can now update the createPDF function to capture the HTML:
Now when you test the functionality you’ll see any styles from external CSS files are captured in the PDF.
That’s all for this tutorial. You should now have an understanding of how jsPDF & html2canvas can be used to export a React component to a PDF file. The full source code for the component is available on GitHub .
![pdf export react pdf export react](https://w3collective.com/wp-content/themes/w3c/img/ad-amazon-01.png)
Related Posts
How to create a checkbox component in React
Create a custom React star rating component
Create a custom React stopwatch timer component
#AD Shop Web Developer T-Shirts
![pdf export react No Internet T-Shirt](https://w3collective.com/wp-content/themes/w3c/img/ad-tshirt-01.jpg)
- skip navigation KendoReact Product Bundles DevCraft All Telerik .NET tools and Kendo UI JavaScript components in one package. Now enhanced with: NEW : Design Kits for Figma
- What is KendoReact
Getting Started
- Server Components
- Charts updated
- Common Utilities
- Conversational UI updated
- Data Grid updated
- Date Inputs
- Excel Export
- ListBox updated
- Notification
- PDF Processing
- Image Resolution
- Scaling of Content
- Configuration of Margins
- Repeated Table Headers
- Multi-Page Content
- Hidden Content
- Base64 Strings
- Styling of Content
- Progress Bars
- Spreadsheet
- Sample Applications
- Styling & Themes
- Common Features
- Project Setup
- Knowledge Base
- Troubleshooting
KendoReact Rich Text PDF Generator Overview
The KendoReact PDF Generator enables you to export a selection of or the entire content of a web page to a PDF file. With it, you can scale the content to better fit on the page, customize the paper size, change the page orientation, work with templates and use many others features that provide extensive control over the exported PDF file.
The PDF Generator is built from the ground up and specifically for React so that you get a high-performance control which integrates tightly with your application and with the rest of the KendoReact components. The KendoReact PDF Generator component is distributed through the @progress/kendo-react-pdf npm package.
The following example demonstrates the KendoReact PDF Generator component in action.
- Key Features
The KendoReact PDF Generator component delivers a range of handy developer-friendly features whose number and further development are not limited by the list in this section. The KendoReact team constantly invests efforts to improve the performance, add more value to the existing PDF Generator library, and develop new features.
You can limit the image resolution to improve performance (the default behavior is to export images in their original resolution). Read more about the image resolution of the PDF Generator...
You can choose if the hyperlinks in the exported PDF file are clickable or not. Read more about the hyperlinks options of the PDF Generator...
- Content Scaling
To fit the content to one page, the KendoReact PDF Generator enables you to export a PDF document that is bigger or smaller than the original elements. Read more about the content scaling of the PDF Generator...
- Margin Configuration
The KendoReact PDF Generator delivers options for setting the margins of the output PDF files, which provides better control over the layout of the exported document. Read more about the margin configuration of the PDF Generator...
The KendoReact PDF Generator component enables you to render recurrent table headers. Read more about the repeated table headers of the PDF Generator...
For larger documents, the KendoReact PDF Generator provides options for generating multi-page PDF files, preventing page-split, and rendering page templates. Read more about multi-page content of the PDF Generator...
The KendoReact PDF Generator allows you to generate content which is otherwise not visible to the user before the PDF file is exported. Read more about the hidden content of the PDF Generator...
When the document has to be exported on the server, the React PDF Generator enables you to create a base64 string during the PDF export and send it to the server. Read more about the base64 strings of the PDF Generator...
- Content Styling
You can change the appearance of the content through CSS rules that apply only to the PDF file. This approach allows you to style the generated PDF without changing the web page appearance. Read more about the content styling of the PDF Generator...
- Support Options
For any questions about the use of KendoReact PDF Generator, or any other KendoReact components , there are several support options available :
- KendoReact license holders and anyone in an active trial can take advantage of the outstanding KendoReact customer support delivered by the developers who built the library. To submit a support ticket, use the Telerik support system .
- The KendoReact forums are part of the free support you can get from the community and from the KendoReact team on all kinds of general issues.
- KendoReact Feedback Portal and KendoReact Roadmap provide information on the features in discussion and also those planned for release.
- KendoReact uses GitHub Issues as its bug tracker, and you can submit any related reports there. Also, check out the closed list .
- Need something unique that is tailor-made for your project? Progress offers its Progress Services group that can work with you to create any customized solution that you might need.
- Suggested Links
- Getting Started with the KendoReact PDF Generator
- Getting Started with KendoReact
- API Reference of the KendoReact PDF Generator
- React PDF Generator High-Level Overview
- KendoReact End User License Agreement
- Virtual Classroom (Training Courses for Registered Users)
- React UI Components
In this article
Not finding the help you need.
- Installation and First Steps
- What's New
- Release History
Support Resources
- Virtual Classroom
- Video Tutorials
- Form Design Guidelines
- Feedback Portal
- React Blogs
- React Forum
- React Wednesdays on Twitch
![pdf export react Progress company logo](https://www.telerik.com/kendo-react-ui/components/kendo-react-ui/static/4b51c683b8ad83cd0d3bfe494878b0af/9d3eb/progress-small.png)
Telerik and Kendo UI are part of Progress product portfolio. Progress is the leading provider of application development and digital experience technologies.
- Press Releases
- Media Coverage
Copyright © 2024 , Progress Software Corporation and/or its subsidiaries or affiliates. All Rights Reserved. Progress, Telerik, Ipswitch, and certain product names used herein are trademarks or registered trademarks of Progress Software Corporation and/or one of its subsidiaries or affiliates in the U.S. and/or other countries. See Trademarks for appropriate markings.
- Terms of Use
- Privacy Center
- Security Center
- License Agreements
- Code of Conduct
- Doc Copyright
Navigation Menu
Search code, repositories, users, issues, pull requests..., provide feedback.
We read every piece of feedback, and take your input very seriously.
Saved searches
Use saved searches to filter your results more quickly.
To see all available qualifiers, see our documentation .
- Notifications You must be signed in to change notification settings
Display PDFs in your React app as easily as if they were images.
wojtekmaj/react-pdf
Folders and files, repository files navigation.
This package is used to display existing PDFs. If you wish to create PDFs using React, you may be looking for @react-pdf/renderer .
- Install by executing npm install react-pdf or yarn add react-pdf .
- Import by adding import { Document } from 'react-pdf' .
- Use by adding <Document file="..." /> . file can be a URL, base64 content, Uint8Array, and more.
- Put <Page /> components inside <Document /> to render pages.
A minimal demo page can be found in sample directory.
Online demo is also available!
Before you continue
React-PDF is under constant development. This documentation is written for React-PDF 9.x branch. If you want to see documentation for other versions of React-PDF, use dropdown on top of GitHub page to switch to an appropriate tag. Here are quick links to the newest docs from each branch:
Getting started
Compatibility, browser support.
React-PDF supports all modern browsers. It is tested with the latest versions of Chrome, Edge, Safari, Firefox, and Opera.
The following browsers are supported out of the box in React-PDF v9:
- Chrome ≥119
- Safari ≥17.4
- Firefox ≥121
You may extend the list of supported browsers by providing additional polyfills (e.g. for Array.prototype.at , Promise.allSettled or Promise.withResolvers ) and either configuring your bundler to transpile pdfjs-dist or using legacy PDF.js worker .
If you need to support older browsers, you will need to use React-PDF v6 or earlier.
To use the latest version of React-PDF, your project needs to use React 16.8 or later.
If you use an older version of React, please refer to the table below to a find suitable React-PDF version.
React-PDF may be used with Preact.
Installation
Add React-PDF to your project by executing npm install react-pdf or yarn add react-pdf .
If you use Next.js without Turbopack enabled, add the following to your next.config.js :
If you use Next.js with Turbopack enabled, add empty-module.ts file:
and add the following to your next.config.js :
Configure PDF.js worker
For React-PDF to work, PDF.js worker needs to be provided. You have several options.
Import worker (recommended)
For most cases, the following example will work:
In Next.js:
- Using App Router, make sure to add 'use client'; to the top of the file.
- Using Pages Router, make sure to disable SSR when importing the component you're using this code in.
pnpm requires an .npmrc file with public-hoist-pattern[]=pdfjs-dist for this to work.
For Parcel 2, you need to use a slightly different code:
Copy worker to public directory
You will have to make sure on your own that pdf.worker.mjs file from pdfjs-dist/build is copied to your project's output folder.
For example, you could use a custom script like:
Use external CDN
Legacy pdf.js worker.
If you need to support older browsers, you may use legacy PDF.js worker. To do so, follow the instructions above, but replace /build/ with legacy/build/ in PDF.js worker import path, for example:
Here's an example of basic usage:
Check the sample directory in this repository for a full working example. For more examples and more advanced use cases, check Recipes in React-PDF Wiki .
Support for annotations
If you want to use annotations (e.g. links) in PDFs rendered by React-PDF, then you would need to include stylesheet necessary for annotations to be correctly displayed like so:
Support for text layer
If you want to use text layer in PDFs rendered by React-PDF, then you would need to include stylesheet necessary for text layer to be correctly displayed like so:
Support for non-latin characters
If you want to ensure that PDFs with non-latin characters will render perfectly, or you have encountered the following warning:
then you would also need to include cMaps in your build and tell React-PDF where they are.
Copying cMaps
First, you need to copy cMaps from pdfjs-dist (React-PDF's dependency - it should be in your node_modules if you have React-PDF installed). cMaps are located in pdfjs-dist/cmaps .
Add vite-plugin-static-copy by executing npm install vite-plugin-static-copy --save-dev or yarn add vite-plugin-static-copy --dev and add the following to your Vite config:
Add copy-webpack-plugin by executing npm install copy-webpack-plugin --save-dev or yarn add copy-webpack-plugin --dev and add the following to your Webpack config:
Other tools
If you use other bundlers, you will have to make sure on your own that cMaps are copied to your project's output folder.
Setting up React-PDF
Now that you have cMaps in your build, pass required options to Document component by using options prop, like so:
Make sure to define options object outside of your React component, and use useMemo if you can't.
Alternatively, you could use cMaps from external CDN:
Support for standard fonts
If you want to support PDFs using standard fonts (deprecated in PDF 1.5, but still around), ot you have encountered the following warning:
then you would also need to include standard fonts in your build and tell React-PDF where they are.
Copying fonts
First, you need to copy standard fonts from pdfjs-dist (React-PDF's dependency - it should be in your node_modules if you have React-PDF installed). Standard fonts are located in pdfjs-dist/standard_fonts .
If you use other bundlers, you will have to make sure on your own that standard fonts are copied to your project's output folder.
Now that you have standard fonts in your build, pass required options to Document component by using options prop, like so:
Alternatively, you could use standard fonts from external CDN:
Loads a document passed using file prop.
Displays a page. Should be placed inside <Document /> . Alternatively, it can have pdf prop passed, which can be obtained from <Document /> 's onLoadSuccess callback function, however some advanced functions like rendering annotations and linking between pages inside a document may not be working correctly.
Displays an outline (table of contents). Should be placed inside <Document /> . Alternatively, it can have pdf prop passed, which can be obtained from <Document /> 's onLoadSuccess callback function.
Displays a thumbnail of a page. Does not render the annotation layer or the text layer. Does not register itself as a link target, so the user will not be scrolled to a Thumbnail component when clicked on an internal link (e.g. in Table of Contents). When clicked, attempts to navigate to the page clicked (similarly to a link in Outline). Should be placed inside <Document /> . Alternatively, it can have pdf prop passed, which can be obtained from <Document /> 's onLoadSuccess callback function.
Props are the same as in <Page /> component, but certain annotation layer and text layer-related props are not available:
- customTextRenderer
- onGetAnnotationsError
- onGetAnnotationsSuccess
- onGetTextError
- onGetTextSuccess
- onRenderAnnotationLayerError
- onRenderAnnotationLayerSuccess
- onRenderTextLayerError
- onRenderTextLayerSuccess
- renderAnnotationLayer
- renderForms
- renderTextLayer
On top of that, additional props are available:
Useful links
- React-PDF Wiki
The MIT License.
This project wouldn't be possible without the awesome work of Niklas Närhinen who created its original version and without Mozilla, author of pdf.js . Thank you!
Thank you to all our sponsors! Become a sponsor and get your image on our README on GitHub.
Thank you to all our backers! Become a backer and get your image on our README on GitHub.
Top Contributors
Thank you to all our contributors that helped on this project!
Releases 145
Sponsor this project, used by 60.3k.
Contributors 60
- TypeScript 94.2%
Adobe Community
- Global community
- 日本語コミュニティ Dedicated community for Japanese speakers
- 한국 커뮤니티 Dedicated community for Korean speakers
- Discussions
- Re: export pdf Aptos not found
export pdf Aptos not found
Copy link to clipboard
1 Correct answer
never-displayed
Mastertheboss
Converting a PDF to Text in Java made simple
In this tutorial, we will explore how to convert a PDF document into raw text using the Apache PDFBox library in Java. This process can be particularly useful for applications that need to analyze or summarize the contents of a PDF, such as providing input to an AI chatbot .
Introduction to PDFBox
Apache PDFBox is an open-source Java library that allows for the creation, manipulation, and extraction of data from PDF documents. It’s a robust tool for converting PDF content to raw text, which can then be processed by various text analysis tools or AI models.
Setting Up PDFBox
First, you’ll need to include PDFBox in your project. If you’re using Maven, add the following dependency to your pom.xml :
As usual, in our example, we will use a JBang script to show how PDFBox works so you don’t need to create a Maven project for it. Read this article to learn more about JBang: JBang: Create Java scripts like a pro
Converting Text to PDF
To convert a PDF document to text, you will use the PDFTextStripper class provided by PDFBox. This class extracts text from a given PDF document.
The above Class, will load a PDF and save it as a raw text file.
Breaking the Text into Chapters
Unfortunately, you cannot detect from the PDF Metadata where each chapter begins or ends. Breaking a PDF into single chapters is useful if you want to provide the single chapters to a tool, such as a ChatBoot tool. On the other hand, you can easily use a Regular expression to detect the beginning of a Chapter.
For example, in the PDF I wanted to convert, each Chapter begins with the following text: “ Chapter n “.
Therefore, you can use this simple Regexp to break the large text into chapters:
Here is a full example which splits a PDF text into multiple text files. One for each chapter:
Launch it and you are done!
![pdf export react convert text to pdf in java](https://www.mastertheboss.com/wp-content/uploads/2024/05/Screenshot-from-2024-05-30-19-52-22.png)
Converting PDF documents to raw text using the PDFBox library is a straightforward and powerful way to enable various text processing applications. Whether it’s for summarization, question answering, or content analysis, extracting text from PDFs provides a versatile input for AI chatbots and other text-based tools.
By following this tutorial, you should be able to set up PDFBox, extract text from PDFs, and understand how to leverage this text for further processing with AI models.
![ezoic pdf export react](https://go.ezodn.com/utilcave_com/ezoic.png)
![pdf export react U.S. flag](https://www.bea.gov/sites/default/files/favicon-57.png)
An official website of the United States government
Gross Domestic Product, First Quarter 2024 (Second Estimate) and Corporate Profits (Preliminary)
- News Release
- Related Materials
- Additional Information
Real gross domestic product (GDP) increased at an annual rate of 1.3 percent in the first quarter of 2024 (table 1), according to the "second" estimate released by the Bureau of Economic Analysis. In the fourth quarter of 2023, real GDP increased 3.4 percent.
The GDP estimate released today is based on more complete source data than were available for the "advance" estimate issued last month. In the advance estimate, the increase in real GDP was 1.6 percent. The update primarily reflected a downward revision to consumer spending (refer to "Updates to GDP").
The increase in real GDP primarily reflected increases in consumer spending, residential fixed investment, nonresidential fixed investment, and state and local government spending that were partly offset by a decrease in private inventory investment. Imports, which are a subtraction in the calculation of GDP, increased (table 2).
![pdf export react Real GDP: Percent change from preceding quarter](https://www.bea.gov/system/files/gdp1q24-2nd-chart.png)
Compared to the fourth quarter, the deceleration in real GDP in the first quarter primarily reflected decelerations in consumer spending, exports, and state and local government spending and a downturn in federal government spending. These movements were partly offset by an acceleration in residential fixed investment. Imports accelerated.
Current‑dollar GDP increased 4.3 percent at an annual rate, or $298.9 billion, in the first quarter to a level of $28.26 trillion, a downward revision of $28.6 billion from the previous estimate (tables 1 and 3). More information on the source data that underlie the estimates is available in the " Key Source Data and Assumptions " file on BEA's website.
The price index for gross domestic purchases increased 3.0 percent in the first quarter, a downward revision of 0.1 percentage point from the previous estimate. The personal consumption expenditures (PCE) price index increased 3.3 percent, a downward revision of 0.1 percentage point. Excluding food and energy prices, the PCE price index increased 3.6 percent, a downward revision of 0.1 percentage point.
Personal Income
Current-dollar personal income increased $404.4 billion in the first quarter, a downward revision of $2.6 billion from the previous estimate. The increase in the first quarter primarily reflected increases in compensation (led by private wages and salaries) and personal current transfer receipts (led by government social benefits to persons) (table 8).
Disposable personal income increased $266.7 billion, or 5.3 percent, in the first quarter, an upward revision of $40.5 billion from the previous estimate. Real disposable personal income increased 1.9 percent, an upward revision of 0.8 percentage point.
Personal saving was $796.6 billion in the first quarter, an upward revision of $96.6 billion from the previous estimate. The personal saving rate — personal saving as a percentage of disposable personal income—was 3.8 percent in the first quarter, an upward revision of 0.2 percentage point.
Gross Domestic Income and Corporate Profits
Real gross domestic income (GDI) increased 1.5 percent in the first quarter, compared with an increase of 3.6 percent (revised) in the fourth quarter. The average of real GDP and real GDI , a supplemental measure of U.S. economic activity that equally weights GDP and GDI, increased 1.4 percent in the first quarter, compared with an increase of 3.5 percent in the fourth quarter (table 1).
Profits from current production (corporate profits with inventory valuation and capital consumption adjustments) decreased $21.1 billion in the first quarter, in contrast to an increase of $133.5 billion in the fourth quarter (table 10).
Profits of domestic financial corporations increased $73.7 billion in the first quarter, compared with an increase of $5.9 billion in the fourth quarter. Profits of domestic nonfinancial corporations decreased $114.1 billion, in contrast to an increase of $136.5 billion. Rest-of-the-world profits increased $19.3 billion, in contrast to a decrease of $8.9 billion. In the first quarter, receipts increased $29.8 billion, and payments increased $10.5 billion.
Updates to GDP
With the second estimate, downward revisions to consumer spending, private inventory investment, and federal government spending were partly offset by upward revisions to state and local government spending, nonresidential fixed investment, residential fixed investment, and exports. Imports were revised up. For more information, refer to the Technical Note . For information on updates to GDP, refer to the "Additional Information" section that follows.
Updates to Fourth-Quarter Wages and Salaries
In addition to presenting updated estimates for the first quarter, today's release presents revised estimates of fourth-quarter wages and salaries, personal taxes, and contributions for government social insurance, based on updated data from the Bureau of Labor Statistics Quarterly Census of Employment and Wages program. Wages and salaries are now estimated to have increased $58.5 billion in the fourth quarter, a downward revision of $73.0 billion. Personal current taxes are now estimated to have increased $27.1 billion, a downward revision of $12.6 billion. Contributions for government social insurance are now estimated to have increased $8.3 billion, a downward revision of $9.6 billion. With the incorporation of these new data, real gross domestic income is now estimated to have increased 3.6 percent in the fourth quarter, a downward revision of 1.2 percentage points from the previously published estimate.
* * *
Next release, June 27, 2024, at 8:30 a.m. EDT Gross Domestic Product (Third Estimate) Corporate Profits (Revised Estimate) Gross Domestic Product by Industry First Quarter 2024
Full Release & Tables (PDF)
Technical note (pdf), tables only (excel), release highlights (pdf), historical comparisons (pdf), key source data and assumptions (excel), revision information.
- GDP Lisa Mataloni 301-278-9083 [email protected]
- Corporate Profits Kate Pinard 301-278-9417 [email protected]
- Media Connie O’Connell 301-278-9003 [email protected]
Additional resources available at www.bea.gov :
- Stay informed about BEA developments by reading the BEA blog , signing up for BEA's email subscription service , or following BEA on X, formerly known as Twitter @BEA_News .
- Historical time series for these estimates can be accessed in BEA's interactive data application .
- Access BEA data by registering for BEA's data Application Programming Interface (API).
- For more on BEA's statistics, refer to our online journal, the Survey of Current Business .
- BEA's news release schedule
- NIPA Handbook : Concepts and Methods of the U.S. National Income and Product Accounts
Definitions
Gross domestic product (GDP), or value added , is the value of the goods and services produced by the nation's economy less the value of the goods and services used up in production. GDP is also equal to the sum of personal consumption expenditures, gross private domestic investment, net exports of goods and services, and government consumption expenditures and gross investment.
Gross domestic income (GDI) is the sum of incomes earned and costs incurred in the production of GDP. In national economic accounting, GDP and GDI are conceptually equal. In practice, GDP and GDI differ because they are constructed using largely independent source data.
Gross output is the value of the goods and services produced by the nation's economy. It is principally measured using industry sales or receipts, including sales to final users (GDP) and sales to other industries (intermediate inputs).
Current-dollar estimates are valued in the prices of the period when the transactions occurred—that is, at "market value." Also referred to as "nominal estimates" or as "current-price estimates."
Real values are inflation-adjusted estimates—that is, estimates that exclude the effects of price changes.
The gross domestic purchases price index measures the prices of final goods and services purchased by U.S. residents.
The personal consumption expenditure price index measures the prices paid for the goods and services purchased by, or on the behalf of, "persons."
Personal income is the income received by, or on behalf of, all persons from all sources: from participation as laborers in production, from owning a home or business, from the ownership of financial assets, and from government and business in the form of transfers. It includes income from domestic sources as well as the rest of world. It does not include realized or unrealized capital gains or losses.
Disposable personal income is the income available to persons for spending or saving. It is equal to personal income less personal current taxes.
Personal outlays is the sum of personal consumption expenditures, personal interest payments, and personal current transfer payments.
Personal saving is personal income less personal outlays and personal current taxes.
The personal saving rate is personal saving as a percentage of disposable personal income.
Profits from current production , referred to as corporate profits with inventory valuation adjustment (IVA) and capital consumption (CCAdj) adjustment in the National Income and Product Accounts (NIPAs), is a measure of the net income of corporations before deducting income taxes that is consistent with the value of goods and services measured in GDP. The IVA and CCAdj are adjustments that convert inventory withdrawals and depreciation of fixed assets reported on a tax-return, historical-cost basis to the current-cost economic measures used in the national income and product accounts. Profits for domestic industries reflect profits for all corporations located within the geographic borders of the United States. The rest-of-the-world (ROW) component of profits is measured as the difference between profits received from ROW and profits paid to ROW.
For more definitions, refer to the Glossary: National Income and Product Accounts .
Statistical conventions
Annual-vs-quarterly rates . Quarterly seasonally adjusted values are expressed at annual rates, unless otherwise specified. This convention is used for BEA's featured, seasonally adjusted measures to facilitate comparisons with related and historical data. For details, refer to the FAQ " Why does BEA publish estimates at annual rates? "
Quarterly not seasonally adjusted values are expressed only at quarterly rates.
Percent changes . Percent changes in quarterly seasonally adjusted series are displayed at annual rates, unless otherwise specified. For details, refer to the FAQ " How is average annual growth calculated? " and " Why does BEA publish percent changes in quarterly series at annual rates? " Percent changes in quarterly not seasonally adjusted values are calculated from the same quarter one year ago. All published percent changes are calculated from unrounded data.
Calendar years and quarters . Unless noted otherwise, annual and quarterly data are presented on a calendar basis.
Quantities and prices . Quantities, or "real" volume measures, and prices are expressed as index numbers with a specified reference year equal to 100 (currently 2017). Quantity and price indexes are calculated using a Fisher-chained weighted formula that incorporates weights from two adjacent periods (quarters for quarterly data and annuals for annual data). For details on the calculation of quantity and price indexes, refer to Chapter 4: Estimating Methods in the NIPA Handbook .
Chained-dollar values are calculated by multiplying the quantity index by the current dollar value in the reference year (2017) and then dividing by 100. Percent changes calculated from real quantity indexes and chained-dollar levels are conceptually the same; any differences are due to rounding. Chained-dollar values are not additive because the relative weights for a given period differ from those of the reference year. In tables that display chained-dollar values, a "residual" line shows the difference between the sum of detailed chained-dollar series and its corresponding aggregate.
BEA releases three vintages of the current quarterly estimate for GDP. "Advance" estimates are released near the end of the first month following the end of the quarter and are based on source data that are incomplete or subject to further revision by the source agency. "Second" and "third" estimates are released near the end of the second and third months, respectively, and are based on more detailed and more comprehensive data as they become available.
The table below shows the average revisions to the quarterly percent changes in real GDP between different estimate vintages, without regard to sign.
Annual and comprehensive updates are released in late September. Annual updates generally cover at least the five most recent calendar years (and their associated quarters) and incorporate newly available major annual source data as well as some changes in methods and definitions to improve the accounts. Comprehensive (or benchmark) updates are carried out at about 5-year intervals and incorporate major periodic source data, as well as major conceptual improvements.
Unlike GDP, advance current quarterly estimates of GDI and corporate profits are not released because data on domestic profits and net interest of domestic industries are not available. For fourth quarter estimates, these data are not available until the third estimate.
GDP by industry and gross output estimates are released with the third estimate of GDP.
![](http://academicwritinghelp.pw/777/templates/cheerup1/res/banner1.gif)
IMAGES
VIDEO
COMMENTS
React-pdf React renderer for creating PDF files on the browser and server. Try it out! ...
import generatePDF, {Resolution, Margin} from 'react-to-pdf'; const options = {// default is `save` method: 'open', // default is Resolution.MEDIUM = 3, which should be enough, higher values // increases the image quality but also the size of the PDF, so be careful // using values higher than 10 when having multiple pages generated, it // might cause the page to crash or hang. resolution ...
Display PDFs in your React app as easily as if they were images.. Latest version: 9.0.0, last published: 2 days ago. Start using react-pdf in your project by running `npm i react-pdf`. There are 803 other projects in the npm registry using react-pdf.
React-pdf/Renderer 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. ... </Text> </View> </Page> </Document> ); }; export default MyPDF; <Document>: The root component for your PDF document. It acts as a container for ...
react-print-pdf. react-print-pdf is an across-the-board solution for creating PDF documents in a React application. Unlike other solutions, react-print-pdf gives you full control over your document's layout. You can design complex and customized layouts with features like footnotes, headers, margins, and more.
Step 4: Click the "Create PDF using React PDF renderer" button and you should be redirected to a page where you can enter some data for the pdf as demonstrated below. Steps in the demo: 1: Fill out the form fields and select the "Generate PDF" button. 2: You will be directed to the PDF view of the completed form.
Using npm. npm install @react-pdf/renderer --save. 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. 2. Create your PDF document. This is where things start getting interesting.
In the lazy load mode the content of the PDF is added to the DOM when you call generatePdf and is cleared afterwards. In non-lazy load the content is added to the DOM when the page is rendered yes
react-pdf can open a PDF file inside a React App. It displays a PDF file on the <canvas> element, a container for graphics in HTML. Install react-pdf: % yarn add react-pdf. It becomes part of dependencies in package.json: "dependencies": {"react-pdf": "^6.2.2"} react-pdf displays a PDF file using the Document component, with children of Page ...
Project Setup. To get started with React. Run the below command in the terminal to create a new React project. npx create-react-app pdf-gen. Change the directory to the project folder by running. cd pdf-gen. Next, let's install the required dependencies by running the below command.
The MovieList.jsx component contains most of the logic in this application. we import PDFDownloadLink from @react-pdf/renderer, this is basically an anchor tag that enables us to generate and download PDF documents.PDFDownloadLink accepts a document props which are the PDF template we will be creating soon using some of the React-primitives listed early in this post.
Adding Images to the PDF Document You can also render images in the PDF document with the Image component provided by the react-pdf library. The Image component allows you to display images in various formats such as JPEG, PNG, SVG, and many more.. The Image component takes a src prop that specifies the URL of the image and a style prop to add custom styles to your images.
To adapt your code for printing, you have to bypass the 2 main differences between a web page and a PDF: The components of a React application are dynamic whereas a PDF is a static file; A PDF has page breaks and a fixed size whereas a webpage is a "one page" app with a variable viewport size; From dynamic webpage to static rendering
React-PDF is a great resource for this. It is a bit time consuming converting your markup and CSS to React-PDF's format, but it is easy to understand. Exporting a PDF and from it is fairly straightforward. To allow a user to download a PDF generated by react-PDF, use their on the fly rendering, which provides a customizable download link. When ...
The TypeScript definition files of `@react-pdf-viewer` packages use `export type` syntax which is only available from TypeScript 3.8. Installing packages. 1. Installing pdfjs library. React PDF Viewer uses the APIs provided by the popular pdfjs library. Execute the following command from the root folder to install pdfjs:
How to Create PDF Reports in React. Adebola Adeniran In this article, we'll be building a button that generates a PDF document (like you see above) based on data from an API call. ... 14, 15); // we define the name of our PDF file. doc.save(`report_${dateStr}.pdf`); }; export default generatePDF; Create a component to save the tickets to be ...
Generating a PDF file from your React app can be easy with the right tool at hand. Watch this step-by-step guide to learn how you can export any React compon...
How can you export a React page to PDF in a simple and efficient way? This question has been asked by many developers who want to create PDF documents from their React components. In this Stack Overflow post, you will find some possible solutions using different libraries and tools, such as html2canvas, JSPDF, react-pdf, and more. You will also see some code examples and feedback from other ...
In part II of Carl Bergenhem's tutorial on exporting to PDF in React, he demonstrates a common exporting scenario: exporting invoices to PDF.He'll spice thin...
In this tutorial we'll covering the process of exporting a React component to a PDF file. We'll be using jsPDF to generate the PDF which can be installed by running: For the purposes of this tutorial we'll create a simple "shipping label" component which will contain an address and barcode image.
The KendoReact PDF Generator enables you to export a selection of or the entire content of a web page to a PDF file. With it, you can scale the content to better fit on the page, customize the paper size, change the page orientation, work with templates and use many others features that provide extensive control over the exported PDF file.
Export to PDF in React-Table. 1. Pdf download in React.js project. 1. React export Excel? 4. Export React Page to PDF. 5. Create a PDF document after click a button in React. 0. React to PDF options. Hot Network Questions How to deal as a PhD student with a working colleague who is doing private business during working hours?
React-PDF is under constant development. This documentation is written for React-PDF 7.x branch. If you want to see documentation for other versions of React-PDF, use dropdown on top of GitHub page to switch to an appropriate tag. Here are quick links to the newest docs from each branch: v7.x.
Create a new email. Select the fonts drop-down. Make sure Aptos does not have a cloud next to it. If the cloud is visible, click it to install the font. Navigate to C:\Users\<user>\AppData\Local\Microsoft\FontCache\4\CloudFonts\Aptos (Replace <user> with your username) Copy all font files (.ttf) from here.
Breaking a PDF into single chapters is useful if you want to provide the single chapters to a tool, such as a ChatBoot tool. On the other hand, you can easily use a Regular expression to detect the beginning of a Chapter. For example, in the PDF I wanted to convert, each Chapter begins with the following text: "Chapter n ".
I am encountering an issue with my React component re-rendering more often than expected. Despite using useMemo and useCallback to optimize performance, the component still re-renders unexpectedly.. I have a React component structured as follows:
Real gross domestic product (GDP) increased at an annual rate of 1.3 percent in the first quarter of 2024 (table 1), according to the "second" estimate released by the Bureau of Economic Analysis. In the fourth quarter of 2023, real GDP increased 3.4 percent. The GDP estimate released today is based on more complete source data than were available for the "advance" estimate issued last month.