3 Ways to Generate PDF from HTML with JavaScript

article illustrative cover on 3 js libraries

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:

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 tag that points to the library’s CDN URL.

   HTML2PDF Example   

Prepare the HTML Content

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

   

HTML to PDF Document Test

Generate PDF

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

    

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:

Prepare the HTML Content

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

  

PDF Generator Blog

Generate PDF file using jsPDF library

Add JavaScript code

Add JavaScript code to your HTML using the tag below.

  

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:

Limitations:

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:

Limitations:

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:

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:

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

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.

PDF Generator API