How to Fix jsPDF addHTML Errors with html2canvas
Replace deprecated jsPDF addHTML calls with the maintained html() method. Fix missing dependencies, blank or clipped PDFs, missing images, and CSS differences.

addHTML is a legacy jsPDF plugin method. The supported migration path is doc.html(element, options), which uses html2canvas. In a browser application, install and import the dependencies, select the DOM element to render, then await the HTML rendering before saving the PDF. The change also addresses a common source of upgrade breakage: the old plugin expected callback-style html2canvas behavior, while html2canvas is Promise-based.
For an element already on the page, a minimal modern example looks like this:
import { jsPDF } from 'jspdf';
import html2canvas from 'html2canvas';
async function exportInvoice() {
const element = document.querySelector('#invoice');
if (!element) throw new Error('Could not find #invoice');
const pdf = new jsPDF();
await pdf.html(element, {
margin: [10, 10, 10, 10],
autoPaging: 'text',
html2canvas: {
scale: 2,
useCORS: true,
windowWidth: element.scrollWidth,
windowHeight: element.scrollHeight
},
callback: (renderedPdf) => renderedPdf.save('invoice.pdf')
});
}
exportInvoice().catch(console.error);
Check the jsPDF README and html2canvas getting started guide for the package and API details. The html method relies on html2canvas; when you pass an HTML string instead of a DOM element, jsPDF also uses DOMPurify. This is a browser rendering workflow, not a server-side HTML renderer.
1. Why addHTML fails
addHTML and the older fromHTML API are no longer supported by jsPDF maintainers. The legacy plugin looked for a global html2canvas or rasterizeHTML, and used the old onrendered callback convention. That combination breaks readily when you upgrade dependencies, switch to a module bundler, or use a newer Promise-based html2canvas release. The maintained doc.html() API is the appropriate migration target.
There are two common types of issue: an API mismatch, where the method is absent or never completes, and a rendering issue, where the PDF is generated but looks empty, clipped, or different from the browser page. Fix the API path first; then diagnose the rendered output and its source assets.
2. Migrate to doc.html step by step
- Check the installed versions. Inspect your package manifest and lockfile for jsPDF and html2canvas. Confirm you are following documentation for the installed jsPDF version.
- Remove the legacy call. Replace
doc.addHTML(...)ordoc.fromHTML(...)withdoc.html(...). Do not try to fix the old method by adding a global as the long-term solution. - Install and import dependencies. In a bundled project, make html2canvas available through your package manager and import it when required by your integration. A package import does not necessarily create
window.html2canvas. - Render an actual DOM element. Wait until the target exists and has its content before calling the method. A missing selector, hidden element, or a component still loading data can yield empty output.
- Await completion. Call from an
asyncfunction and await the render. Save from the documented callback or after the await, depending on the installed jsPDF version’s API. - Set dimensions deliberately. For long content, pass the element’s scroll dimensions as html2canvas’s
windowWidthandwindowHeightoptions to reduce viewport-related clipping. - Check images and CSS. Confirm image origins and CORS headers, then simplify unsupported visual effects if the result differs from the page.
The example uses a DOM element. If you instead pass an HTML string, sanitize and validate any untrusted input; jsPDF’s optional DOMPurify dependency is relevant for that form. Avoid building an export from arbitrary user-provided markup without an appropriate sanitization policy.

3. Import and dependency patterns
In a module-based frontend, import the named jsPDF class and make html2canvas available to the build. The exact package resolution can depend on your bundler and installed package versions, so resolve module errors against your lockfile and the current package documentation.
import { jsPDF } from 'jspdf';
import html2canvas from 'html2canvas';
const element = document.querySelector('.print-area');
if (!element) throw new Error('Missing .print-area');
const doc = new jsPDF({ orientation: 'portrait', unit: 'mm', format: 'a4' });
await doc.html(element, {
html2canvas: { scale: 1.5, useCORS: true },
callback: (pdf) => pdf.save('report.pdf')
});
If the installed jsPDF build resolves the optional dependency itself, your project may not need a separate explicit import. If it does not, install or configure the expected dependency rather than assuming a browser global exists. Keep the import style consistent with the module system in your application; mixing CommonJS, ESM, and script-tag globals can make an otherwise valid method unavailable.
4. Set page size, margins, and pagination
jsPDF creates a PDF with its own page format and units. The rendered HTML is converted into canvas content, so the CSS width, canvas scale, PDF page size, and margins all affect how much content fits and how legible it appears. Use a format and orientation that suit the document, and test a representative page before exporting a large report.
const doc = new jsPDF({
orientation: 'landscape',
unit: 'mm',
format: 'a4'
});
await doc.html(document.querySelector('#report'), {
margin: [12, 12, 12, 12],
autoPaging: 'text',
html2canvas: {
scale: 1.5,
useCORS: true,
windowWidth: document.querySelector('#report').scrollWidth
},
callback: (pdf) => pdf.save('report.pdf')
});
Use the autoPaging option supported by your installed jsPDF version when content should flow across pages. Pagination is sensitive to the rendered dimensions and layout; a block that cannot split cleanly, a fixed-height container, or content that changes after capture begins may still create awkward page breaks. If exact print pagination is essential, design a print-specific layout and validate it in the generated PDF.
html2canvas options are supplied under the html2canvas key in doc.html. Useful options for this workflow include:
scalecontrols canvas resolution. Larger values can improve text and image sharpness, but use more memory and make large canvases more likely to hit browser limits.useCORSasks html2canvas to load eligible cross-origin images using CORS. The remote server still needs to allow the request.windowWidthandwindowHeightset the rendering viewport dimensions. For full content, derive them fromscrollWidthandscrollHeight.
5. Diagnose rendering problems
Blank or clipped pages
Start by checking that the element exists, is visible, and contains its final content at capture time. A canvas can also become blank or partially rendered when it is too large, without a clear exception. Set the rendering window dimensions from the element’s scroll size. If the element is very tall or wide, reduce scale or render smaller sections separately. Browser canvas limits vary; do not rely on a single maximum dimension as a universal guarantee.
Missing images or a tainted canvas
Same-origin images are the simplest case. Cross-origin images require the remote server to provide suitable CORS response headers, and your capture must be configured to use CORS. Setting useCORS: true does not override server policy. Host assets on your origin, configure the image server’s permitted origins, or use an authorized proxy that returns the resources. Cross-origin iframes generally cannot be rendered because the browser prevents access to their document content.
CSS looks different
html2canvas rebuilds a representation of the DOM; it does not take a pixel-perfect screenshot of the browser’s composited page. Its maintainers document that CSS support is not complete because properties need to be implemented individually. If a shadow, filter, complex layout, or other effect renders differently, isolate that property, simplify the export stylesheet, or use a real browser renderer when fidelity matters more than a client-side implementation.
Content changes during capture
Wait for application data and images to settle before starting. If a framework renders asynchronously, trigger export after its state update has committed. Lazy-loaded images may not have loaded simply because the element exists. Scroll or otherwise load the required content according to your page’s behavior, and verify that the final canvas includes it.
6. Troubleshooting table
| Symptom | Likely cause | Fix |
|---|---|---|
addHTML is not a function |
Legacy plugin absent, deprecated, or incompatible with the installed build. | Migrate to doc.html(element, options) and use the current package API. |
html2canvas is not defined |
The legacy plugin expects a global that your module build did not expose. | Install/import the dependency or use a supported jsPDF build configuration. |
| “You need either html2canvas or rasterizeHTML” | The old implementation cannot find either renderer. | Remove the legacy path; configure the dependency for doc.html(). |
| Callback never runs or export is premature | Old callback assumptions or rendering is not awaited. | Use an async function and await doc.html(); follow the installed version’s callback shape. |
| PDF is blank or cut off | Target is absent/hidden, dimensions are wrong, or canvas is too large. | Check the element, set scroll dimensions, reduce scale, or split the content. |
| Images disappear | Cross-origin image blocked, no CORS permission, or image not loaded yet. | Check response headers and image loading; use same-origin assets or an authorized proxy. |
| Iframe contents are missing | Browser same-origin restrictions prevent reading a cross-origin frame. | Render content from an authorized accessible origin or capture it in a browser workflow that has access. |
| Looks different from the browser | html2canvas has limited CSS fidelity. | Simplify unsupported effects or use a real browser renderer. |
| Fails in Node.js with window/document errors | html2canvas is browser-only. | Run the capture in a browser, or use Puppeteer/Playwright for server-side rendering. |
7. Browser and server-side choices
html2canvas depends on browser APIs including window, document, and computed styles. It is client-side only and cannot be run directly in a plain Node.js process. If you need to generate PDFs on a server, use a headless browser such as Puppeteer or Playwright to load and render the page in a browser context. That approach can provide more faithful browser rendering, but it requires managing a browser runtime, page readiness, fonts, assets, and process resources.

For a client-side export that must use the live page’s authenticated state or local data, doc.html() can be convenient. For repeatable server jobs, browser automation is generally a better fit. For just a website image or PDF from a URL, a screenshot API avoids maintaining browser setup; choose based on whether you need live DOM access, page-specific client state, or a URL-based capture.
8. Or skip the browser setup
If your requirement is to capture a webpage by URL, ScreenshotNeo is a website screenshot API and MCP server. It returns PNG, JPEG, WebP, or PDF from one GET request. See the API documentation for request options.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get(
"https://api.screenshotneo.com/v1/shot",
params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"},
timeout=90,
)
r.raise_for_status()
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
if (!res.ok) throw new Error(`Screenshot request failed: ${res.status}`);
const bytes = new Uint8Array(await res.arrayBuffer());
await import('node:fs/promises').then(fs => fs.writeFile('shot.webp', bytes));
ScreenshotNeo accepts cookie or consent banners like a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks and CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and response headers report the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.
The Free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots; higher tiers are Growth $15 for 15,000, Pro $39 for 60,000, Scale $99 for 250,000, and Business $249 for 1,000,000. Yearly billing gives two months free, and every feature is on every plan. Sign up for 1,000 free screenshots a month with no card.
9. Performance, reliability, and cost
Client-side canvas rendering consumes memory in the user’s browser. Higher scale increases pixel count, while long pages and large images can multiply the cost. Start at a moderate scale, capture only the required element, and split exceptionally long content. Avoid running multiple large exports simultaneously on low-memory devices.
Reliability depends on page readiness, asset access, browser support, and canvas size. A successful JavaScript call does not guarantee a faithful PDF: inspect representative output, especially for long pages, remote images, and custom CSS. For a server workflow, account for the operational work of keeping browser binaries and runtime dependencies available. A URL-based API instead has per-plan usage limits; review its response headers and usage API to understand capture outcomes and consumption. ScreenshotNeo states that only clean shots are billed, with cache hits and failed or blocked captures free.
10. FAQ
Can I keep using addHTML if I pin an old version?
You may encounter old integrations that still depend on it, but the jsPDF maintainers say they will no longer support addHTML or fromHTML. Migrate to html() to use the maintained path.
Does html2canvas print the page exactly as Chrome displays it?
No. It reconstructs the DOM and supports many, but not all, CSS properties. A real browser screenshot or print renderer is preferable when exact browser fidelity is required.
Can I capture a cross-origin iframe from my page?
Not through ordinary html2canvas access when browser same-origin restrictions prevent reading the frame. Render the content from an accessible origin or use a workflow with authorized access.
Can I use html2canvas in a Node serverless function?
Not directly: it requires a browser environment. Use a headless browser runtime for server-side rendering, or capture a URL through a screenshot API.


