The goal is to generate the PDF from your web application without requiring the backend component. There are a number of React libraries which allow you to create PDFs, for this purpose I am using jsPDF libraries.

jsPDF

jsPDF is open source JavaScript library where pdf files can be created within web applications. This software would be relevant especially in cases when you need to enable users to download receipts, invoices, quotations or any other documents for their records.

Installation

npm install jsPDF

yarn add jsPDF

Steps to implement the code into a project

Step -1

Open file and import jsPDF module.

import jsPDF from “jspdf”;

Step-2

Set up paper size, orientation, and units.

const doc =new jsPDF()

This sets the default size of paper to A4, portrait mode, and millimeters as the measuring unit.

In case we desire customized pape size and orientation we can use:

const doc= new jsPDF({

orientation:”landscape”,

unit:”in”,

formate:[4,2]

})

Step -3

We can now add any text we want into our PDF document.

doc. text(“Hello”, 15,15)

“Hello” will be added on the PDF and “Hello” will appear at coordinates (15,15).

Step -4

doc.save (“PDF”)

In which name should PDF is download and save that should be give in this save.

Full code:

import jsPDF from “jspdf”;

const doc =new jsPDF();

const doc = new jsPDF();

doc.text(“Hello” , 15,15)

doc.save(“pdf”)

Creating Tables with AutoTable Plugin

Need to create tables such as invoices or reports? jspdf-autotable makes it extremely simple.

Installation:

npm install jspdf jspdf-autotable

Example:

import jsPDF from “jspdf”;

import autoTable from “jspdf-autotable”;

const doc = new jsPDF();

autoTable(doc, {

head: [[“Name”, “Email”, “Country”]],

body: [[“ABC”, “abc@example.com”, “India”],
[“XYZ”, “xyz@example.com”, “India”]],

});

doc.save(“table.pdf”);

We can use HTML tables as input, merge cells and style the table among other things!

Inserting Images

For images, you can insert in PNG or JPEG formats (base64 or URL).

const imgData = “data:image/png;base64,…”;

doc.addImage(imgData, “PNG”, 10, 10, 50, 50);

This is great for inserting logos, product images and even headers.

Adding Custom Fonts

jsPDF has a method addFont which enables the use of custom fonts (TTF).

To customize your font upload via:


doc.addFileToVFS(“YourFont.ttf”, base64String);
doc.addFont(“YourFont.ttf”, “YourFont”, “normal”);
doc.setFont(“YourFont”);

This is super useful for branding or supporting non-Latin scripts.

Layout & Styling Features

JsPDF gives users a variety utility like:

setFontSize(size)

setTextColor(r, g, b)

rect(x, y, width, height)

Real Time Application

Generating invoices and receipts.

Issuing certificates.

Report or table printing.

Resumes for download.

Tickets or passes for events.

Leave a Reply