Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The fix is to pass jsPDF/html2canvas a live HTMLElement that is attached to the current document. The error appears when the value is null, a jQuery collection, a detached node, a stale framework ref, or an element whose ownerDocument has no window. Select the real DOM node, wait until it is mounted, verify attachment, then use the Promise-based API. PDF size, margins, and image settings cannot repair an invalid element reference.

What the error actually means

jsPDF’s HTML rendering path delegates DOM rendering to html2canvas. Current html2canvas validates its first argument before it starts rendering. A non-object produces an invalid-element error; an object without ownerDocument produces Element is not attached to a Document; and a document whose defaultView is missing produces Document is not attached to a Window. The commonly reported jsPDF wording, Provided element is not within a Document, describes the same basic failure: the renderer cannot find your target in a live, window-backed DOM.

The original html2canvas issue with that exact wording was opened on December 14, 2017 and closed as “Needs More Information.” It is useful historical context, not a universal fix. The maintainer-attributed explanation was that the element being rendered was not within the document DOM.

Values that commonly trigger it

Value passed to the renderer Why it fails
document.querySelector('#invoice') returns null The selector did not match, or the code ran before the element was mounted.
$('#invoice') This is a jQuery collection, not the first DOM element. Pass $('#invoice')[0] or $('#invoice').get(0).
A React/Vue ref before mount The ref is still null, or the component is about to unmount.
A node removed from the DOM The reference exists in JavaScript but is no longer attached to the live document.
An HTML string, component object, virtual-DOM node, or base64 string html2canvas expects an HTMLElement, not a representation of one.

Reliable fix sequence

1. Obtain the actual element

Use a selector that identifies the element you intend to export, and stop immediately if it is missing.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Adobe Acrobat Pro | PDF Software | Convert, Edit, E-Sign, Protect | PC/Mac Online Code | Activation Required
  • Create and edit PDFs. Collaborate with ease. E-sign documents and collect signatures. Get everything done in one app, wherever you go.
  • Edit text and images without jumping to another app.
  • E-sign documents or request e-signatures on any device. Recipients don’t need to log in to e-sign.
  • Convert PDFs to editable Microsoft Word, Excel, or PowerPoint documents.
  • Share PDFs for collaboration. Commenting features make it easy for reviewers to comment, mark up, and annotate.
const element = document.querySelector('#invoice');
if (!element) {
  throw new Error('Invoice element not found');
}
if (!(element instanceof HTMLElement)) {
  throw new Error('Invoice is not an HTMLElement');
}

If you use jQuery, unwrap the collection:

const element = $('#invoice').get(0);
if (!element) throw new Error('Invoice element not found');

2. Confirm that it is attached

A node can pass the selector check and still be detached. Verify both document identity and containment before starting asynchronous rendering.

if (element.ownerDocument !== document) {
  throw new Error('Element belongs to a different document');
}
if (!element.ownerDocument?.defaultView) {
  throw new Error('Element document has no window');
}
if (!document.body.contains(element)) {
  throw new Error('Invoice is not attached to document.body');
}

Run this check after the modal or view has rendered, not in the click handler that begins mounting it. A hidden component may be valid if it remains in the document, but a component that has not mounted or has already been unmounted cannot be captured.

3. Use the Promise API and handle rejection

Call html2canvas with the verified element and catch failures. The following browser example assumes the jsPDF and html2canvas scripts are already loaded.

const element = document.querySelector('#invoice');
if (!element || !document.body.contains(element)) {
  throw new Error('Invoice must be a mounted HTMLElement');
}

html2canvas(element, { useCORS: true })
  .then((canvas) => {
    const pdf = new jsPDF();
    const image = canvas.toDataURL('image/png');
    pdf.addImage(image, 'PNG', 0, 0, 210, 297);
    pdf.save('invoice.pdf');
  })
  .catch((error) => {
    console.error('Invoice capture failed:', error);
  });

Older examples use an onrendered callback. That option is deprecated; jsPDF’s HTML module removes it before calling html2canvas. Promise handlers make the asynchronous failure visible and work with current APIs.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Acrobat Pro | 1-Month Subscription | PDF Software |Convert, Edit, E-Sign, Protect |Activation Required [PC/Mac Online Code]
  • Create and edit PDFs. Collaborate with ease. E-sign documents and collect signatures. Get everything done in one app, wherever you go.
  • Edit text and images without jumping to another app.
  • E-sign documents or request e-signatures on any device. Recipients don’t need to log in to e-sign.
  • Convert PDFs to editable Microsoft Word, Excel, or PowerPoint documents.
  • Share PDFs for collaboration. Commenting features make it easy for reviewers to comment, mark up, and annotate.

4. Let jsPDF’s HTML module manage its container

For ordinary HTML-to-PDF work, jsPDF’s HTML module is often simpler than manually converting a canvas. When given an Element, the module clones it, appends an overlay/container to document.body, calls html2canvas on that attached container, and removes the overlay after completion.

const element = document.querySelector('#invoice');
if (!element || !document.body.contains(element)) {
  throw new Error('Invoice must be mounted before export');
}

const pdf = new jsPDF();
pdf.html(element, {
  callback: (doc) => doc.save('invoice.pdf'),
  html2canvas: { useCORS: true }
});

This does not make an invalid input valid: the element supplied to pdf.html still must be a live HTMLElement.

Framework and modal timing

React

Keep a DOM ref on the element itself and capture only while the component is mounted. If opening a modal changes state, wait for the open/rendered state before calling the export function.

import { useRef } from 'react';

function InvoiceModal() {
  const invoiceRef = useRef(null);

  const download = () => {
    const element = invoiceRef.current;
    if (!element || !document.body.contains(element)) {
      throw new Error('Invoice is not mounted');
    }

    html2canvas(element, { useCORS: true }).then((canvas) => {
      const pdf = new jsPDF();
      pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, 210, 297);
      pdf.save('invoice.pdf');
    }).catch(console.error);
  };

  return (
    <section ref={invoiceRef}>
      <button onClick={download}>Download PDF</button>
      {/* invoice content */}
    </section>
  );
}

Do not pass the React component, a ref object such as invoiceRef, or a ref captured before the modal exists. Pass invoiceRef.current after rendering.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
PDF Extra Lifetime - Professional PDF Editor - Best Adobe Acrobat Pro Alternative - Lifetime License for Windows PC
  • Perfect Adobe Acrobat Pro alternative – lifetime license for Windows 10 and 11.
  • EDIT text, images, pages, hyperlinks, designs in PDF documents. ORGANIZE PDFs.
  • READ and Comment on PDFs – Intuitive reading modes & document commenting and mark up tools!
  • CREATE, COMBINE, SCAN and COMPRESS PDFs.
  • FILL forms & Digitally Sign PDFs. Work with Digital certificates

Vue

Use a template ref and wait for Vue’s next render tick when opening a modal.

<script setup>
import { ref, nextTick } from 'vue';

const invoice = ref(null);
const open = ref(false);

async function download() {
  open.value = true;
  await nextTick();
  const element = invoice.value;
  if (!element || !document.body.contains(element)) {
    throw new Error('Invoice is not mounted');
  }
  html2canvas(element, { useCORS: true }).then((canvas) => {
    const pdf = new jsPDF();
    pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, 210, 297);
    pdf.save('invoice.pdf');
  }).catch(console.error);
}
</script>

Call capture after mounted or nextTick, not while the conditional modal branch is still being inserted.

Minimal diagnostic checklist

Paste these assertions immediately before the html2canvas or jsPDF call:

console.assert(element instanceof HTMLElement);
console.assert(element.ownerDocument === document);
console.assert(element.ownerDocument?.defaultView);
console.assert(document.body.contains(element));
  • If the first assertion fails, correct the value you pass.
  • If the second fails, you are using a node from another document, such as an iframe or an old page instance.
  • If the third fails, the document is not connected to a browser window.
  • If the fourth fails, fix selection or component lifecycle before changing PDF options.

What can go wrong after attachment is fixed?

Attachment errors and rendering-quality problems are separate. html2canvas does not capture browser pixels directly. It traverses the DOM and builds a representation from CSS properties it understands, so unsupported CSS can differ from the on-screen page. Images generally need to be same-origin or served through a proxy; cross-origin image content can make the canvas unreadable. These issues can produce blank, missing, or incomplete output even when every attachment assertion passes.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
PDF Extra 2024| Complete PDF Reader and Editor | Create, Edit, Convert, Combine, Comment, Fill & Sign PDFs | Lifetime License | 1 Windows PC | 1 User [PC Online code]
  • EDIT text, images & designs in PDF documents. ORGANIZE PDFs. Convert PDFs to Word, Excel & ePub.
  • READ and Comment PDFs – Intuitive reading modes & document commenting and mark up.
  • CREATE, COMBINE, SCAN and COMPRESS PDFs
  • FILL forms & Digitally Sign PDFs. PROTECT and Encrypt PDFs
  • LIFETIME License for 1 Windows PC or Laptop. 5GB MobiDrive Cloud Storage Included.

Check resources and styles independently

  • Use useCORS: true when the image server sends appropriate CORS headers.
  • Test the target with a simple background and text if a complex stylesheet produces unexpected output.
  • Wait for images and fonts to load before capture when the page fills them asynchronously.
  • Do not treat a blank canvas caused by blocked cross-origin resources as proof that the element is detached.

Choosing an implementation path

Approach Best fit Important trade-off
Direct html2canvas plus jsPDF.addImage Precise control over canvas processing, image format, and PDF placement. You handle element validation, canvas conversion, sizing, and pagination.
jsPDF.html Typical HTML-to-PDF exports with less glue code. The module still requires a mounted Element and inherits html2canvas’s CSS and image limitations.
Mounted React/Vue ref Components and modals whose DOM is controlled by a framework. You must schedule capture after mount and before unmount.
Selector lookup Static pages or simple event handlers. A selector can return null after a markup change or before rendering.

There is no source-supported universal performance winner among these choices. Select the path that matches your lifecycle and the amount of PDF layout control you need.

Version and API checks

The historical issue is from 2017, while html2canvas’s cited validation code is from its current master implementation viewed September 29, 2026. Behavior can vary with the versions installed in your application, so record both packages when debugging:

npm ls jspdf html2canvas

Upgrade only after reproducing the problem with a verified element. A version change may alter rendering behavior, but it cannot replace the core invariant: the input must be a live, document-attached HTMLElement whose owner document has a window.

Troubleshooting common failures

Symptom Likely cause Fix
Provided element is not within a Document Null, detached, or wrong-type input. Log the value, pass the underlying HTMLElement, and run the four assertions.
Invalid element provided as first argument A string, jQuery collection, component, or other non-object was supplied. Use querySelector or unwrap the jQuery collection with [0]/get(0).
Element is not attached to a Document The node has no owner document or was removed. Capture after mount and verify document.body.contains(element).
Document is not attached to a Window The owner document has no defaultView. Use the element from the active browser document, not a detached document.
Works on one click but fails in a modal The click starts mounting or immediately unmounts the modal. Trigger from the rendered/open state and wait for the framework’s next tick.
PDF is blank or missing images Cross-origin resources or unsupported CSS, not necessarily attachment. Check image origin and CORS headers, try useCORS, and simplify unsupported styles.
Old callback example does nothing onrendered is deprecated. Use the Promise returned by html2canvas or the callback option of jsPDF.html.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your source is a public URL rather than a live, interactive component, ScreenshotNeo can return a PNG, JPEG, WebP, or PDF with one GET request. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Only clean shots are billed: bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and the response identifies the result with X-Page-Verdict and X-Billed headers. Its MCP server exposes take_screenshot, get_page_info, and capture_pdf to Claude, Cursor, and other MCP clients.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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}`);

See the ScreenshotNeo documentation for request options. The service also supports full-page captures with lazy images loaded, CSS-selector element captures, dark mode, device and viewport settings, retina scale, PDF paper and page-range controls, custom CSS and JavaScript, click and wait conditions, request blocking, headers, cookies, user agents, authorization, timezone and geolocation, transparent backgrounds, resizing, chosen cache TTLs, signed links, asynchronous jobs with signed webhooks, bulk capture of up to 100 URLs per call, a usage API, an OpenAPI specification, and familiar parameter names used by other screenshot APIs.

Best Value
PDF Director 3 PLUS - Edit, Convert, Redact, Protect PDFs, Fill Forms for Win 11, 10, 8.1, 7
  • Full-featured PDF Editor: Edit text in the document
  • Fully convert PDF to Word and Excel and continue editing
  • NEW: Further development of existing functions
  • NEW: Even faster and more user-friendly
  • NEW: Over 75 small improvements in all areas

The Free plan includes 1,000 screenshots per month with no card. Paid plans start at $5 for 3,000 shots; every feature is available on every plan. Create a free ScreenshotNeo account to try it.

Frequently Asked Questions

Does changing the PDF page size fix this error?

No. Page size, margins, and image dimensions are applied only after a valid element has been accepted. Resolve the DOM and lifecycle checks first.

Why can the same selector work on one page but not another?

The selector may run at a different lifecycle point, match a modal that has not mounted, or refer to a node replaced during a framework update. Log the element immediately before capture and test containment at that moment.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Quick Recap

Bestseller No. 1
Adobe Acrobat Pro | PDF Software | Convert, Edit, E-Sign, Protect | PC/Mac Online Code | Activation Required
Adobe Acrobat Pro | PDF Software | Convert, Edit, E-Sign, Protect | PC/Mac Online Code | Activation Required
Edit text and images without jumping to another app.; Convert PDFs to editable Microsoft Word, Excel, or PowerPoint documents.
$239.88
Bestseller No. 2
Acrobat Pro | 1-Month Subscription | PDF Software |Convert, Edit, E-Sign, Protect |Activation Required [PC/Mac Online Code]
Acrobat Pro | 1-Month Subscription | PDF Software |Convert, Edit, E-Sign, Protect |Activation Required [PC/Mac Online Code]
Edit text and images without jumping to another app.; Convert PDFs to editable Microsoft Word, Excel, or PowerPoint documents.
$29.99
Bestseller No. 3
PDF Extra Lifetime - Professional PDF Editor - Best Adobe Acrobat Pro Alternative - Lifetime License for Windows PC
PDF Extra Lifetime - Professional PDF Editor - Best Adobe Acrobat Pro Alternative - Lifetime License for Windows PC
Perfect Adobe Acrobat Pro alternative – lifetime license for Windows 10 and 11.; EDIT text, images, pages, hyperlinks, designs in PDF documents. ORGANIZE PDFs.
$99.99
Bestseller No. 4
PDF Extra 2024| Complete PDF Reader and Editor | Create, Edit, Convert, Combine, Comment, Fill & Sign PDFs | Lifetime License | 1 Windows PC | 1 User [PC Online code]
PDF Extra 2024| Complete PDF Reader and Editor | Create, Edit, Convert, Combine, Comment, Fill & Sign PDFs | Lifetime License | 1 Windows PC | 1 User [PC Online code]
READ and Comment PDFs – Intuitive reading modes & document commenting and mark up.; CREATE, COMBINE, SCAN and COMPRESS PDFs
$99.99
Bestseller No. 5
PDF Director 3 PLUS - Edit, Convert, Redact, Protect PDFs, Fill Forms for Win 11, 10, 8.1, 7
PDF Director 3 PLUS - Edit, Convert, Redact, Protect PDFs, Fill Forms for Win 11, 10, 8.1, 7
Full-featured PDF Editor: Edit text in the document; Fully convert PDF to Word and Excel and continue editing
$29.99

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.