pdforge logo

Product

Resources

Integrations

pdforge logo

Redirected from pdforge.com? You’re in the right place. we’re now pdf noodle!

Redirected from pdforge.com? You’re in the right place. we’re now pdf noodle!

Redirected from pdforge.com? You’re in the right place. we’re now pdf noodle!

Generating PDFs from HTML with jsPDF and javascript

Written by

Written by

Marcelo Abreu, Founder of pdforge,  picture

Marcelo | Founder at pdf noodle

Marcelo | Founder at pdf noodle

Last Updated

Last Updated

Jan 30, 2025

Jan 30, 2025

Tags

Tags

PDF Libraries

PDF Libraries

Javascript

Javascript

pdforge logo
pattern behind Call to action

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
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', '[email protected]'], ['Bob', '[email protected]']],
});
  • 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", "[email protected]"],
        ["Bob", "30", "[email protected]"],
        ["Charlie", "28", "[email protected]"],
      ];
      
      // 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: Convert HTML to PDF Using pdf noodle

Homepage of pdf noodle

Managing HTML-to-PDF conversion at scale can quickly become a nightmare!

Especially in serverless environments where cold starts, memory limits, and headless browser quirks love to break at the worst possible time (we even wrote a full article about it). Add constant template iterations, version control headaches, and the need to support non-technical contributors, and suddenly your “simple PDF library” turns into an ongoing engineering project.

pdf noodle eliminates all of that.

Instead of maintaining brittle infrastructure or wrestling with outdated pdf libraries, pdf noodle gives you a battle-tested PDF generation API that just works!

Fast, scalable, and designed for both developers and non-developers. You send raw HTML or use our AI-powered template builder, and pdf noodle handles the rendering, scaling, optimization, and delivery so your team doesn’t have to.

Here's an example of a simple API request to generate your pixel-perfect PDF with just a few lines of code:

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

pdf noodle also includes a powerful AI Agent that can generate PDF templates instantly, along with a modern editor for refining the design, also using AI, to match your brand. You don't need developing or design experience to quickly update layouts, adjust styling, and manage template versions.

Here’s a quick demo showing how it works:

You can create your account and design your first template without any upfront payment.

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 pdf noodle will save you hours of work and deliver a high quality pdf layout.

Generating pdfs can be annoying!

Let us help you make it easier while you focus on what truly matters for your company.

pdforge logo
pattern behind Call to action

Generating pdfs can be annoying!

Let us help you make it easier while you focus on what truly matters for your company.

pdforge logo
pattern behind Call to action

Generating pdfs can be annoying!

Let us help you make it easier while you focus on what truly matters for your company.

pdforge logo
pattern behind Call to action

Table of contents

Automate PDF Generation in minutes

No code or design experience needed

AI creates your template in seconds

Fine tune the design in our friendly builder

Generate PDFs with our API or integrations