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

iTechGuides is reader-supported. When you buy through links on our site, we may earn an affiliate commission. As an Amazon Associate I earn from qualifying purchases. Learn more

Find the stage where the image disappears: check the source image and the canvas returned by html2canvas before debugging jsPDF. If the canvas is missing the image, investigate loading, cross-origin restrictions, rendering, or capture dimensions. If the canvas is correct but the PDF is not, check the data passed to addImage and its format and placement.

Diagnose the failure before changing code

There are two separate operations: html2canvas renders a DOM element into a canvas, then jsPDF embeds image data into a PDF. Inspect the canvas between those steps. This narrows the problem to the component that actually lost the image.

  1. Check the source. Open the image URL directly. Confirm it returns the image, not a login screen, error page, or other response. In your browser’s Network and Console panels, look for failed requests or cross-origin errors.
  2. Inspect the canvas. Temporarily add it to the page with document.body.appendChild(canvas). Confirm that the image appears and that the canvas width and height are nonzero and large enough for the target.
  3. Check the PDF handoff. If the displayed canvas is correct, inspect the image input, format, coordinates, width, and height passed to addImage.

html2canvas is not a literal browser screenshot tool: it builds a representation from properties it reads from the DOM. That means a browser-rendered page and the resulting canvas can differ. Its documentation also notes that browser security prevents access to cross-origin iframe contents. See the html2canvas documentation.

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

Use this browser flow to render and add the image

The example below assumes a browser project that can resolve the installed html2canvas and jspdf packages. It captures an element with id report, checks the rendered canvas, and adds it to a PDF while preserving the canvas aspect ratio. The chosen page placement and available space are examples; adjust them to your PDF layout.

#1 Best Overall
MixPad Free Multitrack Recording Studio and Music Mixing Software [Download]
  • Create a mix using audio, music and voice tracks and recordings.
  • Customize your tracks with amazing effects and helpful editing tools.
  • Use tools like the Beat Maker and Midi Creator.
  • Work efficiently by using Bookmarks and tools like Effect Chain, which allow you to apply multiple effects at a time
  • Use one of the many other NCH multimedia applications that are integrated with MixPad.
import html2canvas from 'html2canvas';
import { jsPDF } from 'jspdf';

async function saveElementAsPdf() {
  const element = document.querySelector('#report');
  if (!element) throw new Error('Could not find #report');

  // Wait for images inside the element to finish loading where possible.
  const images = Array.from(element.querySelectorAll('img'));
  await Promise.all(images.map(async (img) => {
    if (!img.complete) {
      await new Promise((resolve) => {
        img.addEventListener('load', resolve, { once: true });
        img.addEventListener('error', resolve, { once: true });
      });
    }
  }));

  const canvas = await html2canvas(element, {
    useCORS: true,
    windowWidth: element.scrollWidth,
    windowHeight: element.scrollHeight
  });

  // Diagnostic: inspect this before involving jsPDF.
  document.body.appendChild(canvas);
  console.log('Rendered canvas:', canvas.width, canvas.height);

  // This read/export step requires an origin-clean canvas.
  const imageData = canvas.toDataURL('image/png');
  const pdf = new jsPDF();
  const margin = 10;
  const pageWidth = pdf.internal.pageSize.getWidth();
  const availableWidth = pageWidth - margin * 2;
  const imageHeight = canvas.height * (availableWidth / canvas.width);

  pdf.addImage(imageData, 'PNG', margin, margin, availableWidth, imageHeight);
  pdf.save('capture.pdf');
}

saveElementAsPdf().catch(console.error);

The documented windowWidth and windowHeight options can align the render window with an element’s scroll dimensions. This may help when content is clipped, but it does not remove browser canvas size limits. If the output is blank or partial, compare its dimensions with the element’s scroll dimensions and try a smaller capture before increasing scale. Browser limits vary; the html2canvas FAQ does not give one stable numeric limit for all devices and browsers. See the html2canvas configuration.

The image-load wait above proceeds after either a load or an error event; it does not make a failed image succeed. For pages with lazy-loaded images, make sure the relevant content has been brought into view or otherwise loaded before capture. Then check the Network panel and the canvas itself.

Fix cross-origin images without weakening browser security

A remote image can load visibly in a page yet still be unavailable for canvas export. When a cross-origin image is drawn without permission, it taints the canvas; a tainted canvas cannot be safely read or exported as a data URL. The html2canvas FAQ explains that the library cannot bypass browser content policy: html2canvas FAQ.

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

If you control the image server

Configure the server to return an appropriate Access-Control-Allow-Origin response header for the page’s origin (or a broader origin policy only if appropriate for your application). Then use useCORS: true in html2canvas. That option requests cross-origin loading; it does not grant permission by itself. Verify the actual image response headers in the Network panel.

If you do not control the image server

Use a permitted same-origin proxy that fetches the image and serves it from your origin with suitable safeguards. A proxy introduces its own operational cost and latency, and it must be designed so that your application does not become an unrestricted fetch service. Another possibility is to use an image source you can serve from the same origin or embed as data, if that is suitable for the application.

Do not use allowTaint as a CORS workaround

The documented default for allowTaint is false; html2canvas skips a cross-origin image when drawing it would taint the canvas. Setting allowTaint: true does not make a tainted canvas readable, so it is not a fix when you need toDataURL or another exportable result. Use server permission or an appropriate same-origin source instead. The available settings are described in the configuration reference.

Check the jsPDF addImage input and placement

If the canvas visibly contains the image and can be exported, make sure the exact value passed into jsPDF is valid. The jsPDF addImage API documents supported inputs including base64 data URLs, HTMLImageElement, HTMLCanvasElement, Uint8Array, and RGBA data. Invalid image input can throw.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Pass the actual canvas or the data URL created from that canvas—not the original DOM element that html2canvas rendered.
  • When using a data URL, keep its format consistent with the declared format argument. For a PNG data URL, use 'PNG'.
  • When passing a canvas or another input whose format may be ambiguous, provide the format explicitly.
  • Use finite, valid x/y coordinates and positive width/height values in the PDF’s units. Check that the image fits inside the page, accounting for margins and orientation.
  • Preserve the source aspect ratio when computing the PDF dimensions unless you deliberately want the image stretched.

The example uses the image width to calculate a proportional height. A tall canvas may extend beyond a single page; that is a pagination/layout issue, not proof that the image failed to render. Choose a page layout or split the content to fit your intended document.

Match the symptom to the next check

Symptom Inspect first Likely cause or next action
Image is missing from both canvas and PDF Image request and rendered canvas Check failed loading, CORS, whether html2canvas represents the relevant DOM content, or whether the image was skipped because it would taint the canvas.
toDataURL or pixel reading fails Canvas security state A cross-origin resource may have tainted it. Use a server that grants the required CORS access or a suitable same-origin proxy.
Canvas is blank, partial, or cut off Canvas dimensions and target scroll size Try a smaller target; compare dimensions; consider windowWidth and windowHeight for the element’s scroll dimensions.
Canvas looks right, but PDF omits the image addImage arguments Check the input type, format, coordinates, dimensions, and whether the image fits the page.
Only some page content is missing DOM element and content origin or type html2canvas reconstructs a DOM representation rather than taking a literal screenshot; cross-origin iframe contents are not accessible to it.

Keep capture size, sharpness, and reliability in balance

Large captures and high scale settings increase the canvas dimensions and can make browser limits more likely to matter. The html2canvas configuration documentation gives scale a default of the device pixel ratio, but does not prescribe one scale for every device or document. If a capture fails at a larger size, reduce the target area or scale and check whether the smaller canvas renders and exports correctly. Increasing scale can improve raster sharpness, but it also increases the amount of image data to process.

Rank #4
DeskFX Free Audio Effects & Audio Enhancer Software [PC Download]
  • Transform audio playing via your speakers and headphones
  • Improve sound quality by adjusting it with effects
  • Take control over the sound playing through audio hardware

For a repeatable workflow, wait until the content and images needed for the capture are available, inspect the resulting canvas before PDF generation, and handle failures explicitly rather than assuming a successful promise means every image rendered. If the same URL works in one browser but not another, compare their image requests, response headers, viewport dimensions, and canvas output; do not assume a universal browser limit or a single jsPDF defect.

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 goal is to capture a webpage as an image or PDF rather than to render a particular in-app DOM element, ScreenshotNeo offers a website screenshot API. One GET request can return a PNG, JPEG, WebP, or PDF. For example, this cURL request saves a WebP screenshot of Stripe:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for the request options and authentication details. The same request can be made in Python or Node.js:

Best Value
MixPad Multitrack Recording Software for Sound Mixing and Music Production Free [Mac Download]
  • Mix an audio, music and voice tracks
  • Record single or multiple tracks simultaneously
  • Intuitive tools to split, trim, join, and many other editing features
  • Loaded with audio effects including EQ, compression, reverb, and more.
  • Load an audio file and export to all popular audio formats from studio quality wav to high compression formats
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)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
  • Cookie and consent banners, newsletter popups, and chat widgets are removed before capture; each cleanup step can be turned off.
  • Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed. Response headers report the page verdict and billing status.
  • An 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 shots per month with no card; paid plans start at $5 for 3,000 shots. Every feature is on every plan.

Sign up for ScreenshotNeo’s free plan and get 1,000 screenshots a month with no card.

This is a webpage-capture alternative, not a way to fix CORS for an image inside your application or to capture an arbitrary DOM element from the current browser page. Use the browser workflow when that is the requirement.

Frequently Asked Questions

Are these instructions tied to a particular installed version of either library?

No version is specified here. The cited live documentation pages do not identify your project’s installed dependencies, so check your package lockfile and use documentation matching those versions before relying on version-specific behavior.

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

Quick Recap

Bestseller No. 1
MixPad Free Multitrack Recording Studio and Music Mixing Software [Download]
MixPad Free Multitrack Recording Studio and Music Mixing Software [Download]
Create a mix using audio, music and voice tracks and recordings.; Customize your tracks with amazing effects and helpful editing tools.
Bestseller No. 4
DeskFX Free Audio Effects & Audio Enhancer Software [PC Download]
DeskFX Free Audio Effects & Audio Enhancer Software [PC Download]
Transform audio playing via your speakers and headphones; Improve sound quality by adjusting it with effects
Bestseller No. 5
MixPad Multitrack Recording Software for Sound Mixing and Music Production Free [Mac Download]
MixPad Multitrack Recording Software for Sound Mixing and Music Production Free [Mac Download]
Mix an audio, music and voice tracks; Record single or multiple tracks simultaneously; Intuitive tools to split, trim, join, and many other editing features

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.