# JavaScript PDF libraries

JavaScript PDF libraries create PDF files, and some also modify existing PDFs.

[jsPDF](#jspdf), [PDFKit](#pdfkit), [pdfmake](#pdfmake), and [@react-pdf/renderer](#react-pdf-renderer) generate new documents from drawing calls, a document definition, or React components. [pdf-lib](#pdf-lib), its fork [@cantoo/pdf-lib](#cantoo-pdf-lib), and [LibPDF](#libpdf-core) load an existing PDF to fill its forms, copy its pages, or add content. [html2pdf.js](#htmltwopdf-js) turns a rendered web page into a PDF inside the browser. These libraries produce the invoices, tickets, and reports that apps generate for download.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [pdf-lib](#pdf-lib) | 118.0M | 8.7K | Nov 2021 | MIT |
| [jsPDF](#jspdf) | 83.5M | 31.3K | Mar 2026 | MIT |
| [PDFKit](#pdfkit) | 64.5M | 10.7K | Aug 2026 | MIT |
| [@react-pdf/renderer](#react-pdf-renderer) | 36.3M | 16.9K | Aug 2026 | MIT |
| [pdfmake](#pdfmake) | 17.0M | 12.4K | Nov 2026 | MIT |
| [@cantoo/pdf-lib](#cantoo-pdf-lib) | 13.1M | 361 | Sep 2026 | MIT |
| [html2pdf.js](#htmltwopdf-js) | 6.3M | 4.9K | Jan 2026 | MIT |
| [LibPDF](#libpdf-core) | 1.2M | 1.9K | Oct 2026 | MIT |

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

[pdf-lib](#pdf-lib) has the most monthly downloads in this comparison, at 103.5M.

## Capabilities

| Library | Node.js generation | Password encryption |
| --- | --- | --- |
| [pdf-lib](#pdf-lib) | Yes | No |
| [jsPDF](#jspdf) | Yes | Yes |
| [PDFKit](#pdfkit) | Yes | Yes |
| [@react-pdf/renderer](#react-pdf-renderer) | Yes | Yes |
| [pdfmake](#pdfmake) | Yes | Yes |
| [@cantoo/pdf-lib](#cantoo-pdf-lib) | Yes | Yes |
| [html2pdf.js](#htmltwopdf-js) | No | Yes |
| [LibPDF](#libpdf-core) | Yes | Yes |

## Libraries

### pdf-lib

[GitHub](https://github.com/Hopding/pdf-lib) · [npm](https://www.npmjs.com/package/pdf-lib) · [Docs](https://pdf-lib.js.org/)

pdf-lib creates new PDFs and modifies existing ones, and runs in Node.js, browsers, Deno, and React Native. A loaded document can gain, lose, or reorder pages, copy pages from another PDF, and take new text, images, and SVG paths. The form API creates fields, fills them, and flattens them into page content. Custom fonts embed once the separate `@pdf-lib/fontkit` package is registered. Encrypted PDFs are outside its support.

- Downloads / mo: 118.0M
- Stars: 8.7K
- Last release: 1.17.1
- License: MIT
- Capabilities: [From the pdf-lib docs](https://pdf-lib.js.org/)

**Strengths**

- **Modifies existing PDF documents.** Load existing PDFs to add content, copy pages, and update form fields.
- **Creates and fills PDF forms.** Create fields or read and fill existing text fields and controls.

**Watch out for**

- **Page text editing is restricted.** Existing page text can't be edited or removed; only form field text changes.
- **Needs unencrypted input PDFs.** Encrypted PDFs must be decrypted before loading and modifying them.
- **Custom fonts need fontkit.** Install and register @pdf-lib/fontkit before embedding custom fonts.

```sh
npm install --save pdf-lib
```

**alam00000/bentopdf** (16.4K stars)

[alam00000/bentopdf](https://github.com/alam00000/bentopdf) 

```javascript
async function extractPages() {
  const pagesInput = document.getElementById(
    'pages-to-extract'
  ) as HTMLInputElement;
  if (!pagesInput || !pagesInput.value.trim()) {
    showAlert('No Pages', 'Please enter page numbers to extract.');
    return;
  }

  const pagesToExtract = parsePageRanges(
    pagesInput.value,
    extractState.totalPages
  ).map((i) => i + 1);
  if (pagesToExtract.length === 0) {
    showAlert('Invalid Pages', 'No valid page numbers found.');
    return;
  }

  showLoader('Extracting pages...');

  try {
    const zip = new JSZip();
    const baseName = extractState.file?.name.replace('.pdf', '') || 'document';

    for (const pageNum of pagesToExtract) {
      const newPdf = await PDFDocument.create();
      const [copiedPage] = await newPdf.copyPages(extractState.pdfDoc, [
        pageNum - 1,
      ]);
      newPdf.addPage(copiedPage);
      const pdfBytes = await newPdf.save();
      zip.file(`${baseName}_page_${pageNum}.pdf`, pdfBytes);
    }

    const zipBlob = await zip.generateAsync({ type: 'blob' });
    downloadFile(zipBlob, `${baseName}_extracted_pages.zip`);

    hideLoader();
    showAlert(
      'Success',
      trText('Extracted {{length}} page(s) successfully!', {
        length: pagesToExtract.length,
      }),
      'success',
      () => {
        resetState();
      }
    );
  } catch (error) {
    console.error('Error extracting pages:', error);
    hideLoader();
    showAlert('Error', 'Failed to extract pages.');
  }
}

```

[src/js/logic/extract-pages-page.ts](https://github.com/alam00000/bentopdf/blob/18c4aac8bce50cd449982d65b08f7f7abbd0e2cf/src/js/logic/extract-pages-page.ts#L161-L214) · [More projects using pdf-lib →](https://dashboard.exa.ai/playground/search?q=JavaScript%20projects%20that%20use%20pdf-lib&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 {PDFDocument} from 'pdf-lib'

const pdfDoc = await PDFDocument.create()
const page = pdfDoc.addPage()
page.drawText('Hello world!', {x: 50, y: 700, size: 20})
const pdfBytes = await pdfDoc.save()

```

From [README.md](https://raw.githubusercontent.com/Hopding/pdf-lib/master/README.md)

### jsPDF

[GitHub](https://github.com/parallax/jsPDF) · [npm](https://www.npmjs.com/package/jspdf) · [Docs](https://parallax.github.io/jsPDF/docs/)

jsPDF generates PDF documents from drawing commands in the browser or Node.js. `new jsPDF()` starts a portrait page measured in millimeters, `doc.text` places a string at a position, and `doc.save` writes the file, as a download in the browser and to disk in Node.js. Options set the paper size, orientation, and unit. The `html` method converts an HTML element into PDF content, and a bundled table API turns rows of data into a table.

- Downloads / mo: 83.5M
- Stars: 31.3K
- Last release: 4.2.1
- License: MIT
- Capabilities: [From the jsPDF docs](https://parallax.github.io/jsPDF/docs/)

**Strengths**

- **Creates tables without extras.** Use the bundled table API to turn structured data into a table.
- **Downloads generated PDFs.** Use save() to download a generated PDF in the browser.

**Watch out for**

- **Cannot parse existing PDFs.** Generate new documents; use another library to modify an existing PDF.
- **HTML conversion needs extra packages.** HTML conversion requires html2canvas, plus DOMPurify when passing an HTML string.
- **Unicode needs a custom font.** Characters outside the standard fonts need an embedded TrueType font.

```sh
npm install jspdf
```

**drawdb-io/drawdb** (40.3K stars)

[drawdb-io/drawdb](https://github.com/drawdb-io/drawdb) 

```javascript
() => {
              const canvas = document.getElementById("canvas");
              const filename = `${title}_${new Date().toISOString()}`;
              toJpeg(canvas).then(function (dataUrl) {
                const doc = new jsPDF("l", "px", [
                  canvas.offsetWidth,
                  canvas.offsetHeight,
                ]);
                doc.addImage(
                  dataUrl,
                  "jpeg",
                  0,
                  0,
                  canvas.offsetWidth,
                  canvas.offsetHeight,
                );
                doc.save(`${filename}.pdf`);
              });
            }

```

[src/components/EditorHeader/ControlPanel.jsx](https://github.com/drawdb-io/drawdb/blob/b74fb57464c732179b88b6959c96ce451f5a614d/src/components/EditorHeader/ControlPanel.jsx#L1714-L1732) · [More projects using jsPDF →](https://dashboard.exa.ai/playground/search?q=JavaScript%20projects%20that%20use%20jspdf&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";

// Default export is a4 paper, portrait, using millimeters for units
const doc = new jsPDF();

doc.text("Hello world!", 10, 10);
doc.save("a4.pdf");

```

From [README.md](https://raw.githubusercontent.com/parallax/jsPDF/master/README.md)

### PDFKit

[GitHub](https://github.com/foliojs/pdfkit) · [npm](https://www.npmjs.com/package/pdfkit) · [Docs](https://pdfkit.org/)

PDFKit generates multi-page PDFs in Node.js and the browser through a chainable API. A `PDFDocument` streams its output, so a file or an HTTP response receives the PDF as it is written. Drawing calls follow the HTML canvas API, and text wraps across lines with alignment and bulleted lists. Fonts embed with subsetting from TrueType, OpenType, and WOFF files. Documents can also carry tables, annotations, form fields, outlines, encryption, and the tagged structure that accessible PDFs use.

- Downloads / mo: 64.5M
- Stars: 10.7K
- Last release: 0.20.2
- License: MIT
- Capabilities: [From the PDFKit docs](https://pdfkit.org/)

**Strengths**

- **Streams generated documents.** Pipe PDF output to a file or HTTP response as it is written.
- **Includes table generation.** Add tables with native methods for rows, columns, and display options.
- **Creates interactive PDF forms.** Add text fields, selection controls, buttons, and form actions.

**Watch out for**

- **Browser builds need font registration.** Register standard font metrics before creating a browser document with default Helvetica.
- **Browser file paths need registration.** Load font and image bytes before using paths in the browser.

```sh
npm install pdfkit
```

**natancabral/pdfkit-table** (102 stars)

[natancabral/pdfkit-table](https://github.com/natancabral/pdfkit-table) 

```javascript
addBackground(
      { x, y, width, height }: Rect,
      fillColor?: string,
      fillOpacity?: number,
      callback?: (doc: this) => void,
    ): void {
      fillColor ||= "grey";
      fillOpacity ||= 0.1;

      this.save();
      this.fill(fillColor)
        .fillOpacity(fillOpacity)
        .rect(x, y, width, height)
        .fill();
      this.restore();

      typeof callback === "function" && callback(this);
    }

```

[src/document.ts](https://github.com/natancabral/pdfkit-table/blob/main/src/document.ts#L55-L72) · [More projects using PDFKit →](https://dashboard.exa.ai/playground/search?q=JavaScript%20projects%20that%20use%20pdfkit&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
const PDFDocument = require('pdfkit');
const fs = require('fs');
const doc = new PDFDocument();
doc.pipe(fs.createWriteStream('output.pdf'));
doc.text('Hello world!');
doc.end();

```

From [getting_started.html](https://pdfkit.org/docs/getting_started.html)

### @react-pdf/renderer

[GitHub](https://github.com/diegomura/react-pdf) · [npm](https://www.npmjs.com/package/@react-pdf/renderer) · [Docs](https://react-pdf.org/)

@react-pdf/renderer builds PDFs from React components, in the browser and on the server. A document is written with `Document`, `Page`, `View`, and `Text` components and styled through `StyleSheet.create` with CSS-like properties such as flex direction and margin. In the browser, `PDFViewer` shows the result in the page. On the server, `ReactPDF.render` writes it to a file. The package only creates PDFs, and the separate react-pdf package displays existing ones.

- Downloads / mo: 36.3M
- Stars: 16.9K
- Last release: 4.9.0
- License: MIT
- Capabilities: [From the @react-pdf/renderer docs](https://react-pdf.org/)

```sh
yarn add @react-pdf/renderer
```

**xitanggg/open-resume** (9.0K stars)

[xitanggg/open-resume](https://github.com/xitanggg/open-resume) 

```tsx
export const ResumePDF = ({
  resume,
  settings,
  isPDF = false,
}: {
  resume: Resume;
  settings: Settings;
  isPDF?: boolean;
}) => {
  const { profile, workExperiences, educations, projects, skills, custom } =
    resume;
  const { name } = profile;
  const {
    fontFamily,
    fontSize,
    documentSize,
    formToHeading,
    formToShow,
    formsOrder,
    showBulletPoints,
  } = settings;
  const themeColor = settings.themeColor || DEFAULT_FONT_COLOR;

  const showFormsOrder = formsOrder.filter((form) => formToShow[form]);

  const formTypeToComponent: { [type in ShowForm]: () => JSX.Element } = {
    workExperiences: () => (
      <ResumePDFWorkExperience
        heading={formToHeading["workExperiences"]}
        workExperiences={workExperiences}
        themeColor={themeColor}
      />
    ),
    educations: () => (
      <ResumePDFEducation
        heading={formToHeading["educations"]}
        educations={educations}
        themeColor={themeColor}
        showBulletPoints={showBulletPoints["educations"]}
      />
    ),
    projects: () => (
      <ResumePDFProject
        heading={formToHeading["projects"]}
        projects={projects}
        themeColor={themeColor}
      />
    ),
    skills: () => (
      <ResumePDFSkills
        heading={formToHeading["skills"]}
        skills={skills}
        themeColor={themeColor}
        showBulletPoints={showBulletPoints["skills"]}
      />
    ),
    custom: () => (
      <ResumePDFCustom
        heading={formToHeading["custom"]}
        custom={custom}
        themeColor={themeColor}
        showBulletPoints={showBulletPoints["custom"]}
      />
    ),
  };

  return (
    <>
      <Document title={`${name} Resume`} author={name} producer={"OpenResume"}>
        <Page
          size={documentSize === "A4" ? "A4" : "LETTER"}
          style={{
            ...styles.flexCol,
            color: DEFAULT_FONT_COLOR,
            fontFamily,
            fontSize: fontSize + "pt",
          }}
        >
          {Boolean(settings.themeColor) && (
            <View
              style={{
                width: spacing["full"],
                height: spacing[3.5],
                backgroundColor: themeColor,
              }}
            />
          )}
          <View
            style={{
              ...styles.flexCol,
              padding: `${spacing[0]} ${spacing[20]}`,
            }}
          >
            <ResumePDFProfile
              profile={profile}
              themeColor={themeColor}
              isPDF={isPDF}
            />
            {showFormsOrder.map((form) => {
              const Component = formTypeToComponent[form];
              return <Component key={form} />;
            })}
          </View>
        </Page>
      </Document>
      <SuppressResumePDFErrorMessage />
    </>
  );
};

```

[src/app/components/Resume/ResumePDF/index.tsx](https://github.com/xitanggg/open-resume/blob/4f8255a2c763479837f69f1dccf2a3338730cd79/src/app/components/Resume/ResumePDF/index.tsx#L29-L137) · [More projects using @react-pdf/renderer →](https://dashboard.exa.ai/playground/search?q=%40react-pdf/renderer%20GitHub%20projects)

**Quickstart**

```tsx
import React from 'react';
import ReactPDF, {Document, Page, Text} from '@react-pdf/renderer';

const MyDocument = () => (
  <Document><Page size="A4"><Text>Hello world!</Text></Page></Document>
);
ReactPDF.render(<MyDocument />, './example.pdf');

```

From [README.md](https://raw.githubusercontent.com/diegomura/react-pdf/master/README.md)

### pdfmake

[GitHub](https://github.com/bpampuch/pdfmake) · [npm](https://www.npmjs.com/package/pdfmake) · [Docs](https://pdfmake.github.io/docs/0.3/)

pdfmake builds PDFs from a document definition, a JavaScript object that lists content and styles, in Node.js and browsers. The library works out the layout: line wrapping, lists, columns, and tables with column and row spans and header rows that repeat after a page break. Definitions also set page headers and footers, a table of contents, watermarks, and QR codes. `createPdf` turns a definition into a file that downloads, opens, or prints in the browser.

- Downloads / mo: 17.0M
- Stars: 12.4K
- Last release: 0.3.14
- License: MIT
- Capabilities: [From the pdfmake docs](https://pdfmake.github.io/docs/0.3/)

**Strengths**

- **Uses declarative page layouts.** Describe paragraphs, tables, and styles instead of calculating text coordinates.
- **Handles merged table cells.** Build tables with headers, borders and cells spanning rows or columns.

**Watch out for**

- **Fillable forms remain unsupported.** Use another library when the PDF needs interactive form fields.
- **HTML needs a separate converter.** Convert HTML into document definitions with a separate adapter.

```sh
npm install pdfmake
```

**DataTables/Buttons** (138 stars)

[DataTables/Buttons](https://github.com/DataTables/Buttons) 

```javascript
function (e, dt, button, config, cb) {
		var data = dt.buttons.exportData(config.exportOptions);
		var info = dt.buttons.exportInfo(config as any); // Need better typing
		var rows = [];

		if (config.header) {
			data.headerStructure.forEach(function (row) {
				rows.push(
					row.map(function (cell) {
						return cell
							? {
									text: cell.title,
									colSpan: cell.colspan,
									rowSpan: cell.rowspan,
									style: 'tableHeader'
							  }
							: {};
					})
				);
			});
		}

		for (var i = 0, ien = data.body.length; i < ien; i++) {
			rows.push(
				data.body[i].map(function (d) {
					return {
						text:
							d === null || d === undefined
								? ''
								: typeof d === 'string'
								? d
								: (d as any).toString()
					};
				})
			);
		}

		if (config.footer) {
			data.footerStructure.forEach(function (row) {
				rows.push(
					row.map(function (cell) {
						return cell
							? {
									text: cell.title,
									colSpan: cell.colspan,
									rowSpan: cell.rowspan,
									style: 'tableFooter'
							  }
							: {};
					})
				);
			});
		}

		var doc: any = {
			pageSize: config.pageSize,
			pageOrientation: config.orientation,
			content: [
				{
					style: 'table',
					table: {
						headerRows: config.header
							? data.headerStructure.length
							: 0,
						footerRows: config.footer // Used for styling, doesn't do anything in pdfmake
							? data.footerStructure.length
							: 0,
						body: rows
					},
					layout: {
						hLineWidth: function (i: number, node: any) {
							if (i === 0 || i === node.table.body.length) {
								return 0;
							}
							return 0.5;
						},
						vLineWidth: function () {
							return 0;
						},
						hLineColor: function (i: number, node: any) {
							return i === node.table.headerRows ||
								i ===
									node.table.body.length -
										node.table.footerRows
								? '#333'
								: '#ddd';
						},
						fillColor: function (rowIndex: number) {
							if (rowIndex < data.headerStructure.length) {
								return '#fff';
							}
							return rowIndex % 2 === 0 ? '#f3f3f3' : null;
						},
						paddingTop: function () {
							return 5;
						},
						paddingBottom: function () {
							return 5;
						}
					}
				}
			],
			styles: {
				tableHeader: {
					bold: true,
					fontSize: 11,
					alignment: 'center'
				},
				tableFooter: {
					bold: true,
					fontSize: 11,
					alignment: 'center'
				},
				table: {
					margin: [0, 5, 0, 5]
				},
				title: {
					alignment: 'center',
					fontSize: 13
				},
				message: {}
			},
			defaultStyle: {
				fontSize: 10
			}
		};

		if (info.messageTop) {
			doc.content.unshift({
				text: info.messageTop,
				style: 'message',
				margin: [0, 0, 0, 12]
			});
		}

		if (info.messageBottom) {
			doc.content.push({
				text: info.messageBottom,
				style: 'message',
				margin: [0, 0, 0, 12]
			});
		}

		if (info.title) {
			doc.content.unshift({
				text: info.title,
				style: 'title',
				margin: [0, 0, 0, 12]
			});
		}

		if (config.customize) {
			config.customize(doc, config, dt);
		}

		var pdf = DataTable.Buttons.pdfMake().createPdf(doc);

		if (config.download === 'open') {
			pdf.open();
		}
		else {
			pdf.download(info.filename);
		}

		cb();
	}

```

[js/buttons/pdf.ts](https://github.com/DataTables/Buttons/blob/964ce7e0da2845455dfd1dfd07163fdb29b59dbd/js/buttons/pdf.ts#L30-L195) · [More projects using pdfmake →](https://dashboard.exa.ai/playground/search?q=JavaScript%20projects%20that%20use%20pdfmake&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 pdfMake from 'pdfmake/build/pdfmake';
import pdfFonts from 'pdfmake/build/vfs_fonts';
pdfMake.addVirtualFileSystem(pdfFonts);
pdfMake.createPdf({ content: 'Hello world!' }).download('document.pdf');

```

From [client-side docs](https://pdfmake.github.io/docs/0.3/getting-started/client-side/)

### @cantoo/pdf-lib

[GitHub](https://github.com/cantoo-scribe/pdf-lib) · [npm](https://www.npmjs.com/package/@cantoo/pdf-lib)

@cantoo/pdf-lib is a maintained fork of pdf-lib that keeps the original API and adds features the original lacks. It draws full SVG images rather than only SVG paths, and `extractContents` pulls text and images out of a page. Incremental updates append changes without rewriting the whole file, which signing workflows depend on. The fork also recovers truncated PDFs that the original rejects.

- Downloads / mo: 13.1M
- Stars: 361
- Last release: 2.11.1
- License: MIT
- Capabilities: [From the @cantoo/pdf-lib docs](https://github.com/cantoo-scribe/pdf-lib)

```sh
npm install @cantoo/pdf-lib
```

**modelcontextprotocol/ext-apps** (3.1K stars)

[modelcontextprotocol/ext-apps](https://github.com/modelcontextprotocol/ext-apps) 

```tsx
function makeQuadPoints(
  context: PDFDocument["context"],
  rects: Rect[],
): PDFArray {
  const arr = PDFArray.withContext(context);
  for (const r of rects) {
    const x1 = r.x;
    const y1 = r.y;
    const x2 = r.x + r.width;
    const y2 = r.y + r.height;
    // QuadPoints order: top-left, top-right, bottom-left, bottom-right
    arr.push(PDFNumber.of(x1));
    arr.push(PDFNumber.of(y2)); // top-left
    arr.push(PDFNumber.of(x2));
    arr.push(PDFNumber.of(y2)); // top-right
    arr.push(PDFNumber.of(x1));
    arr.push(PDFNumber.of(y1)); // bottom-left
    arr.push(PDFNumber.of(x2));
    arr.push(PDFNumber.of(y1)); // bottom-right
  }
  return arr;
}

```

[examples/pdf-server/src/pdf-annotations.ts](https://github.com/modelcontextprotocol/ext-apps/blob/ea3e9d0e624a20bc1c51310292f09d9b8ed17161/examples/pdf-server/src/pdf-annotations.ts#L453-L474) · [More projects using @cantoo/pdf-lib →](https://dashboard.exa.ai/playground/search?q=%40cantoo/pdf-lib%20GitHub%20projects)

**Quickstart**

```tsx
import { PDFDocument } from '@cantoo/pdf-lib';
const doc = await PDFDocument.create();
const page = doc.addPage();
page.drawText('Hello world!', { x: 50, y: 700 });
const bytes = await doc.save();

```

From [README.md](https://raw.githubusercontent.com/cantoo-scribe/pdf-lib/master/README.md)

### html2pdf.js

[GitHub](https://github.com/eKoopmans/html2pdf.js) · [npm](https://www.npmjs.com/package/html2pdf.js) · [Docs](https://ekoopmans.github.io/html2pdf.js/)

html2pdf.js converts a web page or a single element into a PDF entirely in the browser. It draws the element onto a canvas with html2canvas and places the resulting image into a document with jsPDF. One chained call takes the element and saves the file, and options set margins, page size, image quality, and page breaks. Text in the output is part of the image.

- Downloads / mo: 6.3M
- Stars: 4.9K
- Last release: 0.14.0
- License: MIT
- Capabilities: [From the html2pdf.js docs](https://ekoopmans.github.io/html2pdf.js/)

**Watch out for**

- **Browser only.** The library needs a browser and won't run in Node.js.

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

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

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

```tsx
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=html2pdf.js%20GitHub%20projects)

**Quickstart**

```tsx
import html2pdf from 'html2pdf.js';
const element = document.getElementById('element-to-print');
html2pdf(element);

```

From [README.md](https://raw.githubusercontent.com/eKoopmans/html2pdf.js/master/README.md)

### LibPDF

[GitHub](https://github.com/LibPDF-js/core) · [npm](https://www.npmjs.com/package/@libpdf/core) · [Docs](https://libpdf.dev/)

LibPDF is a TypeScript library that parses, modifies, and generates PDFs, with a parser that falls back gracefully on malformed files. It fills and flattens forms, merges and splits documents, extracts text with positions, and embeds fonts with subsetting. Encryption, digital signatures, and incremental saves that keep existing signatures valid are built in. Documenso, the company that wrote it, runs it in production, and the project labels itself beta software.

- Downloads / mo: 1.2M
- Stars: 1.9K
- Last release: 0.5.3
- License: MIT
- Capabilities: [From the LibPDF docs](https://libpdf.dev/)

**Watch out for**

- **Beta software.** APIs may change between minor versions.

```sh
npm install @libpdf/core
```

**papermark/papermark** (9.4K stars)

[papermark/papermark](https://github.com/papermark/papermark) 

```tsx
export async function buildWatermarkedPdf({
  fileBytes,
  fileType,
  watermarkConfig,
  viewerData,
  flatten = false,
  onProgress,
}: BuildWatermarkedPdfOptions): Promise<Uint8Array> {
  let pdf: PDF;
  let pages: PDFPage[];

  if (fileType === "image") {
    pdf = PDF.create();
    let image;
    try {
      image = pdf.embedImage(fileBytes);
    } catch (error) {
      throw new Error(
        `Unsupported image format for watermarking: ${
          error instanceof Error ? error.message : String(error)
        }`,
      );
    }
    // Scale large images down so the watermark font-size cap (1000pt) doesn't
    // shrink the watermark; the full-resolution image still embeds losslessly.
    const MAX_IMAGE_PAGE_DIMENSION = 1000;
    const longestSide = Math.max(image.widthInPoints, image.heightInPoints);
    const scale =
      longestSide > MAX_IMAGE_PAGE_DIMENSION
        ? MAX_IMAGE_PAGE_DIMENSION / longestSide
        : 1;
    const widthPt = image.widthInPoints * scale;
    const heightPt = image.heightInPoints * scale;
    const page = pdf.addPage({ width: widthPt, height: heightPt });
    page.drawImage(image, { x: 0, y: 0, width: widthPt, height: heightPt });
    pages = [page];
  } else {
    pdf = await PDF.load(fileBytes);
    pages = pdf.getPages();
  }

  for (let i = 0; i < pages.length; i++) {
    insertWatermark(pages[i], watermarkConfig, viewerData);
    if ((i + 1) % 25 === 0) {
      onProgress?.(`Watermarked ${i + 1}/${pages.length} pages`);
    }
  }

  if (flatten) {
    // Flatten forms, annotations, and optional-content layers so nothing can
    // be toggled/removed. Best-effort: never fail the download over this.
    try {
      pdf.flattenAll();
      onProgress?.("Flattened form/annotation/layer content");
    } catch (error) {
      onProgress?.(
        `flattenAll failed, falling back to form flatten: ${
          error instanceof Error ? error.message : String(error)
        }`,
      );
      try {
        pdf.getForm()?.flatten();
      } catch {
        // No form / unsupported – ignore.
      }
    }
  }

  return await pdf.save();
}

```

[lib/utils/watermark-pdf.ts](https://github.com/papermark/papermark/blob/1e269441/lib/utils/watermark-pdf.ts#L409-L478) · [More projects using LibPDF →](https://dashboard.exa.ai/playground/search?q=%40libpdf/core%20GitHub%20projects)

**Quickstart**

```tsx
import { PDF } from "@libpdf/core";

const pdf = await PDF.load(bytes);
const pages = pdf.getPages();

console.log(`${pages.length} pages`);

```

From [README.md](https://raw.githubusercontent.com/LibPDF-js/core/main/README.md)

## FAQ

### Which JavaScript PDF library should I use?

To generate a PDF from code, use [jsPDF](#jspdf) for drawing calls or [pdfmake](#pdfmake) for a declarative layout with tables. To change an existing PDF or fill its forms, use [pdf-lib](#pdf-lib). In a React app, use [@react-pdf/renderer](#react-pdf-renderer) to build the document from components.

### What is jsPDF?

[jsPDF](#jspdf) generates PDFs from drawing commands in the browser and Node.js. It creates new documents only, and changing an existing PDF takes another library such as [pdf-lib](#pdf-lib).

### What is pdf-lib?

[pdf-lib](#pdf-lib) creates and modifies PDF documents in Node.js, browsers, Deno, and React Native. It edits existing files, fills and flattens forms, copies pages between documents, and embeds images and fonts.

### What is pdfmake?

[pdfmake](#pdfmake) generates PDFs in Node.js and browsers from a declarative document definition. The definition lists paragraphs, tables, and styles, and pdfmake works out line wrapping, page breaks, and repeated table headers.

### How do I generate a PDF in JavaScript?

With [jsPDF](#jspdf), create a document with `new jsPDF()`, add text with `doc.text`, and call `doc.save` to download or write the file. [pdfmake](#pdfmake) takes a document definition object instead and builds the layout from it.

### How do I convert HTML to PDF in JavaScript?

[html2pdf.js](#htmltwopdf-js) converts a page or element in the browser by drawing it onto a canvas with html2canvas and placing the image into a PDF with jsPDF. The `html` method in [jsPDF](#jspdf) does the same through html2canvas.

## How this page was built

Data checked Nov 19, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "JavaScript PDF libraries pdf-lib jsPDF pdfmake PDFKit create modify forms tables HTML code examples",
    "numResults": 5
  }
}
```

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