5 Steps to Create a PDF in React Using jsPDF
Step 1: Install modules or link to CDN
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.debug.js" integrity="sha384-NaWTHo/8YCBYJ59830LTz/P4aQZK1sS0SneOgAvhsIl3zBu8r9RevNg5lHCHAuQ/" crossorigin="anonymous"></script>
yarn add jspdf
Step 2: Import jsPDF
import jsPDF from 'jspdf';
Step 3: We create a new instance of the PDF object. We pass in some configuration settings including orientation, unit, and format as strings into the constructor function. Here are your options for these settings which are all strings.
Orientation: ‘p’ for portrait or ‘l’ for landscape
Unit: ‘p’ (points), ‘mm’, ‘cm’, ‘m’, ‘in’, or ‘px’. We will be positioning elements in the PDF using these units. I suggest using ‘px’ since that’s our common CSS unit of measurement.
Format: ‘letter’, ‘legal’, ‘ledger’, etc. You can also use the alphanumeric international paper size chart that ranges from ‘a0’ to ‘c10’. ‘a4’ translates to letter-sized paper.
var doc = new jsPDF('p', 'px', 'letter'); //orientation, unit, format
Step 4: We can add text to our PDF by calling the .text() method of our PDF object. We pass in our desired string into the first argument. Where will this text be placed in the PDF? The position is determined by the second and third arguments. The second argument is the number of units away from the left edge of the page. The third argument is the units away from the top edge. So, for our example, the string begins 200 px from the left edge and 50 px from the top edge. As you recall, we set the units to ‘px’ in step 3.
doc.text('hello world', 200, 50); //string, x-position, y-position
var image = new Image();
image.src = 'images/reactLogo.png';doc.addImage(image, 'PNG', 300, 80, 50, 50); //base64 image, format, x-coordinate, y-coordinate, width, height