Use jsPDF’s html() method to render a DOM element into a PDF in the browser. Install jspdf, create new jsPDF(), pass the element and rendering options, then save the document. The method relies on html2canvas; when you provide an HTML string instead of an element, the jsPDF project also documents dompurify as a dependency. If you need configurable page breaks and a Promise-based workflow, html2pdf.js is a separate wrapper around html2canvas and jsPDF.
Install jsPDF
In an npm project, install the library with:
npm install jspdf
Import jsPDF from the package in your browser application:
import { jsPDF } from 'jspdf';
jsPDF’s HTML renderer loads html2canvas when it is needed. If your bundler cannot resolve dynamically loaded optional dependencies, install the rendering packages explicitly:
npm install jspdf html2canvas dompurify
dompurify is needed when html() receives an HTML string. For an existing DOM element, the essential rendering dependency is html2canvas.
Quick wins for a faster PC:
Scan for outdated or missing drivers - takes under a minuteDriver Scan →Repair Windows errors before they cause bigger problemsFix Now →Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →#1 Best Overall
- INNOVATIVE CARTRIDGE-FREE PRINTING — No more dealing with lots of tiny ink cartridges; With this wireless document and photo printer each ink bottle set is equivalent to about 90 individual cartridges²
- LESS FREQUENT INK REPLACEMENT — Replacement ink bottles don't have to be changed nearly as often as ink cartridges¹; When you choose this combination printer, scanner and copier you can print up to 4,500 pages black/7,500 color³
- COLOR PRINTING — Up to 2 years of ink in the box4 (and with every replacement ink set) for fewer out-of-ink frustrations
- ZERO CARTRIDGE WASTE — By using an Epson EcoTank printer you can help reduce the amount of cartridge waste ending up in landfills
- HOME PRINTER DESIGNED FOR RELIABILITY — The Epson EcoTank ET-2800 All-in-One Supertank Color Printer creates vivid, detailed prints and documents thanks to Micro Piezo Heat-Free Technology; Fire off 10 ISO pages per minute1 to easily finish large jobs
Export a DOM element with doc.html()
Give the content a stable container, wait until it is rendered, and pass that element to jsPDF. The callback runs after the PDF has been built.
<button id='export-pdf' type='button'>Export PDF</button>
<article id='invoice' class='invoice'>
<h1>Invoice 1042</h1>
<p>This content will be rendered into the PDF.</p>
</article>
<script type='module'>
import { jsPDF } from 'jspdf';
const button = document.querySelector('#export-pdf');
const invoice = document.querySelector('#invoice');
button.addEventListener('click', () => {
const doc = new jsPDF({
orientation: 'portrait',
unit: 'mm',
format: 'a4'
});
doc.html(invoice, {
margin: [12, 12, 12, 12],
autoPaging: 'text',
html2canvas: {
scale: 2,
useCORS: true
},
callback: (pdf) => {
pdf.save('invoice-1042.pdf');
}
});
});
</script>
The format, orientation, and unit values configure the jsPDF document. The margin, autoPaging, and html2canvas values control the HTML-rendering pass. Adjust them for your page rather than assuming that a screen layout will fit an A4 page automatically.
Use an HTML string safely
When the source is a string, sanitize user-controlled content before passing it to jsPDF. The project documentation explicitly warns: “We strongly advise you to sanitize user input before passing it to jsPDF!” A typical module setup is:
import { jsPDF } from 'jspdf';
import DOMPurify from 'dompurify';
const unsafeMarkup = getMarkupFromAnEditor();
const safeMarkup = DOMPurify.sanitize(unsafeMarkup);
const doc = new jsPDF();
doc.html(safeMarkup, {
callback: (pdf) => pdf.save('document.pdf')
});
Sanitization protects the HTML you supply; it does not solve cross-origin image restrictions, missing font glyphs, or oversized canvases.
Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteWindows Errors? Fix Them Before They Spread
Repair common Windows errors and clear accumulated junk for a smoother, more stable PC - no reinstall needed.Free scan · no reinstallControl pages with html2pdf.js
html2pdf.js is not another name for jsPDF’s html() method. It is a separate client-side wrapper whose documented pipeline moves from the source element to a container, canvas, image, PDF, and finally the saved file. Install it alongside its rendering dependencies:
Rank #2
- CARTRIDGE-FREE PRINTING — Print lab-quality photos, graphics and creative projects; Get vibrant colors and sharp text with Epson's high-accuracy printhead and Claria ET Premium 6-color inks
- INK BOTTLES — Save on photos1 and creative projects with affordable in-house printing; All-in-one printer allows you to print 4" x 6" photos for about 4 cents each vs. 40 cents with traditional ink cartridges1
- LESS FREQUENT INK REPLACEMENT — Replacement ink bottles don't have to be changed nearly as often as ink cartridges¹; Printer, scanner and copier lets you print up to 6,200 color pages³
- PRINT FOR LONGER — Up to 2 years of ink in the box² (and with every replacement ink set) for fewer out-of-ink frustrations with this wireless printer
- ZERO CARTRIDGE WASTE — Epson EcoTank printer helps reduce the amount of cartridge waste ending up in landfills; Cartridge-free printer uses high-yield ink bottles; Each replacement ink bottle set is equivalent to about 100 individual ink cartridges⁴
npm install html2pdf.js
Its Promise-based chain makes page-break and output settings explicit:
import html2pdf from 'html2pdf.js';
const report = document.querySelector('#report');
const options = {
margin: [10, 10, 10, 10],
filename: 'report.pdf',
image: {
type: 'jpeg',
quality: 0.95
},
html2canvas: {
scale: 2,
useCORS: true
},
jsPDF: {
unit: 'mm',
format: 'a4',
orientation: 'portrait'
},
pagebreak: {
mode: ['css', 'legacy']
}
};
html2pdf()
.set(options)
.from(report)
.save();
You can also use the shorter form html2pdf(report). The wrapper’s options cover margins, image type and quality, jsPDF paper settings, and page-break behavior. Add CSS page-break rules to the source where a section must start on a new page, then verify the result in the browsers you support.
jsPDF HTML rendering versus html2pdf.js
| Question | jsPDF.html() |
html2pdf.js |
|---|---|---|
| What is it? | A direct method on a jsPDF document. | A separate wrapper that orchestrates html2canvas and jsPDF. |
| Typical call | doc.html(element, options) |
html2pdf().set(options).from(element).save() |
| Best fit | A small integration that already owns a jsPDF instance. | A higher-level export with explicit page-break and image settings. |
| Text behavior | Rendering still depends on the browser canvas pass; test whether your content remains selectable in the target setup. | The documented output is rasterized, so text is not selectable or searchable. |
| Page-break controls | Use jsPDF HTML options and your layout; behavior depends on the rendered content. | Provides documented page-break modes and wrapper options. |
| Main risks | Canvas and cross-origin limitations still apply. | Large canvases can fail or produce blank output, and raster images can increase file size. |
Neither approach is a universal winner. Choose the direct method when you need jsPDF itself; choose the wrapper when its chain and page-break configuration match your export. Test the actual document, fonts, browser, and assets before promising a particular result.
Important rendering limits
HTML is rendered through a canvas
These workflows reproduce what the browser can render into a canvas; they are not a full print engine. Complex CSS, very long pages, fixed-position elements, animations, and responsive breakpoints can produce different results from the live page. Freeze dynamic content and use a dedicated print layout when the PDF must be repeatable.
Cross-origin images and resources
html2canvas cannot bypass browser same-origin rules. An image or other resource loaded from another origin can taint the canvas, making the canvas unreadable and causing missing content or an export failure. Serve assets with appropriate cross-origin headers, host them on the same origin, or replace them with data that your page can legally load.
Rank #3
- SET IT UP ONCE AND PRINT WITH CONFIDENCE. No complicated maintenance. Just easy, reliable printing you can count on.
- INK FOR YEARS. NOT MONTHS. Up to 2 years of ink included. Get thousands of pages of cartridge-free printing. More pages, less hassle
- KEEPS PRINTING WELL AFTER COMPETITORS HAVE QUIT. No complex maintenance. Sharper text, richer colors.[2] Only with HP Smart Tank
- PREMIUM SUPPORT - Strong technical expertise to solve issues faster
- THE LAST PRINTER YOU'LL EVER NEED. Enjoy years of refillable, cartridge-free printing.
Fonts and non-ASCII characters
jsPDF’s standard PDF fonts have limited character coverage. For accented text, non-Latin scripts, or symbols outside those fonts, embed a TTF font and register it before selecting it. Confirm that the chosen font actually contains every glyph used by the document; otherwise characters can be missing or replaced.
Raster output and file size
html2pdf.js documents rasterized output: the text is not searchable or selectable, and converting a large page to an image can increase the PDF size. A higher canvas scale can improve visual sharpness but also consumes more memory and produces more data. Use the lowest scale that meets your print requirement.
Canvas dimensions
Very large canvas dimensions can exceed browser limits and result in blank output. Long reports should be split into sensible pages, captured in sections, or generated with a PDF engine designed for document layout rather than one enormous canvas.
How do I fit the entire content in one page when printing it to PDF?
First decide whether “one page” means one physical sheet or merely no unexpected blank pages. A complete report may be unreadable if you force it onto one sheet.
- Set the target paper format and orientation in the jsPDF options, such as
format: 'a4'andorientation: 'portrait'. - Reduce the source element’s print width, margins, font size, and vertical spacing with a print-specific class rather than shrinking the canvas indefinitely.
- Remove fixed-height containers and overflow rules that clip content during rendering.
- Use
autoPagingin the direct method or thepagebreakoptions in html2pdf.js for intentional breaks. - Export a representative long document in each supported browser. A layout that fits one page at one viewport can paginate differently at another viewport or with a different font.
Troubleshooting common failures
| Symptom | Likely cause | Fix |
|---|---|---|
doc.html is undefined |
The code is using a different object or an incompatible import. | Import jsPDF from jspdf and create the document with new jsPDF() before calling doc.html(). |
| Blank PDF | The source is empty or the canvas exceeded browser limits. | Confirm the selector returns a visible element, wait for content to render, reduce the capture size, and split very long documents. |
| Images disappear | Cross-origin restrictions or unavailable image URLs. | Use same-origin assets or configure the server’s cross-origin response correctly; verify each URL loads before export. |
| Text is clipped or overlaps | Screen CSS, fixed heights, or responsive sizing does not match the PDF page. | Add a print layout, remove clipping rules, set a deliberate width, and test at the target paper format. |
| Characters show as boxes | The selected PDF font lacks the required glyphs. | Embed and register a TTF font that contains the document’s characters. |
| Output is blurry or huge | The canvas scale is too low or too high. | Adjust html2canvas.scale incrementally and balance readability against memory use and file size. |
| User content executes unexpectedly | Unsanitized HTML was passed as a string. | Sanitize with DOMPurify before calling doc.html(); never treat arbitrary markup as trusted. |
| Page breaks occur in the wrong place | The rendered dimensions differ from the live layout. | Use explicit print CSS and html2pdf.js page-break settings, then inspect the generated pages at the supported viewport. |
Performance and reliability checklist
- Start the export only after fonts, images, and asynchronous data have finished loading.
- Capture a bounded element instead of the entire application shell.
- Disable animations and transitions in the export state so the canvas does not capture an intermediate frame.
- Keep the source dimensions reasonable; split long reports before they approach browser canvas limits.
- Test non-ASCII text with the exact font files used in production.
- Test external assets under the same origin and security headers used by real users.
- Check page count, image quality, text searchability, and file size as separate acceptance criteria.
- Run exports in every supported browser because canvas, font loading, and layout behavior are browser-dependent.
Or skip the browser setup
If the page you need is already available at a URL, ScreenshotNeo can return a website screenshot or PDF through one request instead of making you maintain browser-rendering code. Before capture it accepts the cookie or consent banner like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be switched off. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the result with X-Page-Verdict and X-Billed headers. It also provides an MCP server with take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.
Use the API examples in the ScreenshotNeo documentation with your own access key:
Rank #4
- Wireless Bluetooth Printer: Portable thermal printer compatible with iPhone, Android phones, iPad and tablet computers via Bluetooth. For smartphones, please download the "Nada Print" App. You can also connect to laptops and computers for printing using a USB-C cable. (Note: Laptops and computers can only be connected via USB and require the installation of a driver first. Bluetooth connection is not supported.)
- No-ink printing: Only supports US Letter and A4 size thermal paper.(Doesn't support regular paper) The no-ink portable thermal printer uses direct thermal technology, requiring no ink, toner or ribbons, making it environmentally friendly, cost-effective and time-saving. The thermal printer package comes with a roll of US Letter thermal printing paper. Note: When installing the paper, remember to switch the paper size switch on APP
- Clear Print: NDYIN N80 portable thermal printer adopts high-definition printing technology, with a 203DPI resolution to provide you with clear printing results. This mobile printer is compatible with roll paper, folded paper and tattoo transfer paper, supporting printing from your mobile phone PDF, Word, pictures and web pages anytime and anywhere. It is recommended to use our NDYIN thermal paper to achieve good printing quality
- Portable wireless printer for travel: The thermal printer is equipped with a built-in 1500mAh rechargeable battery, which can print 160 sheets of 8.5" x 11" thermal paper after being fully charged. It weighs only 1.5 pounds and is compact in size. This ink-free portable printer can be easily carried in a backpack or briefcase! It is perfect for business travel, cars, small offices, construction sites, schools and homes. You can print documents, contracts, invoices and boarding passes anytime and anywhere
- The N80 thermal printer has a wide range of uses. The package includes the N80 printer, a roll of US Letter paper(7m/roll), a user manual, a guide card, a type-C soft cable and a type C adapter. Note: The charging adapter is not included. Special thermal paper is required for use; ordinary paper cannot be used. This ink-free portable thermal printer is suitable for various scenarios such as home, school, travel, office, and outdoor, meeting the printing needs of different groups of people. This tattoo template printer is also compatible with tattoo transfer paper, making it an ideal choice for tattoo art
cURL
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Python
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
Node.js
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
ScreenshotNeo supports PNG, JPEG, WebP, and PDF output, full-page captures with lazy images loaded, CSS-selector element capture, dark mode, device presets or custom viewports, retina scale, custom CSS and JavaScript, click-before-capture actions, selector hiding, waits for selectors, delays or network idle, request and resource blocking, custom headers and cookies, user-agent and authorization values, timezone and geolocation, transparent backgrounds, resizing, configurable-TTL caching, signed image links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, a usage API, and an OpenAPI specification. Parameter names used by other screenshot APIs also work, which can simplify migration.
The Free plan includes 1,000 shots per month with no card. Paid plans start at $5 for 3,000 shots; Growth is $15 for 15,000, Pro is $39 for 60,000, Scale is $99 for 250,000, and Business is $249 for 1,000,000. Yearly billing gives two months free, and every feature is included on every plan. Create a free ScreenshotNeo account to start without a card.
Frequently Asked Questions
Can I use jsPDF and html2pdf.js in the same application?
Yes. They can coexist, but they represent different export paths. Use one path for a given document so that page settings, scaling, and debugging remain predictable.
What should I verify before treating an export as production-ready?
Verify the longest real document, the target browsers, external images, custom fonts, page count, text searchability, visual quality, and resulting file size. Browser rendering can change when any of those inputs changes.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Repair Windows errors before they cause bigger problems3Scan for outdated or missing drivers - takes under a minuteQuick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

