pdf-lib-extended
v1.0.57
Published
This project extends the capabilities of the pdf-lib JavaScript library by providing a set of helper functions that simplify common PDF manipulation tasks. It includes utilities for drawing and formatting text, images, and shapes within PDF documents, all
Maintainers
Readme
pdf-lib-extended
An extension wrapper around pdf-lib that adds higher-level drawing utilities — cursor-based text flow, auto-wrapping paragraphs, tables with per-cell styling, HTML-to-PDF parsing, watermarks, images, and PDF merging — for building PDFs in the browser.
Installation
npm install pdf-lib-extendedpdf-lib is required as a peer dependency.
Quick Start
import PDFLibExtended from 'pdf-lib-extended';
const pdf = new PDFLibExtended();
await pdf.init();
pdf.addNewPage();
pdf.drawText("Hello, world!", { align: "center" });
const url = await pdf.generatePDFURL();
window.open(url);Note: This library uses browser APIs (
XMLHttpRequest,FileReader,DOMParser,Blob,atob) and is intended for browser environments.
Core Concepts
Cursor-based drawing
The library maintains a drawing cursor on the current page. Methods like drawText and htmlParser draw at the cursor position; nextLine() advances it. Move it manually with pdf.getCurrentPage().moveTo(x, y).
Positions and percentages
Many helpers accept coordinates as numbers or percentage strings resolved against the page:
{ x: "15%", y: "55%" } // 15% of page width, 55% down from the topColors
normalizeColor() accepts CSS rgb(r, g, b) strings or Bootstrap theme keywords (primary, secondary, success, info, warning, danger, dark, light). Unrecognized values fall back to black.
API
Setup
| Method | Description |
| --- | --- |
| init() | Async. Creates the PDFDocument and embeds Helvetica (regular, bold, oblique, bold-oblique). Must be called before anything else. |
| addNewPage(dimensions?) | Adds a page (optional [width, height]) and moves the cursor to the top-left margin. |
| generatePDFURL() | Async. Saves the document and returns a blob object URL. |
Text
drawText(text, options?)
Draws a single line at the cursor.
| Option | Default | Description |
| --- | --- | --- |
| align | "left" | "left", "center", or "right" |
| range | page margins | { left, right } bounds used for center/right alignment |
| size | getTextSize() | Font size |
| color | getColor() | pdf-lib color |
| opacity | 1 | 0–1 |
| textDecoration | null | "underline" supported |
drawParagraph(text, options?)
Draws text with automatic wrapping within range. Extra options: padding (line spacing), wordWrap (default true), characterWrap. Returns { height, width }.
measureParagraph(text, options?)
Same wrap logic as drawParagraph but draws nothing. Returns { height, width, lines }. Useful for pre-computing layout.
Tables
drawCell(text, x, y, width, options?)
Draws a single cell; y is the top of the cell.
Key options: height (explicit override), border (true/false or side string like "tb"), align, size, color, backgroundColor, padding, lineThickness, borderColor, borderOpacity, and measure (dry-run — returns dimensions without drawing).
drawTable(header, data, options?)
Draws a full table at the cursor. Rows auto-size to their tallest cell (measure pass, then render pass). Header rows render in bold.
pdf.drawTable(
[ { value: "Name" }, { value: "Post" } ], // header: array of cell objects
[ // data: array of rows
[ { value: "Jane Doe" }, { value: "Clerk I" } ] // each row: array of cell objects
],
{
range: { left: 40, right: 550 },
cellWidth: ["40%", "60%"], // must sum to 100%
border: true,
size: 12
}
);Cell objects support value, color, and backgroundColor (CSS rgb string or theme keyword).
Other options: headerDifference (added to header font size), align, backgroundColor, lineThickness, padding.
HTML Parsing
htmlParser(text, parser?, options?)
Parses an HTML string and renders it to the PDF. Supported elements: <p>, <strong>, <i> (including nested bold-italic), <ul>/<li> (with nesting-based indentation), and <table> (thead/tbody rendered via drawTable).
pdf.htmlParser("<p>Hello <strong>world</strong></p>");Media & Document Utilities
| Method | Description |
| --- | --- |
| addImage(x, y, base64Image, imageScale?, options?) | Async. Embeds a PNG (base64/data URL) at the given coordinates. options.width/options.height override scaling. |
| toDataURL(url) | Async. Fetches a resource and resolves to a base64 data URL — pair with addImage. |
| drawCircleText(x, y, text, options?) | Draws text centered inside a circle. |
| drawWatermark(text, size?) | Draws a rotated, semi-transparent watermark across every page. |
| fetchPDF(url) | Async. Loads an external PDF into a PDFDocument. |
| mergePDF(urls) | Async. Appends one or more external PDFs (string or array of URLs) to the current document and returns the saved bytes. |
Layout Helpers
| Method | Description |
| --- | --- |
| nextLine(padding?) | Moves the cursor down by padding (or the current text size) and back to the left margin. Returns { addedSpace, x, y }. |
| normalizePosition(position, pdf) | Resolves {x, y} (numbers or % strings) or "left"/"center"/"right" into absolute coordinates. |
| normalizeBoundingBox(cursorPosition, boundingBox, type, pdf?) | Converts a % width into { left, right } pixel bounds ("pdf") or a CSS width ("element"). |
| normalizeColor(color, type) | Resolves rgb strings / theme keywords into a pdf-lib color ("pdf") or CSS string ("element"). |
| normalizeRGB(number) | Converts a 0–255 channel to pdf-lib's 0–1 range. |
| getPercentOfRange(percentage, range) | Resolves a % of a {left, right} range into { percentage, value }. |
Getters & Setters
Fonts: getFont(), getBoldFont(), getItalicFont(), getItalicBoldFont(), getCurrentFont(), setFont(font)
State: getPDF(), getCurrentPage() / setCurrentPage(page), getTextSize() / setTextSize(n), getColor() / setColor(color), getMargin() / setMargin({ left?, right?, top?, bottom? }), getCircleScale() / setCircleScale(n)
Defaults: text size 12, margins 40 on all sides, color black.
Full Example
import PDFLibExtended from 'pdf-lib-extended';
const pdf = new PDFLibExtended();
await pdf.init();
pdf.addNewPage();
// Title
pdf.setFont(pdf.getBoldFont());
pdf.drawText("Return of Personnel", { align: "center", size: 16 });
pdf.setFont(pdf.getFont());
// Table at 55% down the page, 90% wide
pdf.getCurrentPage().moveTo(40, pdf.getCurrentPage().getHeight() * 0.45);
pdf.drawTable(
[
{ value: "No." }, { value: "Name of Officer" },
{ value: "Post" }, { value: "Absences" }, { value: "Remarks" }
],
[
[
{ value: "1" }, { value: "Jane Doe" },
{ value: "Clerk I" }, { value: "0" }, { value: "—" }
]
],
{ cellWidth: ["10%", "25%", "25%", "15%", "25%"], border: true }
);
// Watermark + output
pdf.drawWatermark("DRAFT");
const url = await pdf.generatePDFURL();
window.open(url);License
MIT
