pdf libraries

pdf libraries

Javascript

Javascript

Generating PDFs from HTML with jsPDF and javascript

Marcelo Abreu, Founder of pdforge,  picture

Marcelo | Founder

Marcelo | Founder

Jan 30, 2025

Jan 30, 2025

What is jsPDF and how can I use it to convert HTML to PDF?

Creating downloadable PDFs from HTML is a crucial feature for many SaaS platforms—especially for invoices, reports, or summaries. One popular approach is using jsPDF, a lightweight JavaScript library capable of generating PDFs on the client side without needing a backend.

In this guide, we’ll explore how to convert HTML to PDF using jsPDF, share best practices for styling and performance, and compare jsPDF to more advanced tools like Playwright, Puppeteer, or dedicated PDF APIs.

You can also check our jsPDF full documentation here.

Alternative PDF Libraries: How jsPDF Compares to Other Tools

jsPDF is the most popular PDF library on npm for generating PDFs purely in JavaScript.

Download montly for pdf generation javascript libraries

Libraries like Playwright or Puppeteer are widely used for rendering HTML into PDFs via headless browser instances. These tools offer greater accuracy in rendering CSS and are excellent for visually rich documents but come at the cost of increased resource usage.

Its client-side capabilities make it a great option for lightweight use cases where server resources are limited. But it's important to note that jsPDF is a low-level solution, like pdfmake or PDFKit.

If you want to go deep on a full comparison between pdf libraries in javascript for 2025, you can check out this guide.

guide on how to generate pdf reports with jsPDF
guide on how to generate pdf reports with jsPDF

Step 01: Setting Up jsPDF for HTML to PDF Conversion

You can install jsPDF via npm:

npm install jspdf

Or by including the CDN:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>

Here's a basic example of generating a PDF:

const { jsPDF } = window.jspdf;
const doc = new jsPDF();
doc.text("Hello World", 10, 10);
doc.save("document.pdf");

Step 02: Your First “Hello World” PDF

When converting HTML to PDF, keeping your HTML clean and structured is essential for accurate rendering. Here's an example of well-organized HTML and CSS that ensures clean outputs:

<!DOCTYPE html>
<html lang="en">
<head>
  <style>
    body {
      font-family: Arial, sans-serif;
    }
    .container {
      width: 80%;
      margin: auto;
      padding: 20px;
    }
    .header {
      text-align: center;
      margin-bottom: 30px;
    }
    .content {
      line-height: 1.6;
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="header">
      <h1>PDF Report Title</h1>
    </div>
    <div class="content">
      <p>This is the content of your PDF report. Keep it clean and structured.</p>
      <p>Additional data can go here.</p>
    </div>
  </div>
</body>
</html>

This minimal HTML, paired with CSS for layout and styling, ensures that the structure will remain consistent when converted into a PDF using jsPDF.

Step 03: Basic PDF Generation

Below are some jsPDF examples to create robust PDF documents:

  • Custom Text: Control fonts and colors:

doc.setFontSize(18);
doc.setFont("times", "italic");
doc.setTextColor(50, 50, 150);
doc.text("Custom PDF Title", 20, 30);
  • Image Support: Embed images directly into the PDF:

doc.addImage("imageURL", "JPEG", 10, 10, 180, 100);
  • Tables: Utilize the AutoTable plugin for structured data:

doc.autoTable({
  head: [['Name', 'Email']],
  body: [['Alice', 'alice@example.com'], ['Bob', 'bob@example.com']],
});
  • Adding pages: Multiple page documents

doc.addPage();

Heres an example of a complete pdf using only native jsPDF

Below is a self-contained JavaScript snippet demonstrating only jsPDF usage. It shows how to create a PDF with a heading, styled text, a table, and multiple sections (on separate pages). Make sure you have the jsPDF library included (e.g., via a <script> tag or npm import) before running this script.

<!DOCTYPE html>
<html>
<head>
  <title>jsPDF Example</title>
  <!-- Include jsPDF (UMD build) -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
</head>
<body>
  <button id="generatePdfBtn">Generate PDF</button>

  <script>
    document.getElementById("generatePdfBtn").addEventListener("click", () => {
      // Destructure jsPDF from the UMD module
      const { jsPDF } = window.jspdf;
      
      // Initialize a new jsPDF instance
      const doc = new jsPDF({
        orientation: 'portrait',
        unit: 'pt',      // points, 72pt = 1 inch
        format: 'letter' // 'letter' = 612 x 792 pt
      });
      
      // ----- Section 1: Heading & Custom Font -----
      doc.setFont("helvetica", "bold"); // font face, style
      doc.setFontSize(22);
      doc.text("My Awesome PDF Report", 40, 60);
      
      doc.setFontSize(12);
      doc.setFont("helvetica", "normal");
      doc.setTextColor(50, 50, 50);
      doc.text("This PDF was generated using only jsPDF, demonstrating multiple features and sections.", 40, 90);
      
      // ----- Section 2: Table (Using jsPDF's autoTable Plugin Alternative) -----
      // Note: If you want to create a table without plugins, we'll do a simplified approach.
      // For fully featured tables, you'd use 'jspdf-autotable' plugin, but here’s a basic approach using text() for demonstration.
      
      const tableData = [
        ["Name", "Age", "Email"],
        ["Alice", "25", "alice@example.com"],
        ["Bob", "30", "bob@example.com"],
        ["Charlie", "28", "charlie@example.com"],
      ];
      
      // Starting position for the table
      let startX = 40;
      let startY = 120;
      let rowHeight = 20;
      
      doc.setFont("helvetica", "bold");
      for (let rowIndex = 0; rowIndex < tableData.length; rowIndex++) {
        const row = tableData[rowIndex];
        
        // Reset X position for each row
        let currentX = startX;
        
        // If it's the header row, maybe set a background or different style
        if (rowIndex === 0) {
          doc.setTextColor(255, 255, 255); // white text
          // Draw a rectangle for header background
          doc.setFillColor(40, 40, 40);    // dark gray
          doc.rect(startX - 5, startY - 15, 350, rowHeight, 'F'); // x, y, width, height, style
        } else {
          doc.setTextColor(0, 0, 0); // revert to black text
        }
        
        // Print each cell
        row.forEach(cell => {
          doc.text(cell.toString(), currentX, startY);
          currentX += 100; // move horizontally for next cell
        });
        
        startY += rowHeight;
      }
      
      // ----- Section 3: Move to a New Page for More Content -----
      doc.addPage();
      
      doc.setFont("helvetica", "bold");
      doc.setFontSize(16);
      doc.setTextColor(60, 60, 180);
      doc.text("Additional Section on a New Page", 40, 60);
      
      doc.setFont("helvetica", "normal");
      doc.setFontSize(12);
      doc.setTextColor(0, 0, 0);
      doc.text("We can include more paragraphs, images, or further data here.", 40, 90);
      doc.text("Using multiple pages ensures your PDF remains organized and readable.", 40, 110);
      
      // Example second table or content
      doc.setFont("helvetica", "italic");
      doc.text("End of Report", 40, 160);
      
      // ----- Finally, Save the PDF -----
      doc.save("example-report.pdf");
    });
  </script>
</body>
</html>

Step 04: Convert HTML to PDF Using html2canvas

The html2canvas library is a powerful tool that captures HTML elements and renders them into canvas images, which can then be embedded into PDFs using jsPDF.

This approach allows for a more accurate representation of complex HTML layouts, including CSS styles and images, which jsPDF alone might not fully support. Here’s how you can use html2canvas with jsPDF to convert HTML to PDF:

html2canvas(document.getElementById('content')).then(function(canvas) {
  const imgData = canvas.toDataURL('image/png');
  const pdf = new jsPDF();
  pdf.addImage(imgData, 'PNG', 10, 10);
  pdf.save("document.pdf");
});

In this example, html2canvas captures the HTML element with the ID content, converts it into an image, and then jsPDF embeds that image into the PDF. This technique is ideal for preserving the exact look and feel of your HTML content, including complex layouts, images, and CSS.

Tip: Use HTML Template Engines

Using an HTML template engine like Handlebars can streamline the generation of dynamic PDFs by templating your HTML and filling it with data programmatically.

Here’s a basic example using Handlebars:

const template = `
  <div class="report">
    <h1>{{title}}</h1>
    <p>{{body}}</p>
  </div>
`;
const data = {
  title: "Dynamic PDF Report",
  body: "This report is generated from a template engine.",
};
const compiledTemplate = Handlebars.compile(template);
const html = compiledTemplate(data);
// Pass the compiled HTML into jsPDF or any other library

Alternative: Scaling PDF Generation with Third-Party APIs

homepage of pdforge

For larger SaaS platforms requiring automated PDF generation at scale, integrating a PDF Generation API like pdforge can offload the heavy lifting. This approach is ideal for SaaS platforms with high volumes of PDF requests.

With pdforge, you can create beautiful reports with flexible layouts and complex components with an easy-to-use opinionated no-code builder. Let the AI do the heavy lifting by generating your templates, creating custom components or even filling all the variables for you.

You can handle high-volume PDF generation from a single backend call.

Here’s an example of how to generate pdf with pdforge via an API call:

fetch('https://api.pdforge.com/v1/pdf/sync', {
  method: 'POST',
  body: JSON.stringify({ templateId: 'your-template' , data: {html:'your-html' } }),
  headers: { 'Authorization' : 'Bearer your-api-key' }
});

You can create your account, experience our no-code builder and create your first layout template without any upfront payment clicking here.

Conclusion

jsPDF is a powerful solution to convert HTML to PDF quickly on the client side. With the help of html2canvas and best practices like image compression and smart pagination, you can generate high-quality PDFs for invoices, reports, or summaries in your SaaS platform.

For more complex use cases—like large-scale PDF generation or advanced layouts—consider tools like Playwright, Puppeteer.

If you don't want to waste time maintaining pdfs layouts and their infrastructure or if you don't want to keep track of best practices to generate PDFs at scale, third-party PDF APIs like pdforge will save you hours of work and deliver a high quality pdf layout.

Generating pdfs at scale can be quite complicated!

Generating pdfs at scale can be quite complicated!

We take care of all of this, so you focus on what trully matters on your Product!

We take care of all of this, so you focus on what trully matters on your Product!

Try for free

7-day free trial

Table of contents

Title