# JavaScript HTML to PDF libraries

JavaScript HTML to PDF libraries turn a web page or an HTML element into a PDF file. A headless browser prints the page with its print CSS, while an in-page converter draws the element onto a canvas or a PDF document. These libraries produce the receipts, statements, certificates, and archived web pages that apps save or send as PDFs.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [playwright-core](#playwright-core) | 712.5M | 100.4K | Nov 2026 | Apache-2.0 |
| [puppeteer-core](#puppeteer-core) | 127.0M | 95.8K | Nov 2026 | Apache-2.0 |
| [jspdf](#jspdf) | 83.5M | 31.3K | Mar 2026 | MIT |
| [electron](#electron) | 47.7M | 124.0K | Nov 2026 | MIT |
| [webdriverio](#webdriverio) | 12.8M | 9.9K | Nov 2026 | MIT |
| [chrome-remote-interface](#chrome-remote-interface) | 12.5M | 4.6K | Feb 2026 | MIT |
| [selenium-webdriver](#selenium-webdriver) | 8.2M | 34.6K | Nov 2026 | Apache-2.0 |
| [html2pdf.js](#html-pdf-js) | 6.3M | 4.9K | Jan 2026 | MIT |

Downloads: npm, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[playwright-core](#playwright) has the most monthly downloads in this comparison, at 712.5M.

## Capabilities

| Library | Accepts a DOM element | HTML header/footer templates | Page-range selection |
| --- | --- | --- | --- |
| [playwright-core](#playwright-core) | No | Yes | Yes |
| [puppeteer-core](#puppeteer-core) | No | Yes | Yes |
| [jspdf](#jspdf) | Yes | No | No |
| [electron](#electron) | No | Yes | Yes |
| [webdriverio](#webdriverio) | No | No | Yes |
| [chrome-remote-interface](#chrome-remote-interface) | No | Yes | Yes |
| [selenium-webdriver](#selenium-webdriver) | No | No | Yes |
| [html2pdf.js](#html-pdf-js) | Yes | No | No |

## Libraries

### playwright-core

[GitHub](https://github.com/microsoft/playwright) · [npm](https://www.npmjs.com/package/playwright-core) · [Docs](https://playwright.dev/docs/api/class-page#page-pdf)

Prints a browser page to PDF through page.pdf, using print CSS media.

- Downloads / mo: 712.5M
- Stars: 100.4K
- Last release: 1.65.1
- License: Apache-2.0
- Capabilities: [From the playwright-core docs](https://playwright.dev/docs/api/class-page#page-pdf)

**Strengths**

- **Header and footer templates.** Set displayHeaderFooter with HTML templates for the print header and footer.

**Watch out for**

- **PDF needs headless Chromium.** Launch headless Chromium for PDF output, because other engines reject page.pdf.
- **Templates ignore page styles.** Style header and footer templates inline, because page styles do not reach them.

```sh
npm install playwright-core
```

**executeautomation/mcp-playwright** (5.7K stars)

[executeautomation/mcp-playwright](https://github.com/executeautomation/mcp-playwright) 

```javascript
async execute(args: any, context: ToolContext): Promise<ToolResponse> {
  return this.safeExecute(context, async (page) => {
    const filename = args.filename || 'page.pdf';
    const options = {
      path: path.resolve(args.outputPath || '.', filename),
      format: args.format || 'A4',
      printBackground: args.printBackground !== false,
      margin: args.margin || {
        top: '1cm',
        right: '1cm',
        bottom: '1cm',
        left: '1cm'
      }
    };

    await page.pdf(options);
    return createSuccessResponse(`Saved page as PDF: ${options.path}`);
  });
}

```

[src/tools/browser/output.ts](https://github.com/executeautomation/mcp-playwright/blob/2349c2891e7c499c8c07b7d78c7f3fb4c797a1da/src/tools/browser/output.ts#L12-L30) · [More projects using playwright-core →](https://dashboard.exa.ai/playground/search?q=playwright-core%20GitHub%20projects)

**Quickstart**

```javascript
import { chromium } from 'playwright-core';

const browser = await chromium.launch({ channel: 'chrome', headless: true });
const page = await browser.newPage();
await page.setContent('<h1>Hello</h1>');
await page.pdf({ path: 'output.pdf' });
await browser.close();

```

From [class-page](https://playwright.dev/docs/api/class-page#page-pdf)

### puppeteer-core

[GitHub](https://github.com/puppeteer/puppeteer) · [npm](https://www.npmjs.com/package/puppeteer-core) · [Docs](https://pptr.dev/api/puppeteer.page.pdf)

Provides the Puppeteer browser API without downloading Chrome during install.

- Downloads / mo: 127.0M
- Stars: 95.8K
- Last release: 25.18.1
- License: Apache-2.0
- Capabilities: [From the puppeteer-core docs](https://pptr.dev/api/puppeteer.page.pdf)

**Strengths**

- **Honors CSS page sizes.** Set preferCSSPageSize to use the page's CSS @page size over width, height, or format.
- **Fills header and footer values.** Header templates fill in the date, title, URL, page number, and total pages.

**Watch out for**

- **Backgrounds off by default.** Set printBackground to true to keep background colors and images.
- **Needs a browser to connect to.** Point puppeteer-core at an installed Chrome before launching.

```sh
npm install puppeteer-core
```

**marp-team/marp-cli** (3.9K stars)

[marp-team/marp-cli](https://github.com/marp-team/marp-cli) 

```javascript
private async convertFileToPDF(
  tpl: TemplateResult,
  file: File,
  { postprocess = true }: ConvertPDFOption = {}
): Promise<File> {
  const html = new File(file.absolutePath)
  html.buffer = Buffer.from(tpl.result)

  const ret = file.convert(this.options.output, { extension: 'pdf' })

  // Generate PDF
  let outlineData: OutlineData | undefined

  ret.buffer = Buffer.from(
    await this.usePuppeteer(html, async (page, { render }) => {
      await render()

      if (tpl.rendered.outline) {
        outlineData = await page.evaluate(
          pptrOutlinePositionResolver,
          tpl.rendered.outline.flatMap((o) => o.headings),
          pdfOutlineAttr
        )
      }

      return await page.pdf({
        printBackground: true,
        preferCSSPageSize: true, // This option is not working in WebDriver BiDi
        width: tpl.rendered.size.width,
        height: tpl.rendered.size.height,
      })
    })
  )

  if (postprocess) {
    // Apply PDF metadata and annotations
    const creationDate = new Date()
    const { PDFDocument, PDFHexString, PDFString } = await import('pdf-lib')
    const pdfDoc = await PDFDocument.load(ret.buffer)

    pdfDoc.setCreator(CREATED_BY_MARP)
    pdfDoc.setProducer(CREATED_BY_MARP)
    pdfDoc.setCreationDate(creationDate)
    pdfDoc.setModificationDate(creationDate)

    if (tpl.rendered.title) pdfDoc.setTitle(tpl.rendered.title)
    if (tpl.rendered.description) pdfDoc.setSubject(tpl.rendered.description)
    if (tpl.rendered.author) pdfDoc.setAuthor(tpl.rendered.author)
    if (tpl.rendered.keywords)
      pdfDoc.setKeywords([tpl.rendered.keywords.join('; ')])

    if (this.options.pdfOutlines && tpl.rendered.outline) {
      await setOutline(
        pdfDoc,
        generatePDFOutlines(tpl.rendered.outline, {
          ...this.options.pdfOutlines,
          data: outlineData,
          size: tpl.rendered.size,
        })
      )
    }

    if (this.options.pdfNotes) {
      const pages = pdfDoc.getPages()

      for (let i = 0, len = pages.length; i < len; i += 1) {
        const notes = tpl.rendered.comments[i].join('\n\n')

        if (notes) {
          const noteAnnot = pdfDoc.context.obj({
            Type: 'Annot',
            Subtype: 'Text',
            Rect: [0, 20, 20, 20],
            Contents: PDFHexString.fromText(notes),
            T: tpl.rendered.author
              ? PDFHexString.fromText(tpl.rendered.author)
              : undefined,
            Name: 'Note',
            Subj: PDFString.of('Note'),
            C: [1, 0.92, 0.42], // RGB
            CA: 0.25, // Alpha
          })

          pages[i].node.addAnnot(pdfDoc.context.register(noteAnnot))
        }
      }
    }

    // Apply modified PDF to buffer
    ret.buffer = Buffer.from(await pdfDoc.save())
  }

  return ret
}

```

[src/converter.ts](https://github.com/marp-team/marp-cli/blob/ffc4128626cbc64965fe1cc805717c6d4438c384/src/converter.ts#L333-L426) · [More projects using puppeteer-core →](https://dashboard.exa.ai/playground/search?q=puppeteer-core%20GitHub%20projects)

**Quickstart**

```javascript
import puppeteer from 'puppeteer-core';

const browser = await puppeteer.launch({ channel: 'chrome' });
const page = await browser.newPage();
await page.setContent('<h1>Hello</h1>');
await page.pdf({ path: 'output.pdf' });
await browser.close();

```

From [puppeteer.page.pdf](https://pptr.dev/api/puppeteer.page.pdf)

### jspdf

[GitHub](https://github.com/parallax/jsPDF) · [npm](https://www.npmjs.com/package/jspdf) · [Docs](https://github.com/parallax/jsPDF/blob/master/src/modules/html.js)

Provides an HTML-to-PDF method alongside programmable PDF document APIs.

- Downloads / mo: 83.5M
- Stars: 31.3K
- Last release: 4.2.1
- License: MIT
- Capabilities: [From the jspdf docs](https://github.com/parallax/jsPDF/blob/master/src/modules/html.js)

**Strengths**

- **Matches supplied font faces.** Pass fontFaces with font URLs when rendering HTML.
- **Fits HTML to target width.** Set width and windowWidth together to fit the rendered element.

**Watch out for**

- **HTML rendering adds dependencies.** Load html2canvas and DOMPurify when rendering HTML strings.
- **Default paging can split text.** Use text auto-paging for mostly single-column documents.

```sh
npm install jspdf html2canvas dompurify
```

**anurag3407/career-pilot** (135 stars)

[anurag3407/career-pilot](https://github.com/anurag3407/career-pilot) 

```javascript
export async function exportAtsSafePdf(node, filename = 'resume.pdf', opts = {}) {
  const {
    orientation = 'portrait',
    format = 'a4',
    marginMm = 10,
  } = opts

  if (!node) throw new Error('exportAtsSafePdf: node is required')

  // Try text-layer path first
  try {
    const pdf = new jsPDF({
      orientation,
      unit: 'mm',
      format,
    })
    await pdf.html(node, {
      autoPaging: 'text',
      html2canvas: {
        scale: 2,
        useCORS: true,
        backgroundColor: '#ffffff',
        windowWidth: node.scrollWidth,
      },
      margin: [marginMm, marginMm, marginMm, marginMm],
      width: format === 'letter' ? 195.9 : 190,
      windowWidth: node.scrollWidth,
    })
    pdf.save(filename)
    return { ok: true, method: 'text', filename }
  } catch (err) {
    // Fall through to canvas fallback
    console.warn('ATS PDF (text) failed, falling back to canvas raster:', err)
  }

  // Fallback: rasterize the whole node and slice into pages
  const canvas = await html2canvas(node, {
    scale: 2,
    useCORS: true,
    backgroundColor: '#ffffff',
    windowWidth: node.scrollWidth,
    windowHeight: node.scrollHeight,
  })

  const pdf = new jsPDF({ orientation, unit: 'mm', format })
  const pageWidth = pdf.internal.pageSize.getWidth()
  const pageHeight = pdf.internal.pageSize.getHeight()
  const imgWidth = pageWidth
  const imgHeight = (canvas.height * imgWidth) / canvas.width
  const pageHeightInCanvas = (pageHeight * canvas.width) / pageWidth

  if (imgHeight <= pageHeight) {
    pdf.addImage(canvas.toDataURL('image/jpeg', 0.92), 'JPEG', 0, 0, imgWidth, imgHeight)
  } else {
    let yOffset = 0
    let pageIdx = 0
    while (yOffset < canvas.height) {
      const sliceHeight = Math.min(pageHeightInCanvas, canvas.height - yOffset)
      const pageCanvas = document.createElement('canvas')
      pageCanvas.width = canvas.width
      pageCanvas.height = sliceHeight
      const ctx = pageCanvas.getContext('2d')
      ctx.fillStyle = '#ffffff'
      ctx.fillRect(0, 0, pageCanvas.width, pageCanvas.height)
      ctx.drawImage(canvas, 0, yOffset, canvas.width, sliceHeight, 0, 0, canvas.width, sliceHeight)
      const imgData = pageCanvas.toDataURL('image/jpeg', 0.92)
      if (pageIdx > 0) pdf.addPage()
      pdf.addImage(
        imgData, 'JPEG', 0, 0,
        imgWidth,
        (sliceHeight * imgWidth) / canvas.width,
      )
      yOffset += sliceHeight
      pageIdx += 1
    }
  }
  pdf.save(filename)
  return { ok: true, method: 'canvas', filename }
}

```

[frontend/src/services/atsPdfExport.js](https://github.com/anurag3407/career-pilot/blob/5959e42012dd19e2d074db1399e21b24ba123cd4/frontend/src/services/atsPdfExport.js#L20-L98) · [More projects using jspdf →](https://dashboard.exa.ai/playground/search?q=JavaScript%20projects%20using%20jspdf%20for%20HTML%20page%20PDF%20export%20with%20layout%20and%20pagination&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```javascript
import { jsPDF } from 'jspdf';

const pdf = new jsPDF();
await pdf.html('<h1>Hello</h1>');
pdf.save('output.pdf');

```

From [module-html.html](https://github.com/parallax/jsPDF/blob/master/src/modules/html.js)

### electron

[GitHub](https://github.com/electron/electron) · [npm](https://www.npmjs.com/package/electron) · [Docs](https://github.com/electron/electron/blob/main/docs/api/web-contents.md)

Builds desktop apps with JavaScript, HTML, and CSS.

- Downloads / mo: 47.7M
- Stars: 124.0K
- Last release: 45.4.1
- License: MIT
- Capabilities: [From the electron docs](https://github.com/electron/electron/blob/main/docs/api/web-contents.md)

**Strengths**

- **Prints a window's page.** Call printToPDF on a window's webContents to print its loaded page.

**Watch out for**

- **Backgrounds off by default.** Set printBackground to true to include background graphics.

```sh
npm install --save-dev electron
```

**TriliumNext/Trilium** (39.0K stars)

[TriliumNext/Trilium](https://github.com/TriliumNext/Trilium) 

```javascript
async function print() {
    const filePath = electron.dialog.showSaveDialogSync(browserWindow, {
        defaultPath: coreUtils.formatDownloadTitle(title, "file", "application/pdf"),
        filters: [
            {
                name: t("pdf.export_filter"),
                extensions: ["pdf"]
            }
        ]
    });
    if (!filePath) return;

    let buffer: Buffer;
    try {
        buffer = await browserWindow.webContents.printToPDF({
            landscape,
            pageSize,
            scale,
            margins: parseMargins(margins),
            pageRanges: pageRanges || undefined,
            preferCSSPageSize: false,
            generateDocumentOutline: true,
            generateTaggedPDF: true,
            printBackground: true,
            displayHeaderFooter: true,
            headerTemplate: `<div></div>`,
            footerTemplate: `
                <div class="pageNumber" style="width: 100%; text-align: center; font-size: 10pt;">
                </div>
            `
        });
    } catch (_e) {
        electron.dialog.showErrorBox(t("pdf.unable-to-export-title"), t("pdf.unable-to-export-message"));
        return;
    }

    try {
        await fs.writeFile(filePath, buffer);
    } catch (_e) {
        electron.dialog.showErrorBox(t("pdf.unable-to-export-title"), t("pdf.unable-to-save-message"));
        return;
    }

    electron.shell.openPath(filePath);
}

```

[apps/desktop/src/services/printing.ts](https://github.com/TriliumNext/Trilium/blob/3c60eac13f66161492334efefa2613923ebe541f/apps/desktop/src/services/printing.ts#L280-L324) · [More projects using electron →](https://dashboard.exa.ai/playground/search?q=electron%20GitHub%20projects)

**Quickstart**

```javascript
const { app, BrowserWindow } = require('electron');
const fs = require('node:fs/promises');

app.whenReady().then(async () => {
  const win = new BrowserWindow({ show: false });
  try {
    await win.loadURL('data:text/html,<h1>Hello</h1>');
    const pdf = await win.webContents.printToPDF({});
    await fs.writeFile('output.pdf', pdf);
  } finally {
    win.destroy();
    app.quit();
  }
});

```

From [app.md](https://github.com/electron/electron/blob/main/docs/api/app.md)

### webdriverio

[GitHub](https://github.com/webdriverio/webdriverio) · [npm](https://www.npmjs.com/package/webdriverio) · [Docs](https://webdriver.io/docs/api/browser/savePDF/)

Automates browsers, and its savePDF command prints the current page to a PDF file.

- Downloads / mo: 12.8M
- Stars: 9.9K
- Last release: 10.2.0
- License: MIT
- Capabilities: [From the webdriverio docs](https://webdriver.io/docs/api/browser/savePDF/)

**Strengths**

- **Returns the PDF bytes.** savePDF writes the file and also returns its bytes as a Buffer.
- **Prints through WebDriver BiDi.** BiDi sessions print from Chrome, Edge, and Firefox in headed or headless mode.

**Watch out for**

- **File path must end in .pdf.** Give savePDF a file path that ends in .pdf.

```sh
npm install webdriverio
```

**Quickstart**

```javascript
import { remote } from 'webdriverio';

const browser = await remote({
  capabilities: { browserName: 'chrome', 'goog:chromeOptions': { args: ['--headless=new'] } }
});
try {
  await browser.url('data:text/html,<h1>Hello</h1>');
  await browser.savePDF('output.pdf');
} finally {
  await browser.deleteSession();
}

```

From [index.ts](https://github.com/webdriverio/webdriverio/blob/main/packages/webdriverio/src/index.ts) · [Find projects using webdriverio →](https://dashboard.exa.ai/playground/search?q=webdriverio%20GitHub%20projects)

### chrome-remote-interface

[GitHub](https://github.com/cyrus-and/chrome-remote-interface) · [npm](https://www.npmjs.com/package/chrome-remote-interface) · [Docs](https://github.com/cyrus-and/chrome-remote-interface/blob/master/README.md)

Sends Chrome DevTools Protocol commands and receives its events from JavaScript.

- Downloads / mo: 12.5M
- Stars: 4.6K
- Last release: 0.34.0
- License: MIT
- Capabilities: [From the chrome-remote-interface docs](https://github.com/cyrus-and/chrome-remote-interface/blob/master/README.md)

**Strengths**

- **Works with other protocol implementations.** Connects to Chrome or another implementation of the DevTools Protocol.

**Watch out for**

- **Needs a running browser.** Start Chrome with a remote debugging port before connecting.

```sh
npm install chrome-remote-interface
```

**westy92/html-pdf-chrome** (807 stars)

[westy92/html-pdf-chrome](https://github.com/westy92/html-pdf-chrome) 

```javascript
async function generate(html: string, options: CreateOptions, tab: CDP.Target): Promise<CreateResult> {
  await throwIfExitCondition(options);
  const client = await CDP({ ...options, target: tab });
  const connectionLostOrTimeout = new Promise<never>((_, reject) => {
    client.on('disconnect', () => {
      const error = new ConnectionLostError();
      options._exitCondition = error;
      reject(error);
    });
    if (options.timeout != null && options.timeout >= 0) {
      setTimeout(() => {
        const error = new Error('HtmlPdf.create() timed out.');
        options._exitCondition = error;
        reject(error);
      }, options.timeout);
    }
  });

  async function generateInternal() {
    try {
      await beforeNavigate(options, client);
      const {Page} = client;
      if (/^(https?|file|data):/i.test(html)) {
        await Promise.all([
          Page.navigate({url: html}),
          Page.loadEventFired(),
        ]); // Resolve order varies
      } else {
        const {frameTree} = await Page.getResourceTree();
        await Promise.all([
          Page.setDocumentContent({html, frameId: frameTree.frame.id}),
          Page.loadEventFired(),
        ]); // Resolve order varies
      }
      await afterNavigate(options, client);
      let base64Result: string;
      if (options.screenshotOptions) {
        // https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-captureScreenshot
        const screenshot = await Page.captureScreenshot(options.screenshotOptions);
        base64Result = screenshot.data;
      } else {
        // https://chromedevtools.github.io/debugger-protocol-viewer/tot/Page/#method-printToPDF
        const pdf = await Page.printToPDF(options.printOptions);
        base64Result = pdf.data;
      }
      await throwIfExitCondition(options);
      return new CreateResult(base64Result, options._mainRequestResponse);
    } catch (error) {
      if (options._exitCondition) {
        throw options._exitCondition;
      }
      if (hasErrorCode(error, ['ECONNABORTED', 'ECONNRESET', 'EPIPE'])) {
        const connectionLostError = new ConnectionLostError();
        options._exitCondition = connectionLostError;
        throw connectionLostError;
      }
      throw error;
    } finally {
      client.close();
    }
  }

  return Promise.race([
    connectionLostOrTimeout,
    generateInternal(),
  ]);
}

```

[src/index.ts](https://github.com/westy92/html-pdf-chrome/blob/e238d1b7e2841f47856ac5e6422d71d08ee82124/src/index.ts#L60-L126) · [More projects using chrome-remote-interface →](https://dashboard.exa.ai/playground/search?q=chrome-remote-interface%20GitHub%20projects)

**Quickstart**

```javascript
const CDP = require('chrome-remote-interface');
const fs = require('node:fs/promises');

(async () => {
  const client = await CDP();
  try {
    await client.Page.enable();
    const loaded = client.Page.loadEventFired();
    await client.Page.navigate({ url: 'data:text/html,<h1>Hello</h1>' });
    await loaded;
    const { data } = await client.Page.printToPDF({});
    await fs.writeFile('output.pdf', Buffer.from(data, 'base64'));
  } finally {
    await client.close();
  }
})();

```

From [README.md](https://github.com/cyrus-and/chrome-remote-interface/blob/master/README.md)

### selenium-webdriver

[GitHub](https://github.com/SeleniumHQ/selenium) · [npm](https://www.npmjs.com/package/selenium-webdriver) · [Docs](https://github.com/SeleniumHQ/selenium/blob/trunk/javascript/selenium-webdriver/chromium.js)

Provides the official Selenium WebDriver bindings, including a command that prints the page.

- Downloads / mo: 8.2M
- Stars: 34.6K
- Last release: 4.53.0
- License: Apache-2.0
- Capabilities: [From the selenium-webdriver docs](https://github.com/SeleniumHQ/selenium/blob/trunk/javascript/selenium-webdriver/chromium.js)

**Strengths**

- **Configurable print settings.** Set page layout, margins, and scaling before printing.

**Watch out for**

- **Returns encoded PDF data.** Decode the returned string before writing it to a PDF file.

```sh
npm install selenium-webdriver
```

**Quickstart**

```javascript
const { Builder } = require('selenium-webdriver');
const chrome = require('selenium-webdriver/chrome');
const fs = require('node:fs/promises');

(async () => {
  const options = new chrome.Options().addArguments('--headless=new');
  const driver = await new Builder().forBrowser('chrome').setChromeOptions(options).build();
  try {
    await driver.get('data:text/html,<h1>Hello</h1>');
    await fs.writeFile('output.pdf', await driver.printPage({}), 'base64');
  } finally {
    await driver.quit();
  }
})();

```

From [webdriver.js](https://github.com/SeleniumHQ/selenium/blob/trunk/javascript/selenium-webdriver/lib/webdriver.js) · [Find projects using selenium-webdriver →](https://dashboard.exa.ai/playground/search?q=selenium-webdriver%20GitHub%20projects)

### html2pdf.js

[GitHub](https://github.com/eKoopmans/html2pdf.js) · [npm](https://www.npmjs.com/package/html2pdf.js) · [Docs](https://github.com/eKoopmans/html2pdf.js/blob/main/README.md)

Converts browser HTML elements into PDFs through html2canvas and jsPDF.

- Downloads / mo: 6.3M
- Stars: 4.9K
- Last release: 0.14.0
- License: MIT
- Capabilities: [From the html2pdf.js docs](https://github.com/eKoopmans/html2pdf.js/blob/main/README.md)

**Strengths**

- **Converts existing browser elements.** Pass an existing page element into the conversion worker.
- **Controls element page breaks.** Select page-break modes and selectors for splitting content.

**Watch out for**

- **PDF text becomes an image.** The resulting text cannot be selected or searched.
- **Large canvases can fail rendering.** Keep rendered content within the browser’s canvas size limits.
- **Requires a browser.** Run conversion in a browser rather than a Node-only process.

```sh
npm install html2pdf.js
```

**kempsteven/vue-html2pdf** (452 stars)

[kempsteven/vue-html2pdf](https://github.com/kempsteven/vue-html2pdf) 

```javascript
async downloadPdf () {
			// Set Element and Html2pdf.js Options
			const pdfContent = this.$refs.pdfContent
			let options = this.setOptions()

			this.$emit('beforeDownload', { html2pdf, options, pdfContent })

			const html2PdfSetup = html2pdf().set(options).from(pdfContent)
			let pdfBlobUrl = null

			if (this.previewModal) {
				this.pdfFile = await html2PdfSetup.output('bloburl')
				pdfBlobUrl = this.pdfFile
			}

			if (this.enableDownload) {
				pdfBlobUrl = await html2PdfSetup.save().output('bloburl')
			}

			if (pdfBlobUrl) {
				const res = await fetch(pdfBlobUrl)
				const blobFile = await res.blob()
				this.$emit('hasDownloaded', blobFile)
			}

			this.progress = 100
		}

```

[src/vue-html2pdf.vue](https://github.com/kempsteven/vue-html2pdf/blob/d608228f525477ed076a38f3a1ab3dd79cc9e420/src/vue-html2pdf.vue#L227-L253) · [More projects using html2pdf.js →](https://dashboard.exa.ai/playground/search?q=JavaScript%20projects%20using%20html2pdf.js%20for%20HTML%20page%20PDF%20export%20with%20layout%20and%20pagination&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```javascript
import html2pdf from 'html2pdf.js';

const element = document.getElementById('element-to-print');
html2pdf(element);

```

From [README.md](https://github.com/eKoopmans/html2pdf.js/blob/main/README.md)

## FAQ

### Which JavaScript HTML to PDF library should I use?

A headless browser library such as puppeteer-core or playwright-core prints the page with its print CSS through page.pdf. Inside the browser, html2pdf.js and jsPDF convert an element on the page into a PDF.

### What is jsPDF?

jsPDF creates PDF documents from JavaScript, and its html method renders HTML into a document. Rendering HTML strings needs a canvas renderer and DOMPurify loaded alongside it.

### Puppeteer vs Playwright: which should I use for PDFs?

Both print a page to PDF through page.pdf with print CSS media, and both accept HTML header and footer templates. Playwright generates PDFs only in headless Chromium. puppeteer-core skips the browser download and connects to an installed Chrome.

### What is html2pdf.js?

html2pdf.js converts an element on a web page into a PDF through a canvas renderer and jsPDF. Its PDFs hold an image of the content, and their text cannot be selected or searched. It runs only in a browser, not in Node.js.

### How do I make a PDF with Puppeteer?

Load the page, then call page.pdf to print it with print CSS media. Set printBackground to true to keep background graphics, and call emulateMediaType('screen') first to use screen styles.

### Can Playwright generate PDFs in every browser?

No. Playwright generates PDFs only in headless Chromium, and other browser engines reject page.pdf.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best JavaScript HTML to PDF libraries Puppeteer Playwright html2pdf.js jsPDF code examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
