In this tutorial, I'll cover How to Printing and download PDF file in React With React-To-Print. Scroll down to the end of the page to you can see the YouTube video(CodeAT21) and GitHub repository full source code available for this.

React using the React-To-Print components in the browser supports Chrome, Safari, Firefox, and EDGE. This is an npm package. This package aims to solve that ability to print out the component by popping up a new print window with CSS styles copied over as well.

Setup

First, we'll create the react project and install the one npm packages. In open your system terminal/command line enter the code below :

npx create-react-app react-print
cd react-print
npm install --save react-to-print
npm start 

Next, Project structure your folder as follows.

src
├── App.js
├── index.css
└── index.js 

Next, open up the App.js file located in the src folder. You should see this:

App.js
import React,{useRef} from 'react'; import { useReactToPrint } from "react-to-print"; const App = () => { const componentRef = useRef(); const handlePrint = useReactToPrint({ content: () => componentRef.current, }); return (<> <div class="print__section"> <div class="container"> <div class="row"> <div class="col-md-12"> <button onClick={handlePrint} className="print__button"> Print </button> <div ref={componentRef} className="card"> <div class="float__start"> <h3 class="card-title mb-0">Information</h3> </div> <hr /> <div class="float__infoss"> <ul> <li> Name : <span> Dr Andrew C S Koh </span> </li> <li> Email : <span> [email protected] </span> </li> <li> Gender : <span> Male </span> </li> <li> Date of Birth : <span> 07-24-1982</span> </li> <li> Phone No: <span> </span> 9856231456 </li> <li> Address : <span> 26 Wyle Cop, Shrewsbury, Shropshire, SY1 1XD </span> </li> <li> Website : <span> www.Andrew.com </span> </li> <li> Country : <span> United states </span> </li> </ul> </div> </div> </div> </div> </div> </div> </> ) } export default App

React pdf and download file using react-to-print

To get started with the react hook form library with npm install npm install --save react-to-print after import { useReactToPrint } from "react-to-print" into app.js.

  • It is easy and simple to use
  • useReactToPrint: This method is one of the parts of react-to-print
  • Supports all browsers: Chrome, Safari, Firefox, and EDGE