How to create a PDF file using React.js? React To PDF

24 February 2023 257 Reading time: 2 minute

You are developing web applications with React, one of the widely used javascript frameworks. You want a certain image (Component) to be saved as a pdf in one of the applications. So how can you do this? We can use the very useful "react-to-pdf" package created to convert any component into pdf in React.

To install the package, simply run the following npm command:

npm i react-to-pdf

After installing the package, you can simply create a pdf with react by following the steps below.

We include the ReactToPdf package in our file:

import ReactToPdf from 'react-to-pdf'

We create ref using

React.createRef() :

const ref = React.createRef();

We give the ref value that we created to the main tag of the section we want to include in the PDF as a prop.

Finally, you can complete the necessary processes to create a pdf by adding the values I gave below in the ReactToPdf tag.


<ReactToPdf targetRef={ref} filename="lorem.pdf">
    {({toPdf}) => (
       <button onClick={toPdf}>Generate pdf</button>
    )}
</ReactToPdf>

Combining what I have said, I would like to give the following codes as an example.


import React from 'react'
import ReactToPdf from 'react-to-pdf'
const ref = React.createRef();

export const App =()=> {
  return (
    <div>
      <ReactToPdf targetRef={ref} filename="lorem.pdf">
          {({toPdf}) => (
            <button onClick={toPdf}>Generate pdf</button>
          )}
      </ReactToPdf>
      <div ref={ref}>
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularized in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
      </div>
    </div>
  )
}

export default App;

Similar articles