As a frontend developer, we get Data from API Responses all the times. And we render it on UI.
However, sometimes we might not want to display this data on UI. Instead we want it in a PDF that can be downloaded easily.
We will use jsPDF library to achieve this.
In some situations, we also might want to display data inside pdf in tabular form. For this purpose, we will use jsPDF-autotable library alongside jsPDf.
NB: jsPDF-autotable is and extension of jsPDF. You should use jsPDF-autotable only when you want pdf data to be displayed in tabular format.
STEP-1: Install it to your Project
A. Get jspdf
library- (npm link) npm install jspdf --save OR yarn install jspdf
OR (to try it with CDN)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
B. Get jspdf-autable
library- (npm link)
npm install jspdf-autotable --save OR yarn install jspdf-autotable
STEP-2: import libraries to your component
import jsPDF from "jspdf";
require('jspdf-autotable');
STEP-3: Use it in your Component
we make an array of animals.
const animals = ['Tiger', 'Lion', 'Jaguar']
Now we make a function that we want to run to generate PDF. we call it PrintPDF()
function.
const PrintPDF = () => {}
Inside this function we make an object of `jsPDF`
class that we imported earlier. we call it pdf.
const PrintPDF = () => {
const pdf = new jsPDF("p", "pt", "a4");
}
jsPDF class takes three arguments.
First one is ‘orientation’ that we have given ‘p’ (portrait).
Second one is unit that we have given ‘pt’.
Third one is document format size that we have given ‘a4’, because we want large size pdf.
It’s time to do some formatting of our PDF document.
pdf.setFontSize(30)
, 170, 40);
pdf.setTextColor(0, 0,255)
jspdf-autotable
with jspdf
which is an extension to the later one.const rows = animals
(as we want to show animals name as rows, so we copy the array)autoTable
function of jspdf-autotable
library with ‘pdf’ object of jspdf
class. And give it our arrays of columns
and rows
.pdf.save('list of animals);