How to Generate a PDF file in React

How to Generate a PDF file in React

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.

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.

npx create-react-app Matfrom  

Open the newly created project in Visual Studio Code. and install following packages using these command.

npm install jspdf --save  
npm install --save html2canvas   

In this demo we use Material UI for design, so let's install material ui in this application.

npm install @material-ui/core --save 

Now install the Axios library by using the following command. Learn more about Axios

npm install --save axios   

Now let’s create a component named 'MatTable.js' and import the following packages in this component

import jsPDF from 'jspdf';  
import html2canvas from 'html2canvas';  

Now add the following code in this component.

import React, { Component } from 'react'  
import Table from '@material-ui/core/Table';  
import TableBody from '@material-ui/core/TableBody';  
import TableCell from '@material-ui/core/TableCell';  
import TableContainer from '@material-ui/core/TableContainer';  
import TableHead from '@material-ui/core/TableHead';  
import TableRow from '@material-ui/core/TableRow';  
import Paper from '@material-ui/core/Paper';  
import axios from 'axios';  
import jsPDF from 'jspdf';  
import Button from '@material-ui/core/Button';  
import './App.css';  
import html2canvas from 'html2canvas';  
  
export class MatTable extends Component {  
  constructor(props) {  
    super(props)  
    this.state = {  
      ProductData: []  
  
    }  
  }  
  printDocument() {  
    const input = document.getElementById('pdfdiv');  
    html2canvas(input)  
      .then((canvas) => {  
        var imgWidth = 200;  
        var pageHeight = 290;  
        var imgHeight = canvas.height * imgWidth / canvas.width;  
        var heightLeft = imgHeight;  
        const imgData = canvas.toDataURL('image/png');  
        const pdf = new jsPDF('p', 'mm', 'a4')  
        var position = 0;  
        var heightLeft = imgHeight;  
        pdf.addImage(imgData, 'JPEG', 0, position, imgWidth, imgHeight);  
        pdf.save("download.pdf");  
      });  
  }  
  
  componentDidMount() {  
    axios.get('http://localhost:51760/Api/Emp/employee').then(response => {  
      console.log(response.data);  
      this.setState({  
        ProductData: response.data  
      });  
    });  
  }  
  render() {  
    console.log(this.state.ProductData);  
    return (  
      <div>  
        <TableContainer id="pdfdiv" className="txt" component={Paper}>  
          <Table stickyHeader aria-label="sticky table">  
            <TableHead>  
              <TableRow>  
                <TableCell>Id</TableCell>  
                <TableCell align="right">Name</TableCell>  
                <TableCell align="right">Age</TableCell>  
                <TableCell align="right">Address</TableCell>  
                <TableCell align="right">City</TableCell>  
                <TableCell align="right">ContactNum</TableCell>  
                <TableCell align="right">Salary</TableCell>  
                <TableCell style={{ paddingRight: "60px" }} align="right" >Department</TableCell>  
              </TableRow>  
            </TableHead>  
            <TableBody>  
              {  
                this.state.ProductData.map((p, index) => {  
                  return <TableRow key={index}>  
                    <TableCell component="th" scope="row">  
                      {p.Id}  
                    </TableCell>  
                    <TableCell align="right">{p.Name}</TableCell>  
                    <TableCell align="right">{p.Age}</TableCell>  
                    <TableCell align="right">{p.Address}</TableCell>  
                    <TableCell align="right">{p.City}</TableCell>  
                    <TableCell align="right">{p.ContactNum}</TableCell>  
                    <TableCell align="right">{p.Salary}</TableCell>  
                    <TableCell style={{ paddingRight: "114px" }} align="right">{p.Department}</TableCell>  
                  </TableRow>  
                })  
              }  
            </TableBody>  
          </Table><br></br>  
          <Button onClick={this.printDocument} variant="contained" color="primary">  
            Generate Pdf  
                                </Button>  
        </TableContainer>  
  
      </div>  
  
    );  
  }  
}  
  
export default MatTable  

Now open app.js file and add the following code.

import React from 'react';  
import logo from './logo.svg';  
import './App.css';  
import MatTable from './MatTable'  
function App() {  
  return (  
    <div className="App">  
      <MatTable/>  
    </div>  
  );  
}  
  
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".

CREATE TABLE [dbo].[Employee](      
    [Id] [int] IDENTITY(1,1) NOT NULL,      
    [Name] [varchar](50) NULL,      
    [Age] [int] NULL,      
    [Address] [varchar](50) NULL,      
    [City] [varchar](50) NULL,      
    [ContactNum] [varchar](50) NULL,      
    [Salary] [decimal](18, 0) NULL,      
    [Department] [varchar](50) NULL,      
 CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED       
(      
    [Id] ASC      
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]      
) ON [PRIMARY]      
GO    

Add a new demo data in this table.

Create a new Web API project

Open Visual Studio and create a new project.

Change the name to MatUITable.

Choose the template as Web API.

Right-click the Models folder from Solution Explorer and go to Add >> New Item >> data.

Click on the "ADO.NET Entity Data Model" option and click "Add".

Select EF Designer from the database and click the "Next" button.

Add the connection properties and select database name on the next page and click OK.

Check the "Table" checkbox. The internal options will be selected by default. Now, click the "Finish" button.

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

using MatUITable.Models;   

Now add a method to fetch data from database.

[HttpGet]    
[Route("employee")]    
public object Getrecord()    
{    
    var emp = DB.Employees.ToList();    
    return emp;    
}    

Complete Employee controller code

using System;    
using System.Collections.Generic;    
using System.Linq;    
using System.Net;    
using System.Net.Http;    
using System.Web.Http;    
using MatUITable.Models;    
namespace MatUITable.Controllers    
{    
    
    [RoutePrefix("Api/Emp")]    
    public class EmployeeController : ApiController    
    {    
        EmployeeEntities DB = new EmployeeEntities();    
        [HttpGet]    
        [Route("employee")]    
        public object Getrecord()    
    
        {    
            var emp = DB.Employees.ToList();    
            return emp;    
        }    
    }    
}   

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

EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");          
config.EnableCors(cors);  

Now go to visual studio code and run the project using 'npm start' command.

Click on the Button and check that the pdf is downloaded.

Summary

In this article we learned how to create pdf in Reactjs applications.Thank you for reading !

How to Share Code Between React and React Native

How to Share Code Between React and React Native

Learn how to share code between React and React Native to avoid duplicating logic. Sharing Code Between React and React-Native: What Not to Share. This question of sharing code between React and React Native, in fact, one of the hot topics among React and React native developers all over the world. React and React-Native allow a learn once write anywhere paradigm. This is great, because one tech team can build both your web app and native mobile experience. The problem is developers hate writing things twice. There have been a couple of efforts to build a unifying technology to write an application once and have it work on both web and native.

How to Share Code Between React and React Native

Sharing Code Between React and React-Native: What Not to Share - Ben Ellerby

React and React-Native allow a learn once write anywhere paradigm. This is great, because one tech team can build both your web app and native mobile experience. The problem is developers hate writing things twice. There have been a couple of efforts to build a unifying technology to write an application once and have it work on both web and native. Yet this is not always the best approach. There is value in only sharing your business and state logic; keeping your render code separate.

In this talk I will give real examples from my work with MADE.COM, migrating their web and mobile application to React and React-Native with code sharing as a primary objective.

How to Share Code Between React and React Native

Learn how to share code between React and React Native to avoid duplicating logic

Sharing Code Between React and React Native

React and React-Native allow a learn once write anywhere paradigm. This is great, because one tech team can build both your web app and native mobile experience. The problem is developers hate writing things twice. There have been a couple of efforts to build a unifying technology to write an application once and have it work on both web and native. Yet this is not always the best approach. There is value in only sharing your business and state logic; keeping your render code separate.

Hire React Js Developer from Expert React JS Development Company

Hire React Js Developer from Expert React JS Development Company

Are you looking to [hire React JS developer](https://www.mobiwebtech.com/react-js-development-company/ "hire React JS developer") from a prestigious and reliable React JS development company? Visit at Mobiweb Technologies here we have a big team...

Are you looking to hire React JS developer from a prestigious and reliable React JS development company? Visit at Mobiweb Technologies here we have a big team of expert React JS developers, you can hire them on an hourly, weekly or monthly basis for the successful completion of your dream project.

10 Best React Loading Component for Your App

10 Best React Loading Component for Your App

If you are unable to shorten the process, you should at least try to make the wait pleasant for your users. Here are 10 react loading components for your react.js application

While instant feedback from an app or website is best, sometimes your product won't be able to adhere to speed guidelines. The slow response may be due to poor internet connection or the operation process may take a long time. For such cases, the designer must reassure the user that:
The application is working according to their requirements and the actual process is still active.

If you are unable to shorten the process, you should at least try to make the wait pleasant for your users. Here are 10 react loading components for your react.js application

1. Create React Content Loader

Have you heard about react-content-loader? It's a SVG component to create placeholder loading, like Facebook cards loading or also known as skeleton UI. So now you can use this online tool to create your own loader easily. You just need to draw using the canvas or code using the live editing!

View Demo: https://danilowoz.com/create-content-loader/

Github: https://github.com/danilowoz/create-content-loader

Download Link: https://github.com/danilowoz/create-content-loader/archive/master.zip

2. react-loading

React-Loading is a React-based Loading animation component library includes many exquisite and beautiful loading components. It will effectively relieve the user's anxiety when you give loading dynamics tips at the appropriate place and moment in your project. This component library supports on-demand loading, so pick a favorite Loading component now to enrich your project

View Demo: http://139.196.82.33:8080/iframe.html?id=demo--demo

Github: https://github.com/sixiaodong123/react-loading

Download Link: https://github.com/sixiaodong123/react-loading/archive/master.zip

3. react-simple-infinite-loading

Someone pointed out the React implementation of the list was a bit complex. I figure out it was possible to write an abstraction for this particular case. Here it is!

This component aims to stay easy to use. If your use case needs more options I recommend using directly awesome libraries from Brian Vaughn listed in dependencies section.

View Demo: https://codesandbox.io/s/magical-shockley-vhkz8

Github: https://github.com/frinyvonnick/react-simple-infinite-loading

Download Link: https://github.com/frinyvonnick/react-simple-infinite-loading/archive/master.zip

4. react-pure-loaders

React Pure Loaders is a package that disponibilizes loaders for your Project. Those loaders are used as components, using color and a loading variables as properties.

The component expects the to receive the color as a string with the hexadecimal code and the loading as a boolean, that is true by default.

View Demo: https://reactpureloaders.io/

Github: https://github.com/jameswlane/react-pure-loaders

Download Link: https://github.com/jameswlane/react-pure-loaders

5. react-loadcon

React component to manipulate the favicon, as a loading or progress indicator, for now. The idea of "Favicon as DOM" is under construction.

View Demo: https://foreseaz.github.io/react-loadcon/

Github: https://github.com/foreseaz/react-loadcon

Download Link: https://github.com/foreseaz/react-loadcon/archive/master.zip

6. React Nested Loader

The easiest way to manage loaders/errors inside a button. NOT an UI lib.

  • Manage loading/error state of nested views/buttons triggering async actions
  • Not an UI lib, you provide the UI. Works with ReactNative.
  • No boilerplate at all, no need to use setState/Redux

View Demo: https://codesandbox.io/s/w640yv5p9w

Github: https://github.com/slorber/react-nested-loader

Download Link: https://github.com/slorber/react-nested-loader/archive/master.zip

7. react-wait

react-wait is a React Hook helps to manage multiple loading states on the page without any conflict. It's based on a very simple idea that manages an Array of multiple loading states. The built-in loader component listens its registered loader and immediately become loading state.

View Demo: https://codesandbox.io/s/y3w5v5lk0j

Github: http://github.com/f/react-wait

Download Link: https://reactjsexample.com/complex-loader-management-hook-for-react/

8. React Redux Loading Bar

A React component that provides Loading Bar (aka Progress Bar) for long running tasks.

Consists of:

  • React component — displays loading bar and simulates progress
  • Redux reducer — manages loading bar's part of the store
  • (optional) Redux middleware — automatically shows and hides Loading Bar for actions with promises

View Demo: https://mironov.github.io/react-redux-loading-bar/

Github: http://github.com/mironov/react-redux-loading-bar

Download Link: https://github.com/mironov/react-redux-loading-bar/archive/master.zip

9. Material UI Image

Images are ugly until they're loaded. Materialize it with material image! It will fade in like the material image loading pattern suggests.

View Demo: https://mui.wertarbyte.com/#material-ui-image

Github: http://github.com/TeamWertarbyte/material-ui-image

Download Link: https://github.com/TeamWertarbyte/material-ui-image/archive/master.zip

10. React Lazy Load Image Component

React Component to lazy load images and other components/elements. Includes a HOC to track window scroll position to improve performance.

React Component to lazy load images and components using a HOC to track window scroll position.

View Demo: https://www.albertjuhe.com/react-lazy-load-image-component/

Github: http://github.com/Aljullu/react-lazy-load-image-component

Download Link: https://github.com/Aljullu/react-lazy-load-image-component/archive/master.zip