Package Exports
- jspdf-utils
Readme
jsPDF Utils
Utilities for rendering HTML into paginated PDF output with jsPDF and
html2canvas.
Installation
npm install jspdf-utils jspdf html2canvasExported API
generatePDF(doc, source, opts)generateImagePDF(source, opts)generateImages(source, opts)previewImages(source, container, opts)PAGE_SIZESPAGE_MARGINS- Types:
PageOptions,PageOptionsInput,ImagePDFOptions
Type import example:
import type { PageOptionsInput } from "jspdf-utils";Quick Start
1) HTML -> vector/text PDF (doc.html)
import jsPDF from "jspdf";
import { generatePDF } from "jspdf-utils";
const target = document.getElementById("print-section");
if (!target) throw new Error("Missing #print-section");
const doc = new jsPDF({ unit: "mm", format: "a4" });
// Optional for Arabic/RTL text:
// doc.addFont("/fonts/arial.ttf", "arial", "normal");
// doc.addFont("/fonts/arial-bold.ttf", "arial", "bold");
await generatePDF(doc, target, {
margin: { top: 20, right: 20, bottom: 20, left: 20 },
forcedPageCount: 1,
});
doc.save("output.pdf");2) HTML -> image-based PDF (raster pages)
import { generateImagePDF } from "jspdf-utils";
const target = document.getElementById("print-section");
if (!target) throw new Error("Missing #print-section");
const imagePDF = await generateImagePDF(target, {
format: "a5",
imageFormat: "PNG",
forcedPageCount: 1,
});
imagePDF.save("output-image.pdf");3) Preview pages as images in a container
import { previewImages } from "jspdf-utils";
const target = document.getElementById("print-section");
const preview = document.getElementById("preview-container");
if (!target || !preview) throw new Error("Missing preview elements");
await previewImages(target, preview, {
format: "a5",
forcedPageCount: 1,
});Options
PageOptionsInput
unit?: string(default:"mm")format?: "a0" | "a1" | "a2" | "a3" | "a4" | "a5" | "a6" | "letter" | "legal" | "tabloid"(default:"a4")pageWidth?: number(default comes fromformat)pageHeight?: number(default comes fromformat)margin?: number | { top?: number; right?: number; bottom?: number; left?: number }
ImagePDFOptions
imageFormat?: "JPEG" | "PNG"imageQuality?: numberscale?: numbermarginContent?: MarginContentInputforcedPageCount?: number
forcedPageCount behavior:
- Forces output to the first
Npages only. generatePDF: trims extra pages afterdoc.htmlrendering.generateImagePDF: only rasterizes and writes firstNpages.generateImagesandpreviewImages: only returns/displays firstNpages.- Invalid values (
<= 0,NaN,Infinity) are ignored.
Margin Content and Borders
marginContent supports:
top,right,bottom,leftas:HTMLElement, or(page: number, totalPages: number) => HTMLElement
contentBorder(vector rectangle)textBorder(repeated text around page edges)
Rendering order:
- Margin content and borders are rendered beneath page content.
- Main document content stays visually above borders/text borders.
Development
npm install
npm run devOpen http://localhost:5173.
License
MIT