HTML to PDF in JavaScript: 5 libraries compared (2026)
Table of contents
- Nutrient — Document platform with SDKs and APIs. Full CSS, viewing, signing, redaction.
- html2pdf.js — Simple client-side exports. Limited CSS support.
- jsPDF — Build PDFs programmatically from data. Selectable text, no HTML input.
- pdfmake — Structured documents from JSON data. Manual configuration.
- Playwright — Full CSS support, server-side. Requires infrastructure.
How to convert HTML to PDF in JavaScript
The simplest way to convert HTML to PDF in JavaScript is with html2pdf.js. Add the library via CDN, select your HTML element, and call html2pdf().from(element).save().
// Include via CDN: https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.jsconst element = document.getElementById('content');html2pdf().from(element).save('document.pdf');This works for simple documents. For better CSS support, use Playwright (server-side) or Nutrient (managed API). For structured data like invoices, use pdfmake.
Five ways to convert HTML to PDF in JavaScript
JavaScript developers have five main approaches, each with different tradeoffs:
- HTML-to-image libraries (html2pdf.js) — Quick setup, converts HTML to canvas then PDF
- Programmatic builders (jsPDF, pdfmake) — Build PDFs from data, selectable text
- Server-side automation (Playwright) — High fidelity, full CSS support
- Document platforms (Nutrient) — SDKs and APIs with viewing, signing, and more
- Custom solutions — Full control but significant development overhead
This guide covers the first four options, comparing their capabilities, performance, and ideal use cases.
Open source vs. commercial: Tradeoffs
Open source libraries (html2pdf.js, pdfmake, Playwright) are free to use and work well for many use cases. Commercial solutions like Nutrient add features that matter for larger deployments:
| Consideration | Open source | Nutrient |
|---|---|---|
| Cost | Free | Subscription after free tier |
| Support | Community forums | Dedicated support, SLAs |
| CSS support | Varies by library | Full CSS3 |
| Infrastructure | Self-managed | Managed or self-hosted |
| Compliance | DIY | SOC 2, encryption included |
Choose based on your scale, support needs, and feature requirements.
Nutrient
Nutrient is a document processing platform with SDKs for web, iOS, Android, .NET, Java, and Node.js. Beyond HTML-to-PDF conversion, it handles viewing, annotations, eSignatures, redaction, OCR, and AI-powered extraction.
For HTML-to-PDF conversion, Nutrient offers several options.
- Document Engine — Self-hosted server API with full CSS support. Converts HTML forms into fillable PDF fields. Chain operations like merging, watermarking, and page manipulation in one call.
curl -X POST http://localhost:5000/api/build \ -H "Authorization: Token token=<API token>" \ -F page.html=@/path/to/page.html \ -F instructions='{ "parts": [{ "html": "page.html" }] }' \ -o result.pdf- Processor API — Cloud-hosted API for serverless workflows. Supports PDF generation, conversion, OCR, and batch processing.
// Node.js example// This code requires Node.js. Do not run this code directly in a web browser.
const axios = require('axios')const FormData = require('form-data')const fs = require('fs')
const formData = new FormData()formData.append('html', fs.createReadStream('index.html'))
(async () => { try { const response = await axios.post('https://api.nutrient.io/processor/generate_pdf', formData, { headers: formData.getHeaders({ 'Authorization': 'Bearer your_api_key_here' }), responseType: "stream" })
response.data.pipe(fs.createWriteStream("result.pdf")) } catch (e) { const errorString = await streamToString(e.response.data) console.log(errorString) }})()
function streamToString(stream) { const chunks = [] return new Promise((resolve, reject) => { stream.on("data", (chunk) => chunks.push(Buffer.from(chunk))) stream.on("error", (err) => reject(err)) stream.on("end", () => resolve(Buffer.concat(chunks).toString("utf8"))) })}- .NET SDK — Chrome-based rendering for local files and live URLs.
- Mobile SDKs (Android and iOS) — Generate PDFs from HTML on-device.
- No-code (Zapier and Power Automate) — Convert templates and form submissions without code.
Features not available in open source libraries
- Form field conversion — HTML form elements become fillable PDF fields automatically
- Chained operations — Merge, watermark, and manipulate pages in a single API call
- Cross-platform consistency — Same rendering engine across web, iOS, Android, and server
- Enterprise support — SLAs, dedicated support, long-term maintenance
- Compliance — SOC 2 Type 2 audited, encryption, audit trails
html2pdf.js
html2pdf.js is a client-side library that works for prototypes and simple applications. It produces image-based output without text selection and can run into browser memory limits with large documents.
The html2pdf(opens in a new tab) library converts HTML pages to PDFs in the browser. It uses html2canvas(opens in a new tab) and jsPDF(opens in a new tab) under the hood. html2canvas renders an HTML page into a canvas element and turns it into a static image. jsPDF then takes the image and converts it to a PDF file.
Check out our blog on how to convert HTML to PDF using React for a step-by-step guide on how to use jsPDF in a React app.
Installation options
You can install html2pdf.js in three ways:
- CDN — Add a
scripttag to your HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>- npm —
npm install html2pdf.js - Manual download — Grab the bundle from GitHub(opens in a new tab) and include it with a script tag
<script src="html2pdf.bundle.min.js"></script>Convert HTML to PDF using html2pdf
Define a generatePDF() function to get the HTML element and convert it to PDF. Call this function from a download button:
<!DOCTYPE html><html>10 collapsed lines
<head> <!-- html2pdf CDN link --> <script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script> </head> <body> <button id="download-button">Download as PDF</button> <div id="invoice"> <h1>Our Invoice</h1> </div>
<script> const button = document.getElementById("download-button");
function generatePDF() { // Choose the element that your content will be rendered to. const element = document.getElementById("invoice"); // Choose the element and save the PDF for your user. html2pdf().from(element).save(); }
button.addEventListener("click", generatePDF); </script> </body></html>This example renders only the h1 element, but you can render any HTML element, including images and tables.
To test this example locally, run a quick static server with:
npx serve -l 4111 .Then open http://localhost:4111(opens in a new tab) in your browser to interact with the PDF download button.

Open PDF in new tab (instead of downloading)
Sometimes you want to display the PDF in a new browser tab rather than trigger a download. Use outputPdf('blob') to get a Blob. Then create a URL:
function openPDFInNewTab() { const element = document.getElementById("invoice"); html2pdf() .from(element) .outputPdf("blob") .then((blob) => { const url = URL.createObjectURL(blob); window.open(url, "_blank"); });}This works well for previews or when users want to review before saving.
Advanced example: Downloading an invoice as a PDF
You can download an invoice template as a PDF by clicking this link. You can also generate the HTML for your own invoice on your backend if you prefer.
As in the previous example, the generatePDF() function downloads the invoice as a PDF. This time, the invoice template renders to the div element.
The end result will look like what’s shown below.

Common issues with html2pdf.js in production
Typical problems — Blurry output, memory crashes with large documents, and inconsistent mobile rendering. Nutrient Web SDK addresses these issues while still supporting client-side operation.
jsPDF (standalone)
jsPDF(opens in a new tab) is the underlying library that html2pdf.js uses, but you can use it directly for more control. It’s ideal when you need to build PDFs programmatically with text, images, and shapes — without converting HTML.
Installation
npm install jspdfOr via CDN:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>Basic example with text and images
const { jsPDF } = window.jspdf;
function generatePDF() { const doc = new jsPDF();
// Add text. doc.setFontSize(22); doc.text("Invoice", 20, 20);
doc.setFontSize(12); doc.text("Date: February 6, 2026", 20, 35); doc.text("Total: $150.00", 20, 45);
// Add a line. doc.setDrawColor(0); doc.line(20, 50, 190, 50);
// Add items. doc.text("Item 1 - Widget", 20, 60); doc.text("$50.00", 170, 60, { align: "right" });
doc.text("Item 2 - Gadget", 20, 70); doc.text("$100.00", 170, 70, { align: "right" });
doc.save("invoice.pdf");}When to use jsPDF vs. html2pdf.js
| Use jsPDF when… | Use html2pdf.js when… |
|---|---|
| Building PDFs from data (not HTML) | Converting existing HTML layouts |
| You need precise positioning | Quick prototypes with HTML |
| Adding images, shapes, tables programmatically | CSS styling is important |
| Smaller file sizes matter | Simplicity over control |
pdfmake
pdfmake works well for data-driven documents and reports. It requires manual configuration and doesn’t accept HTML input — you define layouts in JavaScript objects instead.
The pdfmake(opens in a new tab) library generates PDF documents directly in the browser. It uses a layout and style configuration defined in a JSON-like structure within JavaScript. It’s built on pdfkit(opens in a new tab).
Unlike html2pdf.js, which converts HTML to an image first, pdfmake defines document structure in JavaScript, so text stays selectable.
Installation
Add via CDN:
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.12/pdfmake.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.12/vfs_fonts.min.js"></script>Or, install via npm:
npm install pdfmakeGenerate PDFs from HTML using pdfmake
Define a generatePDF() function with your PDF content as a JavaScript object. Use pdfmake to create and download the file. The example shows text and a table, but pdfmake also supports lists, images, and advanced styling.
<!DOCTYPE html><html>12 collapsed lines
<head> <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.12/pdfmake.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.12/vfs_fonts.min.js"></script> </head> <body> <button onclick="generatePDF()">Download Invoice</button>
<!-- Move script here so pdfMake is loaded --> <script> function generatePDF() { const docDefinition = { content: [ { text: "Invoice", style: "header" }, { table: { body: [ ["Item", "Qty", "Price"], ["Product 1", "2", "$10"], ["Product 2", "1", "$20"], ["Total", "", "$40"], ], }, }, ], styles: {3 collapsed lines
header: { fontSize: 18, bold: true }, }, };
pdfMake.createPdf(docDefinition).download("invoice.pdf"); } </script> </body></html>You can test the example by running:
npx serve -l 4111 .
Benefits of using pdfmake
- Selectable text — Unlike
html2pdf.js,pdfmakepreserves text as selectable and copyable. - Custom styling — Define font sizes, colors, and positioning with structured JavaScript.
- Advanced layouts — Supports tables, lists, and multicolumn designs.
Playwright
Playwright provides high-fidelity rendering with full CSS support. It requires server infrastructure and ongoing maintenance.
Playwright(opens in a new tab) controls headless Chrome, Firefox, and WebKit browsers to convert webpages into PDFs. Unlike html2pdf, Playwright runs on your server and generates PDFs server-side.
Installation
Create a new project and install Playwright(opens in a new tab):
mkdir playwright-pdf-generation && cd playwright-pdf-generationnpm init --yesnpm install playwrightBefore using Playwright, make sure the required browser binaries are installed by running:
npx playwright installBasic PDF example
Create an index.js file that requires Playwright, launches a browser session, goes to your invoice page, and saves the PDF file:
// Require Playwright.const { chromium } = require("playwright");
(async function () { try { // Launch a new browser session. const browser = await chromium.launch(); // Open a new page. const page = await browser.newPage();
// Set the page content. await page.setContent("<h1>Our Invoice</h1>");
// Generate a PDF and store it in a file named `invoice.pdf`. await page.pdf({ path: "invoice.pdf", format: "A4" });
await browser.close(); } catch (e) { console.error(e); }})();Running node index.js generates invoice.pdf locally. To let users download PDFs, set up a Node server with the http module. The server listens on /generate-pdf, renders the page with Playwright, and returns the PDF to the browser.
To do this, omit the path option in page.pdf() to get a buffer, set the response header to application/pdf, and send the buffer as the response. For all other routes, return a simple HTML page with a link to trigger the PDF download:
const { chromium } = require("playwright");const http = require("http");
// Create an instance of the HTTP server to handle the request.http .createServer(async (req, res) => { if (req.url === "/generate-pdf") { // Making sure to handle a specific endpoint. const browser = await chromium.launch(); const page = await browser.newPage();
// Set the content directly or navigate to an existing page. await page.setContent(` <!DOCTYPE html> <html> <head> <title>Invoice</title> </head> <body> <h1>Our Invoice</h1> <p>Details about the invoice...</p> </body> </html> `);
// By removing the `path` option, you'll receive a `Buffer` from `page.pdf`. const buffer = await page.pdf({ format: "A4" });
await browser.close();
// Set the content type so the browser knows how to handle the response. res.writeHead(200, { "Content-Type": "application/pdf" }); res.end(buffer); } else { // Respond with a simple instruction page. res.writeHead(200, { "Content-Type": "text/html" }); res.end( '<h1>Welcome</h1><p>To generate a PDF, go to <a href="/generate-pdf">/generate-pdf</a>.</p>', ); } }) .listen(3000, () => { console.log("Server is running on http://localhost:3000"); });Open localhost:3000 in your browser to see the instruction page. Navigate to /generate-pdf to open the PDF with the invoice.

Common issues and troubleshooting
- Blurry output — Use high-resolution images and scale properly.
- Limited CSS — Limited styling; avoid modern layout features like flexbox or grid.
- Large files — Optimize HTML and assets.
- Layout complexity — Manual configuration required; break documents into smaller blocks when needed.
- Font issues — Ensure custom fonts are embedded correctly.
- Complex setup — More involved than client-side tools; requires server infrastructure.
- Slow rendering — Minimize dynamic scripts or unnecessary content before generating PDFs.
- License validation — Confirm valid key and domain configuration.
- Large documents — Use streaming API for >100MB.
- Custom fonts — Upload to Document Engine for consistency.
HTML to PDF library comparison
| Feature | html2pdf.js | jsPDF | pdfmake | Playwright | Nutrient |
|---|---|---|---|---|---|
| Ease of use | Very easy | Easy | Moderate | Moderate | Easy |
| Installation | Simple (CDN, npm) | Simple (CDN, npm) | Simple (CDN, npm) | npm | SDK/API |
| Runs in browser | |||||
| Text selection | |||||
| CSS/HTML support | Limited | None | None | Full | Full |
| Customization | Low | High | High | High | High |
| PDF quality | Medium (image-based) | High (vector) | High (structured) | Very high (browser) | Very high (Chrome-based) |
| Best for | Quick HTML exports | Data-driven PDFs | JSON-based layouts | Complex CSS layouts | Production apps, compliance |
| Support | Community | Community | Community | Community | Enterprise SLA |
Nutrient SDK includes annotations, form filling, and custom output options.
Start your free trial to test Nutrient’s HTML-to-PDF conversion.
PDF-to-HTML conversion is coming soon to Document Engine and DWS API.
Which library should you use?
Choose based on your specific use case:
| Use case | Recommended | Why |
|---|---|---|
| Quick prototype | html2pdf.js | Fastest setup, no server needed |
| Invoices from data | jsPDF or pdfmake | Build PDFs programmatically, selectable text |
| Complex CSS layouts | Playwright | Full browser rendering, pixel-perfect |
| Production app | Nutrient | Managed infrastructure, support, compliance |
| Fillable forms | Nutrient | Only option with form field conversion |
| Mobile apps | Nutrient | iOS/Android SDKs available |
Decision flowchart:
- Need fillable PDF forms? → Nutrient
- Running on mobile? → Nutrient (iOS/Android SDKs)
- Need full CSS support? → Playwright (self-hosted) or Nutrient (managed)
- Building from data, not HTML? → jsPDF or pdfmake
- Simple prototype? → html2pdf.js
Related posts
- How to convert HTML to PDF using React
- How to generate PDF reports from HTML in Node.js
- How to generate PDF reports from HTML in Python
- Top 10 ways to convert HTML to PDF
- HTML-to-PDF API guide
FAQ
It depends on your needs. For simple client-side conversion, use html2pdf.js. For structured documents from data, use pdfmake. For full CSS support on a server, use Playwright. For managed infrastructure with additional features, use Nutrient.
Yes. html2pdf.js and pdfmake both run entirely in the browser. html2pdf.js converts HTML elements directly, while pdfmake generates PDFs from JavaScript objects. Neither requires a backend server.
html2pdf.js creates image-based PDFs, which can look blurry at certain zoom levels. For sharper output, use Playwright or Nutrient, which render actual text and vector graphics instead of images.
html2pdf.js has limited CSS support. For full CSS3 compatibility, including flexbox and grid, use Playwright (server-side) or Nutrient. Both use real browser engines to render your styles accurately.
Client-side (html2pdf.js, pdfmake) runs in the browser and needs no server, but it’s limited by browser memory and capabilities. Server-side (Playwright, Nutrient) runs on a server and handles larger documents and complex CSS, but it requires infrastructure.
Most open source libraries don’t support this. Nutrient Document Engine converts HTML form elements into fillable PDF fields, including text inputs, checkboxes, and dropdowns.