PDF Generator API
article illustrative cover on 3 js libraries

3 Ways to Generate PDF from HTML with JavaScript

Introduction

While PDFs offer advantages like printability and offline viewing, HTML provides benefits like searchability and accessibility. Users may choose to convert HTML to PDF for various reasons, such as creating printable receipts, archiving reports, or sharing content in a standardized format.

This article explores popular JavaScript libraries for HTML to PDF conversion. These libraries allow you to generate PDFs directly from your web pages without relying on server-side processing. We’ll also discuss the advantages and limitations of client-side (JavaScript-based) vs server-side generation approaches to help you choose the best method for your project. Finally, we’ll introduce PDFGeneratorAPI.com, a powerful server-side solution that simplifies the conversion process.

Comparison of Popular JavaScript Libraries for HTML to PDF Conversion

Here are three popular JavaScript libraries used to convert HTML to PDF:

  • HTML2PDF: A library that allows you to convert HTML content into PDF files using JavaScript.
  • Puppeteer: A Node.js library that provides a high-level API to control headless Chrome or Chromium browsers. It can be used for web scraping, automated testing, and generating PDFs from web pages.
  • jsPDF: A JavaScript library that generates PDFs directly from JavaScript. It allows you to create and manipulate PDF documents on the client-side without needing external dependencies or server-side processing.

Choosing the Right JavaScript Library for HTML to PDF Conversion

The following table compares these libraries across five key parameters to help you select the best option for your use case:

Featurehtml2pdfPuppeteerjsPDF
FunctionalityBasic conversion, Advanced layout control (with limitations)High-fidelity rendering, Limited layout controlGood image handling, Supports complex layouts, Supports images
Installation & SetupEasy (npm install)Moderate (requires Node.js)Easy (CDN or npm)
PerformanceModerateSlower (server-side)Fastest (client-side)
ComplexityLow (easy-to-use API)High (requires browser knowledge)Moderate (learning curve)
SecurityMitigated by server-side rendering if used that wayRelies on the browser security modelData processed on client-side, security depends on implementation
SpecialtyClient-side conversion, lightweightServer-side rendering, high fidelityClient-side conversion, lightweight

Step-by-Step Code Examples for Each Library

Here, we’ll provide step-by-step code examples to get you started with using each popular JavaScript library for HTML to PDF conversion.

While these libraries have specific requirements, a basic understanding of HTML, CSS, and JavaScript is generally beneficial for working with them. A text editor of your choice (like VS Code, but not mandatory) will help write and edit the code for web-to-PDF conversion.

HTML2PDF

Installation

You can install the HTML2PDF library using either npm (Node Package Manager) or by including it from a CDN (Content Delivery Network).

Installation via npm
If you’re using Node.js, you can install the HTML2PDF library as a dependency in our project using npm:

npm install html2pdf.js

After installing the library, you can import it into your JavaScript file:

const html2pdf = require('html2pdf.js');

Installation via CDN (Content Delivery Networks)

Alternatively, you can include the HTML2PDF library directly in your HTML file by adding a <script> tag that points to the library’s CDN URL.

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>HTML2PDF Example</title>
  <!-- Include the HTML2PDF library from the CDN -->
  <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js">
</script>
</head>

Prepare the HTML Content

Prepare the HTML content that you want to convert to allocate a <div> element with an id of content that contains the content we want to convert.

<body>
  <!-- Your HTML content goes here -->
  <div id="content">
    <h1>HTML to PDF Document Test</h1>

Generate PDF

Add JavaScript code to your HTML using the <script> tag as shown below.

 <!-- Your JavaScript code goes here -->
  <script>
    window.onload = function() {
      const element = document.getElementById('content');
      const options = {
        margin: 1,
        filename: 'my-document.pdf',
        image: { type: 'jpeg', quality: 0.98 },
        html2canvas: { scale: 2 },
        jsPDF: { unit: 'in', format: 'letter', orientation: 'portrait' }
      };


      // Promise-based usage:
      html2pdf().set(options).from(element).save();


      // Old monolithic-style usage:
      // html2pdf(element, options);
    }
  </script>

In the VS Code, the Live Server Extension will give a live preview of your page. Upon refreshing the page. Your page will be converted to PDF and downloaded on your Chrome Browser.

Puppeteer

Install Puppeteer

First, you need to install Puppeteer in your project. You can run the following command in your project’s directory.

npm install puppeteer

Import Puppeteer

In your JavaScript file, import the Puppeteer library:

const puppeteer = require('puppeteer');

Create a new Browser instance

Next, create a new browser instance using the Puppeteer.launch() method:

(async () => {
  const browser = await puppeteer.launch();
  // Your code will go here
})();

Create a new Page instance

Create a new page instance within the browser instance:

Replace 'https://example.com' with the URL of the HTML content you want to convert.
(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('https://example.com', { waitUntil: 'networkidle0' });
  // Your code will go here
})();

Generate the PDF

Use the page.pdf() method to generate a PDF from the current page:
This will generate a PDF file named output.pdf in the same directory as your JavaScript file. The format option specifies the paper size (in this case, A4).

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('https://example.com', { waitUntil: 'networkidle0' });
  await page.pdf({ path: 'output.pdf', format: 'A4' });
  await browser.close();
})();

Close the Browser instance

Finally, close the browser instance using the browser.close() method. You’ve now learned the simplest way to convert HTML to PDF using Puppeteer. Here’s the complete code:

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('https://example.com', { waitUntil: 'networkidle0' });
  await page.pdf({ path: 'output.pdf', format: 'A4' });
  await browser.close();
})();

jsPDF

Include jsPDF Library

First, you need to include the jsPDF library in your HTML file. You can download and include the library locally or use a CDN link. Here’s an example using a CDN link:

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

Prepare the HTML Content

Prepare the HTML content that you want to convert to a PDF by adding a <div> element with an id of content that contains the HTML content we want to convert to PDF.

<div id="content">
        <h2 style="color:green">
            PDF Generator Blog
        </h2>
        <h3>
            Generate PDF file using jsPDF library
        </h3>
        <div class="container">                    
            <input  type="button" value="Create PDF"              
                    onclick="generatePDF()">
        </div>
</div>

Add JavaScript code

Add JavaScript code to your HTML using the <script> tag below.

<script type="text/javascript">
        function generatePDF() {
            const { jsPDF } = window.jspdf;
            const doc = new jsPDF();
            doc.text("Hello world!", 100, 100);
            doc.save("newFile.pdf");                
        }            
    </script>

Click the Generate PDF button to download your PDF

Run the HTML in the browser and click the button to download.

Client-side vs. Server-side PDF Generation

Choosing between client-side and server-side PDF generation is a common question for developers. Both approaches offer distinct advantages and limitations, and the best choice depends on your specific project requirements.

Client-side

Client-side PDF generation creates PDF files directly in the user’s web browser using JavaScript libraries or APIs. No server-side processing is involved.

Advantages:

  • Improved Performance: Code executes directly on the client’s machine, leading to faster execution.
  • Reduced Server Load: Processing is offloaded to the client’s machine from the server.
  • Enhanced User Experience: Enables dynamic and interactive user interfaces.

Limitations:

  • Security Risks: Exposes sensitive logic and data to the client.
  • Inconsistent Execution: Different browsers and devices may interpret code differently, leading to inconsistencies.
  • Hardware Limitations: This feature relies on the client’s device capabilities, potentially impacting performance on older or less powerful devices.

Server-side

Server-side PDF generation involves creating PDF files on the server using server-side technologies like Node.js, Python, Ruby, or Java. This approach sends the HTML content from the client (web browser) to the server, which is processed and converted into a PDF file.

Advantages:

  • Security: Sensitive information and logic are not exposed to the client.
  • Reliability: Centralized processing reduces the risk of inconsistency across different browsers and devices.
  • Scalability: Easier to scale and manage server resources to handle increased demand.

Limitations:

  • Network Dependency: Performance can be impacted by network latency, especially for users with slow internet connections.
  • Server Overload: Heavy load can slow down client response times if the server becomes overloaded.
  • Limited Interactivity: More limited interactivity without frequent communication with the server, potentially affecting user experience.

Simplifying the Process with PDF Generator API

PDF Generator API is a server-side PDF generator that simplifies HTML to PDF conversion compared to JavaScript libraries. With its API, there’s no need to manage complex libraries or code. It offers several benefits:

  • No Installation Required: Use the API directly without installing software on your machine.
  • Simple Integration via HTTP requests: Integrate the API into your application using straightforward HTTP requests.
  • Powerful Rendering Engine: Delivers accurate HTML to PDF conversion with a powerful rendering engine.
  • Advanced Configuration Options: This option provides control over various aspects of the PDF, including page sizes, margins, headers, footers, watermarks, encryption, and more.
  • Scalable and High-Performance Infrastructure: Handles large workloads efficiently with its scalable infrastructure.
  • Cross-browser and Cross-platform Compatibility: Ensures consistent output across different browsers and platforms.
  • Secure Handling of Sensitive Data: Maintains data security through server-side conversion.

This lets you focus on data and templates instead of conversion logic, potentially improving scalability and performance.

JavaScript Libraries vs. PDF Generator API

The following table compares PDFGeneratorAPI.com’s API with JavaScript libraries like HTML2PDF and jsPDF.

AspectJavaScript LibrariesPDFGeneratorAPI.com (Server-Side)
Rendering SpeedSlower (limited by client-side browser resources)Faster (utilizes powerful server-side engines)
ScalabilityLimited (individual devices)Efficient (cloud infrastructure)
Cross-browser CompatibilityPotential issues due to browser differencesConsistent across browsers/platforms
HTML/CSS SupportLimited for complex layoutsComprehensive support for HTML, CSS, JavaScript
Advanced FeaturesFewer (coding required)Wide range (headers, footers, watermarks, encryption)
SecurityPotential risks (client-side handling)Secure server-side conversion
Resource UtilizationConsumes client’s device resourcesOffloads processing to the server
Maintenance and UpdatesManual updates requiredMaintained by the provider

Best Practices for Optimizing PDFs with PDF Generator API

Here are some best practices for optimizing PDFs when using PDF Generator API:

  • Clean and Well-Organized HTML: Ensure your HTML structure is clean and well-organized, using semantic elements appropriately.
  • CSS for Styling: Use CSS for styling your HTML content instead of inline styles or formatting elements like <font> or <b>.
  • Optimize Font Rendering: Leverage CSS techniques like font subsetting and data URIs to optimize font rendering and reduce file size.
  •  Minify your CSS: Mintify and JavaScript files to remove unnecessary whitespace, comments, and other redundant data.
  •   Enable compression by setting the compression parameter in your API request to reduce the final PDF file size.
  • Optimize image quality: Optimize image quality with the image quality parameter.

Integrating PDF Generator API.com into a web application

Obtaining an API key and secret

Before you use PDFGeneratorAPI.com, you must obtain an API key and API secret. Follow these steps:

  1. Go to https://pdfgeneratorapi.com/ and sign up for a free account.
  2. After signing up, access your account dashboard.
  3. From the dashboard, navigate to the Settings section.
  4. Scroll down to API Credentials to access your API key and secret.

Converting HTML to PDF with the SDK

PDF Generator API provides SDKs and libraries for various programming languages, making integrating their API into your web application easy. Let’s look at an example using their JavaScript SDK to generate PDFs.

import PDFGeneratorAPI from 'pdf-generator-api-client';
let defaultClient = PDFGeneratorAPI.ApiClient.instance;
// Configure Bearer (JWT) access token for authorization: JSONWebTokenAuth
let JSONWebTokenAuth = defaultClient.authentications['JSONWebTokenAuth'];
JSONWebTokenAuth.accessToken = "YOUR ACCESS TOKEN"

let apiInstance = new PDFGeneratorAPI.DocumentsApi();
let generate_document_request = new PDFGeneratorAPI.GenerateDocumentRequest(); // GenerateDocumentRequest | Request parameters, including template id, data and formats.
apiInstance.generateDocument(generate_document_request, (error, data, response) => {
  if (error) {
    console.error(error);
  } else {
    console.log('API called successfully. Returned data: ' + data);
  }
});

In the above example, we first import the PDF Generator API SDK and Configure Bearer (JWT) access token to generate a document for authorization. 

Next, we call the generatedocument method provided by the SDK, passing in the necessary data. You can find the SDK here.

 CodePen Reference

PDF Generator API has provided a CodePen example to help you get started and test code here. This CodePen demonstrates how to use their JavaScript SDK to convert HTML content to PDF and handle the generated PDF data.

You will need the following to write code in Codepen

  • API KEY
  • API Secret
  • Workspace Identifier
  • Template ID
  • JSON Data (optional)

Get your workplace identifier by going to your Account dashboard > Workplace > Identifier and Get your template ID through Account dashboard> Template > Template ID.

Fill in the boxes as shown and click Generate PDF to view your PDF.

Integrating PDF Generator API in your application

You can integrate it into your web application using the Open Editor endpoint.

Using Open Editor 

Use the Open Editor endpoint to generate a unique URL. You can get your URL by making a Postman request.

Set it as the src parameter to an iframe in Codepen to display the generated PDF. You can find an example here

After you have your unique URL from the Open Editor endpoint, you can display the PDF in an iframe with simple HTML on your dashboard.

  1. Click Dashboard 
  2. Click any Template Example 
  3. Then Click Add Data

Conclusion

This article has explored various approaches to converting HTML content into PDFs. We’ve discussed popular JavaScript libraries like html2pdf, Puppeteer, and jsPDF, each offering unique functionalities and use cases. We’ve also compared client-side and server-side generation methods, helping you understand their strengths and limitations. Finally, we introduced PDF Generator API as a powerful server-side solution for streamlined PDF generation. If PDF Generator API meets your needs, you can start by signing up here.