written by Răzvan Puiu
In the article below we'll cover client-side PDF generation in JavaSript with jsPDF.
Getting started: Pick the installation that suits you best.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.debug.js" integrity="sha384-NaWTHo/8YCBYJ59830LTz/P4aQZK1sS0SneOgAvhsIl3zBu8r9RevNg5lHCHAuQ/" crossorigin="anonymous"> </script>
<script src="https://unpkg.com/jspdf@latest/dist/jspdf.min.js"></script>
npm install jspdf --save
yarn add jspdf
First you need to create a pdf document:
var pdf = new jsPDF('landscape', 'px', 'a4');
The jsPDF constructor gets the page orientation, the measuring unit and the page format as parameters. If not specified, them the defaults will be portrait, A4 and millimeters (mm). It supports the most common page formats, and each format contains the size so you can inspire from the library when building your pdf.
To add text at an absoulte position in your document you need to use:
pdf.text('Hello getPDFapi!', 123.45, 321.774);
The first argument is the text that needs to be displayed. The method supports adding multiline text when the argument is an array of Strings.
The next 2 parameters are X and Y coordinates in units delcared when constructing the jsPDF object.
The method also supports options
- a collection of settings that specify how the text should be encoded and transform
which will rotate the text by it's value around the anchor set by x and y.
Customizing your text further:
pdf.addFileToVFS('Roboto.ttf','YOUR_ENCODED_FONT');
pdf.setFontType('bold');
pdf.addFont('Roboto.ttf', 'Roboto', 'bold');
pdf.setFont('Roboto');
pdf.setFontSize(11);
pdf.text('text', 486.1876527655285, 101.14478267454187);
Let's break down the above code:
pdf.addImage(imageData, format, x, y, width, height, alias, compression, rotation)
imageData
should be either a base64 encoded image, ImageHTMLElement or Canvas-HTMLElementformat
(e.g "PNG", "WEBP") should be specified id the imageData type recognition fails or if the type of the image is Canvas-Element. The default for canvas is "JPEG".x and y
are the coordinates. They are represented in the units declared when initializing the jsPDF.widht and height
are also represented in the units declared when initializing the jsPDF.alias
can be specified if the image is used multiple times.compression
can be "NONE", "FAST", "MEDIUM" and "SLOW"rotation
0-359 degreesTables can be generated either directly from HTML attributes or manually.
<table id=”the-table”> </table>
pdf.autoTable({html:”#the-table”});