How To Create PDF In ReactJS

Introduction

 
In this article, we will learn how to generate a PDF in ReactJS spplications. Generating a PDF of reports or invoices or any other documents in web application is the basic requirement. In this article we use the following libraries to create our pdf. Rendering React as a pdf is generally complex, but using these libraries we can generate it easily.
  1. html2canvas
  2. jsPDF 
Prerequisites
  • We should have basic knowledge of React.js and Web API.
  • Visual Studio and Visual Studio Code IDE should be installed on your system.
  • SQL Server Management Studio.

Create ReactJS Project

 
Let's create a React app by using this following command.
  1. npx create-react-app Matfrom  
Open the newly created project in Visual Studio Code. and install following packages using these command.
  1. npm install jspdf --save  
  2. npm install --save html2canvas   
In this demo we use Material UI for design, so let's install material ui in this application.
  1. npm install @material-ui/core --save      
Now install the Axios library by using the following command. Learn more about Axios.
  1. npm install --save axios   
Now let’s create a component named 'MatTable.js' and import the following packages in this component
  1. import jsPDF from 'jspdf';  
  2. import html2canvas from 'html2canvas';  
Now add the following code in this component.
  1. import React, { Component } from 'react'  
  2. import Table from '@material-ui/core/Table';  
  3. import TableBody from '@material-ui/core/TableBody';  
  4. import TableCell from '@material-ui/core/TableCell';  
  5. import TableContainer from '@material-ui/core/TableContainer';  
  6. import TableHead from '@material-ui/core/TableHead';  
  7. import TableRow from '@material-ui/core/TableRow';  
  8. import Paper from '@material-ui/core/Paper';  
  9. import axios from 'axios';  
  10. import jsPDF from 'jspdf';  
  11. import Button from '@material-ui/core/Button';  
  12. import './App.css';  
  13. import html2canvas from 'html2canvas';  
  14.   
  15. export class MatTable extends Component {  
  16.   constructor(props) {  
  17.     super(props)  
  18.     this.state = {  
  19.       ProductData: []  
  20.   
  21.     }  
  22.   }  
  23.   printDocument() {  
  24.     const input = document.getElementById('pdfdiv');  
  25.     html2canvas(input)  
  26.       .then((canvas) => {  
  27.         var imgWidth = 200;  
  28.         var pageHeight = 290;  
  29.         var imgHeight = canvas.height * imgWidth / canvas.width;  
  30.         var heightLeft = imgHeight;  
  31.         const imgData = canvas.toDataURL('image/png');  
  32.         const pdf = new jsPDF('p''mm''a4')  
  33.         var position = 0;  
  34.         var heightLeft = imgHeight;  
  35.         pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight);  
  36.         pdf.save("download.pdf");  
  37.       });  
  38.   }  
  39.   
  40.   componentDidMount() {  
  41.     axios.get('http://localhost:51760/Api/Emp/employee').then(response => {  
  42.       console.log(response.data);  
  43.       this.setState({  
  44.         ProductData: response.data  
  45.       });  
  46.     });  
  47.   }  
  48.   render() {  
  49.     console.log(this.state.ProductData);  
  50.     return (  
  51.       <div>  
  52.         <TableContainer id="pdfdiv" className="txt" component={Paper}>  
  53.           <Table stickyHeader aria-label="sticky table">  
  54.             <TableHead>  
  55.               <TableRow>  
  56.                 <TableCell>Id</TableCell>  
  57.                 <TableCell align="right">Name</TableCell>  
  58.                 <TableCell align="right">Age</TableCell>  
  59.                 <TableCell align="right">Address</TableCell>  
  60.                 <TableCell align="right">City</TableCell>  
  61.                 <TableCell align="right">ContactNum</TableCell>  
  62.                 <TableCell align="right">Salary</TableCell>  
  63.                 <TableCell style={{ paddingRight: "60px" }} align="right" >Department</TableCell>  
  64.               </TableRow>  
  65.             </TableHead>  
  66.             <TableBody>  
  67.               {  
  68.                 this.state.ProductData.map((p, index) => {  
  69.                   return <TableRow key={index}>  
  70.                     <TableCell component="th" scope="row">  
  71.                       {p.Id}  
  72.                     </TableCell>  
  73.                     <TableCell align="right">{p.Name}</TableCell>  
  74.                     <TableCell align="right">{p.Age}</TableCell>  
  75.                     <TableCell align="right">{p.Address}</TableCell>  
  76.                     <TableCell align="right">{p.City}</TableCell>  
  77.                     <TableCell align="right">{p.ContactNum}</TableCell>  
  78.                     <TableCell align="right">{p.Salary}</TableCell>  
  79.                     <TableCell style={{ paddingRight: "114px" }} align="right">{p.Department}</TableCell>  
  80.                   </TableRow>  
  81.                 })  
  82.               }  
  83.             </TableBody>  
  84.           </Table><br></br>  
  85.           <Button onClick={this.printDocument} variant="contained" color="primary">  
  86.             Generate Pdf  
  87.                                 </Button>  
  88.         </TableContainer>  
  89.   
  90.       </div>  
  91.   
  92.     );  
  93.   }  
  94. }  
  95.   
  96. export default MatTable  
Now open app.js file and add the following code.
  1. import React from 'react';  
  2. import logo from './logo.svg';  
  3. import './App.css';  
  4. import MatTable from './MatTable'  
  5. function App() {  
  6.   return (  
  7.     <div className="App">  
  8.       <MatTable/>  
  9.     </div>  
  10.   );  
  11. }  
  12.   
  13. export default App;  

Create a table in the database

 
Open SQL Server Management Studio, create a database named "Employee", and in this database, create a table. Give that table a name like "Employee".
  1. CREATE TABLE [dbo].[Employee](      
  2.     [Id] [int] IDENTITY(1,1) NOT NULL,      
  3.     [Name] [varchar](50) NULL,      
  4.     [Age] [int] NULL,      
  5.     [Address] [varchar](50) NULL,      
  6.     [City] [varchar](50) NULL,      
  7.     [ContactNum] [varchar](50) NULL,      
  8.     [Salary] [decimal](18, 0) NULL,      
  9.     [Department] [varchar](50) NULL,      
  10.  CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED       
  11. (      
  12.     [Id] ASC      
  13. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]      
  14. ) ON [PRIMARY]      
  15. GO    
Add a new demo data in this table.
 

Create a new Web API project

 
Open Visual Studio and create a new project.
 
How To Create PDF In ReactJS
 
Change the name to MatUITable.
 
How To Create PDF In ReactJS
 
Choose the template as Web API.
 
How To Create PDF In ReactJS
 
Right-click the Models folder from Solution Explorer and go to Add >> New Item >> data.
 
How To Create PDF In ReactJS

Click on the "ADO.NET Entity Data Model" option and click "Add".
 
How To Create PDF In ReactJS
 
Select EF Designer from the database and click the "Next" button.
 
How To Create PDF In ReactJS
 
Add the connection properties and select database name on the next page and click OK.
 
How To Create PDF In ReactJS
 
Check the "Table" checkbox. The internal options will be selected by default. Now, click the "Finish" button.
 
How To Create PDF In ReactJS
 
Now, our data model is successfully created.
 
Right-click on the Controllers folder and add a new controller. Name it as "Employee controller" and add the following namespace in the Employee controller
  1. using MatUITable.Models;   
Now add a method to fetch data from database. 
  1. [HttpGet]    
  2. [Route("employee")]    
  3. public object Getrecord()    
  4. {    
  5.     var emp = DB.Employees.ToList();    
  6.     return emp;    
  7. }    
Complete Employee controller code
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Net;    
  5. using System.Net.Http;    
  6. using System.Web.Http;    
  7. using MatUITable.Models;    
  8. namespace MatUITable.Controllers    
  9. {    
  10.     
  11.     [RoutePrefix("Api/Emp")]    
  12.     public class EmployeeController : ApiController    
  13.     {    
  14.         EmployeeEntities DB = new EmployeeEntities();    
  15.         [HttpGet]    
  16.         [Route("employee")]    
  17.         public object Getrecord()    
  18.     
  19.         {    
  20.             var emp = DB.Employees.ToList();    
  21.             return emp;    
  22.         }    
  23.     }    
  24. }   
Now, let's enable CORS. Go to Tools, open NuGet Package Manager, search for CORS, and install the "Microsoft.Asp.Net.WebApi.Cors" package. Open Webapiconfig.cs and add the following lines
  1. EnableCorsAttribute cors = new EnableCorsAttribute("*""*""*");          
  2. config.EnableCors(cors);  
Now go to visual studio code and run the project using 'npm start' command.
 
How To Create PDF In ReactJS
Click on the Button and check that the pdf is downloaded.
 
How To Create PDF In ReactJS

Summary

 
In this article we learned how to create pdf in Reactjs applications.