In this article, we will learn about how to generate PDF in reactjs.
–First of all, we have to create a react application.
-Then import the below packages in your project.
npm i pdfmake npm i html2canvas
-Now open your app.js file and add the code given below :
import React, { useEffect, useState } from 'react' import { Row, Col, Table, Modal, Button, } from "react-bootstrap"; import html2canvas from "html2canvas"; import pdfMake from "pdfmake"; function App() { const download_pdf = () => { html2canvas(document.getElementById("appear")).then(canvas => { var data = canvas.toDataURL(); var pdfExportSetting = { content: [ { image: data, width: 500 } ] }; pdfMake.createPdf(pdfExportSetting).download("file.pdf"); }); } return ( <> <div className="myform"> <div id='appear'> <form class="form-floating"> <div class="mb-3"> <label for="exampleFormControlInput1" class="form-label">Name</label> <input type="name" name="name" value="ABC" class="form-control" id="exampleFormControlInput1" placeholder="name..." /> </div> <div class="mb-3"> <label for="exampleFormControlInput1" class="form-label">age</label> <input type="number" value="21" name="age" class="form-control" id="exampleFormControlInput1" placeholder="age.." /> </div> <div class="row"> <div class="col"> <label for="exampleFormControlInput1" class="form-label">state</label> <select class="form-select" id="floatingSelectGrid" value="Gujrat" aria-label="Floating label select example" name="state"> <option selected>--select state--</option> <option value="Gujrat"> Gujrat</option> <option value="Jharkhand">Jharkhand</option> <option value="Sikkim">Sikkim</option> </select> </div> <div class="col"> <label for="exampleFormControlInput1" class="form-label">city</label> <select class="form-select" id="floatingSelectGrid" value="Surat" aria-label="Floating label select example" name="city"> <option selected>--select city--</option> <option value="Surat">Surat</option> <option value="Jharkhand">Pune</option> <option value="Sikkim">Sikkim</option> </select> </div> </div> </form> <Table striped hover bordered className="mt-4"> <thead> <tr> <th>name</th> <th>age</th> <th>state</th> <th>city</th> </tr> </thead> <tbody> <tr> <td>ABC</td> <td>21</td> <td>Gujrat</td> <td>Surat</td> </tr> </tbody> </Table> </div> <button onClick={download_pdf}>Generate PDF</button> </div> </> ) } export default App
Here, click on Generate PDF button to create a pdf file.
– Using pdfMake we can easily create a pdf.
– Also in the download option we can specify a pdf file name.
– In html2canvas we have to add our id in div which will show content in the div.
– We can add any type of html content.
– It shows HTML code in a pdf file.
– pdfmake helps us to download forms and other documents related data dynamically.
OUTPUT: