How to Generate PDFs with JavaScript Using jsPDF — A Practical Guide

- Andrés Cruz - ES En español

How to Generate PDFs with JavaScript Using jsPDF — A Practical Guide

Generating PDFs with JavaScript is a very common requirement in modern web applications. In my case, I have encountered this need time and time again when building reporting systems, administrative dashboards, or data export modules, where users expect to be able to download reports in PDF format with a single click.

The good news is that today there are several JavaScript libraries that allow you to create, modify, and view PDF files directly from the browser, without depending on other languages or a complex backend. In this guide, I explain what options exist, when to use each one, and how to generate customized PDFs step by step with real examples.

Why Generate PDFs with JavaScript in Web Applications

The PDF format remains the standard for professional documents such as invoices, reports, contracts, and briefs. Its main advantage is that it keeps the design intact on any device, which is key when talking about official documents that the user needs to print or share.

From a web development perspective, generating PDFs with JavaScript has clear advantages:

  • Immediate response to the user, without server calls.
  • Lower load on the backend.
  • Ability to work even without an internet connection.
  • Greater visual control over the final outcome of the document.

Main JavaScript Libraries for Working with PDFs

Not all libraries serve the same purpose, and this is where many developers make the first mistake: choosing the wrong tool for the job. Reporting is a fundamental topic in any system; exporting data from a web page to PDF format is a very common task, and it can be easily accomplished through JavaScript libraries like the following:

  • JavaScript Reporting Server
  • jsPDF
  • ByteScout

On Google you can find a large number of libraries that perform conversions to PDF; however, jsPDF is the one that has convinced me the most due to its simplicity and how intuitive it is when creating documents from scratch.

jsPDF: Create PDFs from Scratch Easily

jsPDF is, without a doubt, one of the most popular libraries for generating PDFs with JavaScript. Personally, it is one of my favorites due to its simplicity and speed when building documents from scratch without complications.

It is ideal when you need to:

  • Generate PDF reports directly in the frontend.
  • Export tabular data or lists.
  • Create custom documents with text, images, and graphics.

PDF.js: View PDFs in the Browser

PDF.js, developed by Mozilla, is not meant for generating PDFs, but rather for viewing them directly in the browser using HTML5 and canvas. It is the same library that powers the built-in PDF viewer in Firefox.

It is perfect if your goal is to:

  • Display PDF documents embedded in a website without relying on browser plugins.
  • Add zoom, page navigation, or text search within the document.

But if what you are looking for is to create or modify PDFs, PDF.js is not the right tool: its purpose is exclusively visualization.

pdf-lib: Create and Modify Existing PDFs

pdf-lib is a very powerful alternative when you need to modify existing PDFs, fill out forms, or merge multiple documents into one.

It works in both the browser and Node.js and allows you to:

  • Edit existing PDFs without regenerating them from scratch.
  • Create and fill out interactive forms.
  • Manipulate pages, embed custom fonts, and merge documents.

Creating a PDF with jsPDF: Generating PDF Files Step by Step

jsPDF is a free JavaScript library, compatible with any type of project, that allows generating PDF files very easily and without depending on other languages. It is lightweight, fast, and with just a few lines of code we can have our reports ready for download.

The first thing we must do is download the library from its official repository on GitHub or install it via npm.

Once downloaded, we unzip it and add the dependency to our web page:

<script src="dist/jspdf.min.js"></script>

With the library imported, we can now use the entire API offered by jsPDF. The first thing is to create an object or instance of type jsPDF:

var doc = new jsPDF();

Creating a Basic PDF with Text and Images

Starting from that instance, the library provides a series of functions to perform the most common operations:

JavaScript PDF functions

Basically, jsPDF is designed to draw:

  • Lines.
  • Texts.
  • Images.
  • Geometric shapes.

If we wanted to generate a PDF with a title followed by an image, the result would look something like this:

JavaScript PDF example

To achieve this, it is enough to apply the following lines of code:

var doc = new jsPDF();

doc.setFontSize(40);
doc.text(40, 20, "Octocat loves jsPDF");

var imgData = 'data:image/jpeg;base64,...';
doc.addImage(imgData, 'JPEG', 10, 40, 180, 180);

doc.save('ejemplo.pdf');

Where:

  • The variable imgData refers to the image in base64 format.
  • The setFontSize() function specifies the font size.
  • The text() function adds text at the specified position (coordinates x, y).
  • The addImage() function adds an image at the specified position and size.
  • The save() function generates the file and triggers the download in the browser with the indicated name.

Customizing PDFs: Fonts, Colors, and Sizes

By placing the complete code we obtain a fully functional PDF:

var doc = new jsPDF();
var imgData = 'data:image/jpeg;base64,/ ...';
doc.setFontSize(40);
doc.text(40, 20, "Octocat loves jsPDF");
doc.addImage(imgData, 'JPEG', 10, 40, 180, 180);

And we get the following PDF:

Landscape Orientation, Metadata, and Text Alignment

Another very useful adjustment is to indicate that the PDF page has horizontal orientation (landscape). To do this, simply pass the corresponding parameter to the constructor and, optionally, define the document metadata with setProperties():

var doc = new jsPDF('landscape');
doc.text(20, 20, 'Hello landscape world!');

doc.setProperties({
  title: 'Report',
  subject: 'Data export',
  author: 'My application'
});

Landscape JavaScript PDF

Metadata of the Generated PDF

The setProperties() method allows defining internal metadata of the PDF file, such as the title, author, or keywords. This data is stored inside the document itself and is visible in the file properties:

var doc = new jsPDF();
doc.text(20, 20, 'This PDF has a title, subject, author, keywords and a creator.');
// Optional - set properties on the document
doc.setProperties({
    title: 'Title',
    subject: 'This is the subject',
    author: 'James Hall',
    keywords: 'generated, javascript, web 2.0, ajax',
    creator: 'MEEE'
});
// Output as Data URI
doc.save('Test.pdf');

Text Size in the PDF

To change the text size of the PDF we have the setFontSize() function. We can call it as many times as necessary to apply different sizes to different parts of the document:

var doc = new jsPDF();
doc.setFontSize(22);
doc.text(20, 20, 'This is a title');
doc.setFontSize(16);
doc.text(20, 30, 'This is some normal sized text underneath.');
doc.save('Test.pdf');

JavaScript PDF text size

Font Type in the PDF

We can also change the font type and its format with the setFont() and setFontType() methods respectively. jsPDF includes standard fonts like courier, times, and helvetica, with support for styles such as normal, italic, bold, and bolditalic:

var doc = new jsPDF();
doc.text(20, 20, 'This is the default font.');
doc.setFont("courier");
doc.text(20, 30, 'This is courier normal.');
doc.setFont("times");
doc.setFontType("italic");
doc.text(20, 40, 'This is times italic.');
doc.setFont("helvetica");
doc.setFontType("bold");
doc.text(20, 50, 'This is helvetica bold.');
doc.setFont("courier");
doc.setFontType("bolditalic");
doc.text(20, 60, 'This is courier bolditalic.');
doc.save('Test.pdf');

Coloring Text in the PDF

We can also assign colors to the texts of our PDF documents using the setTextColor() method, which accepts both grayscale values (a single number) and RGB values (three numbers separated by commas):

var doc = new jsPDF();
doc.setTextColor(100);
doc.text(20, 20, 'This is gray.');
doc.setTextColor(150);
doc.text(20, 30, 'This is light gray.');
doc.setTextColor(255,0,0);
doc.text(20, 40, 'This is red.');
doc.setTextColor(0,255,0);
doc.text(20, 50, 'This is green.');
doc.setTextColor(0,0,255);
doc.text(20, 60, 'This is blue.');
doc.save('Test.pdf');

JavaScript PDF text color

Text Alignment in the PDF

Text alignment is controlled through the same text() method, passing an additional parameter with the alignment value ('center', 'right') and, optionally, the rotation angle in degrees:

var pdf = new jsPDF('p', 'pt', 'letter');
    
pdf.text( 'This text is normally\raligned.', 140, 50 );
pdf.text( 'This text is centered\raround\rthis point.', 140, 120, 'center' );
pdf.text( 'This text is rotated\rand centered around\rthis point.', 140, 300, 45, 'center' );
pdf.text( 'This text is\raligned to the\rright.', 140, 400, 'right' );
pdf.text( 'This text is\raligned to the\rright.', 140, 550, 45, 'right' );
pdf.text( 'This single line is centered', 460, 50, 'center' );
pdf.text( 'This right aligned text\r\rhas an empty line.', 460, 200, 'right' );
pdf.save('Test.pdf');

JavaScript PDF text alignment

Drawing Geometric Shapes in the PDF

In all cases, common functions are used: the setDrawColor() method to indicate the stroke color and the setFillColor() method for the fill color. From there, each figure has its own dedicated method as you can see below:

Squares and Rectangles

var doc = new jsPDF();
doc.rect(20, 20, 10, 10); // empty square
doc.rect(40, 20, 10, 10, 'F'); // filled square
doc.setDrawColor(255,0,0);
doc.rect(60, 20, 10, 10); // empty red square
doc.setDrawColor(255,0,0);
doc.rect(80, 20, 10, 10, 'FD'); // filled square with red borders
doc.setDrawColor(0);
doc.setFillColor(255,0,0);
doc.rect(100, 20, 10, 10, 'F'); // filled red square
doc.setDrawColor(0);
doc.setFillColor(255,0,0);
doc.rect(120, 20, 10, 10, 'FD'); // filled red square with black borders
doc.setDrawColor(0);
doc.setFillColor(255, 255, 255);
doc.roundedRect(140, 20, 10, 10, 3, 3, 'FD'); //  Black square with rounded corners
doc.save('Test.pdf');

JavaScript PDF square

Lines

var doc = new jsPDF();
doc.line(20, 20, 60, 20); // horizontal line
doc.setLineWidth(0.5);
doc.line(20, 25, 60, 25);
doc.setLineWidth(1);
doc.line(20, 30, 60, 30);
doc.setLineWidth(1.5);
doc.line(20, 35, 60, 35);
doc.setDrawColor(255,0,0); // draw red lines
doc.setLineWidth(0.1);
doc.line(100, 20, 100, 60); // vertical line
doc.setLineWidth(0.5);
doc.line(105, 20, 105, 60);
doc.setLineWidth(1);
doc.line(110, 20, 110, 60);
doc.setLineWidth(1.5);
doc.line(115, 20, 115, 60);
doc.save('Test.pdf');

JavaScript PDF lines

Circles and Ellipses

var doc = new jsPDF();
doc.ellipse(40, 20, 10, 5);
doc.setFillColor(0,0,255);
doc.ellipse(80, 20, 10, 5, 'F');
doc.setLineWidth(1);
doc.setDrawColor(0);
doc.setFillColor(255,0,0);
doc.circle(120, 20, 5, 'FD');
doc.save('Test.pdf');

JavaScript PDF circles

Triangles

var doc = new jsPDF();
doc.triangle(60, 100, 60, 120, 80, 110, 'FD');
doc.setLineWidth(1);
doc.setDrawColor(255,0,0);
doc.setFillColor(0,0,255);
doc.triangle(100, 100, 110, 100, 120, 130, 'FD');
doc.save('My file.pdf');

JavaScript PDF triangles

All these examples have been extracted and adapted from the official documentation of jsPDF. You can download one of the examples at the following link:

When to Use jsPDF, PDF.js, or pdf-lib (Real Comparison)

After trying several options in real projects, this is my clear recommendation:

  • Use jsPDF if you need to generate PDFs from scratch directly in the frontend.
  • Use PDF.js if you only need to show or view PDFs within the browser.
  • Use pdf-lib if you must modify existing PDFs, merge documents, or work with complex forms.

Choosing the right library from the start will save you a lot of time and unnecessary refactorings later on.

Real Use Cases: Reports, Invoices, and Data Export

In real systems, generating PDFs with JavaScript is usually applied to:

  • Exporting administrative reports.
  • Downloadable invoices generated from the client side.
  • Customized reports per user or date range.
  • Summaries or data exports from dashboards or control panels.

jsPDF fits perfectly into these scenarios due to its simplicity, its zero backend dependency, and the visual control it offers over the final result.

Common Mistakes When Generating PDFs with JavaScript and How to Avoid Them

Some frequent mistakes I have seen (and made) when working with these libraries:

  • Using PDF.js to try to generate PDFs (that is not its purpose; it is a viewer, not a generator).
  • Not optimizing images before converting them to base64, which can generate huge files.
  • Not controlling content positions well using x and y coordinates, which causes overlaps.
  • Forgetting to define page size and orientation when instantiating new jsPDF(), always using default values.

Keeping these points in mind from the start considerably improves the final result and saves you hours of debugging.

Frequently Asked Questions About PDFs with JavaScript

  • How to generate a PDF with JavaScript?
    • Using libraries like jsPDF or pdf-lib, which allow creating PDF files directly from the browser without needing a backend.
  • Which JavaScript library is best for creating PDFs?
    • For generation from scratch, jsPDF is the simplest and best-documented option. To modify existing PDFs or work with forms, pdf-lib is more powerful and flexible.
  • Can a PDF be generated purely with frontend, without a backend?
    • Yes, completely. Both jsPDF and pdf-lib work perfectly in the browser without requiring any server.
  • What is the current version of jsPDF?
    • At the time of writing this article, the stable version is jsPDF 2.5.1. You can always check the latest version in its official repository on GitHub.

Conclusion

Generating PDFs with JavaScript is a practical, powerful, and increasingly widespread solution in modern web applications. After trying several libraries, my recommendation is clear: choose the tool according to your real need, not out of trend or because of what you see in the first tutorial you find.

If you are looking for simplicity and speed to generate reports directly on the client side, jsPDF is a safe bet. If you need something more advanced, such as manipulating existing documents or managing complex forms, pdf-lib can take your documents to the next level.

Learn how to generate PDF files from scratch using JavaScript and jsPDF. A step-by-step guide featuring real-world examples of text, images, fonts, and geometric shapes.


Únete a la comunidad de desarrolladores que han decidido dejar de picar código y empezar a construir productos reales. Recibe mis mejores trucos de arquitectura cada semana:

I agree to receive announcements of interest about this Blog.