Hello friends, welcome back to my blog. Today in this blog post, I am going to show you, Reactjs Convert HTML into PDF working Functionality.
For reactjs and bootstrap 5 new comers, please check the below links:
Friends now I proceed onwards and here is the working code snippet for react ecommerce template free and please use this carefully to avoid the mistakes:
1. Firstly, we need fresh reactjs setup and for that, we need to run below commands into out terminal and also we should have latest node version installed on our system:
npx create-react-app reactpdf cd reactpdf
2. Now we need to run below commands into our project terminal to get, pdf genrator, bootstrap and related modules into our reactjs application:
npm install bootstrap --save npm install --save pdfmake npm install html-to-pdfmake npm install jspdf --save npm start //For start project
3. Finally for the main output, we need to add below code into our reactboot5/src/App.js file or if you have fresh setup then you can replace reactpdf/src/App.js file code with below code:
import React from 'react'; import '../node_modules/bootstrap/dist/css/bootstrap.min.css'; import jsPDF from 'jspdf'; import pdfMake from 'pdfmake'; import pdfFonts from 'pdfmake/build/vfs_fonts'; import htmlToPdfmake from 'html-to-pdfmake'; class App extends React.Component { printDocument() { //const input = document.getElementById('divToPrint'); const doc = new jsPDF(); //get table html const pdfTable = document.getElementById('divToPrint'); //html to pdf format var html = htmlToPdfmake(pdfTable.innerHTML); const documentDefinition = { content: html }; pdfMake.vfs = pdfFonts.pdfMake.vfs; pdfMake.createPdf(documentDefinition).open(); } render() { return ( <div className="App container mt-5"> <div id="divToPrint"> <h2>therichpost.com</h2> <table class="table table-bordered"> <thead> <tr> <th>Firstname</th> <th>Lastname</th> <th>Website</th> </tr> </thead> <tbody> <tr> <td>Ajay</td> <td>Malhotra</td> <td>Therichpost.com</td> </tr> <tr> <td>Ajay</td> <td>Malhotra</td> <td>Therichpost.com</td> </tr> <tr> <td>Ajay</td> <td>Malhotra</td> <td>Therichpost.com</td> </tr> <tr> <td>Ajay</td> <td>Malhotra</td> <td>Therichpost.com</td> </tr> <tr> <td>Jassa</td> <td>Malhotra</td> <td>Therichpost.com</td> </tr> </tbody> </table> </div> <button class="btn btn-primary" onClick={this.printDocument}>Export To PDF</button> </div> ) }; } export default App;
Now we are done friends. If you have any kind of query or suggestion or any requirement then feel free to comment below.
Note: Friends, I just tell the basic setup and things, you can change the code according to your requirements.
I will appreciate that if you will tell your views for this post. Nothing matters if your views will be good or bad.
Jassa
Thanks
hi ,how can I make jspdf with utf-8
cause this cant support utf-8
This supports UTF-8
hi, how can I add CSS and icons to pdf with pdfmake?
I will update you on this, thanks.