Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run Scan×
Skip to content
html2canvas

How to Combine jQuery Functions to Save html2canvas Output as a PDF

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

Use jQuery for the click handler and element lookup, then wait for html2canvas’s Promise before creating and saving the jsPDF file. The critical sequence is: unwrap the jQuery collection with [0], await html2canvas(), convert the resulting canvas with toDataURL(), place that image in jsPDF, and call save() only after rendering has completed.

The working pattern

Assume your page contains an element with id="content" and a button with id="savePdf". This handler combines jQuery and the two rendering libraries without racing the browser:

$('#savePdf').on('click', async function () {
  const target = $('#content')[0];

  if (!target) {
    alert('The content element was not found.');
    return;
  }

  try {
    const canvas = await html2canvas(target, {
      scale: window.devicePixelRatio,
      useCORS: true
    });

    if (!canvas.width || !canvas.height) {
      throw new Error('html2canvas returned an empty canvas.');
    }

    const imgData = canvas.toDataURL('image/png');
    const pdf = new jsPDF({ unit: 'pt', format: 'a4', orientation: 'portrait' });
    const pageWidth = pdf.internal.pageSize.getWidth();
    const pageHeight = pdf.internal.pageSize.getHeight();
    const ratio = Math.min(pageWidth / canvas.width, pageHeight / canvas.height);
    const imageWidth = canvas.width * ratio;
    const imageHeight = canvas.height * ratio;

    pdf.addImage(imgData, 'PNG', 0, 0, imageWidth, imageHeight);
    pdf.save('export.pdf');
  } catch (error) {
    console.error('PDF export failed:', error);
    alert('Could not create the PDF. Check the console for details.');
  }
});

html2canvas documents that its function returns a Promise resolving to a <canvas> element (official getting-started documentation). Therefore, calling pdf.save() immediately after starting html2canvas can produce an empty or incomplete file.

Why the jQuery collection must be unwrapped

$('#content') is a jQuery collection, even when it contains one element. html2canvas expects the underlying DOM node. Use $('#content')[0] or $('#content').get(0):

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.
#1 Best Overall
Epson EcoTank ET-2800 Wireless Color All-in-One Supertank Printer - Black
  • 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
const target = $('#content')[0];
const canvas = await html2canvas(target);

Passing the collection itself can result in a type error or no useful render. Check that the result is not undefined when the selector does not match anything.

What happens in each stage

  1. Event binding: jQuery listens for the button’s click.
  2. Element lookup: jQuery finds the content and [0] extracts its DOM element.
  3. DOM reconstruction: html2canvas reads the element and draws a visual representation into a canvas. It does not take a native operating-system screenshot; it recreates the page from DOM and CSS (project documentation).
  4. Promise completion: await pauses the handler until the canvas is ready.
  5. Image serialization: canvas.toDataURL('image/png') creates the image payload.
  6. PDF placement: jsPDF inserts that image and writes the file.
  7. Download: pdf.save() starts the browser download only after all previous work succeeds.

Promise syntax without async/await

If your codebase uses callbacks, put every PDF operation inside .then(). This is the same ordering as the async version:

$('#savePdf').on('click', function () {
  const target = $('#content')[0];

  if (!target) {
    alert('The content element was not found.');
    return;
  }

  html2canvas(target, { useCORS: true })
    .then(function (canvas) {
      if (!canvas.width || !canvas.height) {
        throw new Error('The canvas is empty.');
      }

      const pdf = new jsPDF('p', 'pt', 'a4');
      const pageWidth = pdf.internal.pageSize.getWidth();
      const scale = pageWidth / canvas.width;

      pdf.addImage(
        canvas.toDataURL('image/png'),
        'PNG',
        0,
        0,
        canvas.width * scale,
        canvas.height * scale
      );
      pdf.save('export.pdf');
    })
    .catch(function (error) {
      console.error('PDF export failed:', error);
      alert('Could not create the PDF.');
    });
});

Fit the image to a page correctly

A canvas can be much wider or taller than an A4 page. Calculate one ratio and apply it to both dimensions so the image is not distorted:

const margin = 24;
const availableWidth = pageWidth - margin * 2;
const availableHeight = pageHeight - margin * 2;
const ratio = Math.min(
  availableWidth / canvas.width,
  availableHeight / canvas.height
);

pdf.addImage(
  imgData,
  'PNG',
  margin,
  margin,
  canvas.width * ratio,
  canvas.height * ratio
);

If the content is taller than one page, fitting it onto a single page can make text unreadably small. Render separate sections, or slice the canvas into page-sized portions and call pdf.addPage() for each slice. Test page breaks with the real content; a visual image PDF has no automatic understanding of paragraphs, tables, or headings.

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.

Useful html2canvas options

Option Purpose Important limitation
scale Controls canvas resolution. window.devicePixelRatio usually improves sharpness on high-DPI screens. Higher values increase memory use, render time, and output size.
useCORS: true Attempts to load cross-origin images with CORS. It works only when the image server sends permissive CORS headers; it cannot bypass browser security.
data-html2canvas-ignore Marks controls, ads, or other elements to exclude. Add the attribute to each element you do not want rendered.

For example:

<button id="savePdf" data-html2canvas-ignore>Save PDF</button>

Make the captured state deterministic

  • Wait until fonts, charts, and asynchronous data have finished before starting the export. A short application-level wait or a “ready” state is more reliable than an arbitrary delay.
  • Temporarily open collapsed panels or remove hover-only styling if those states must appear in the PDF.
  • Use a print-specific class to hide navigation and interactive controls, then remove it in a finally block.
  • Keep the target visible and attached to the document. Elements with display: none have no layout for html2canvas to reproduce.

Cross-origin images and canvas tainting

Images loaded from another origin can taint the canvas. When that happens, toDataURL() may throw a security exception or the image may be omitted. Prefer same-origin assets, configure the image server to send an appropriate Access-Control-Allow-Origin header, and use useCORS: true. A proxy under your control can relay assets when policy permits. Do not treat useCORS as a way to defeat cross-origin restrictions.

Visual PDF, not native PDF text

This workflow places a raster image in the PDF. The result preserves the appearance of the page, but text generally is not selectable as native PDF text and the document is not automatically accessible to screen readers. If searchable, selectable text or semantic accessibility is a requirement, generate a structured PDF instead of relying solely on a canvas image.

Rank #2
Sale
Epson EcoTank Photo ET-8550 Wireless Wide-Format All-in-One Tank Printer
  • 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⁴

html2canvas plus jsPDF versus html2pdf.js

Manual html2canvas and jsPDF code gives you direct control over page dimensions, margins, image placement, and custom page slicing. It is a good fit for a single dashboard, invoice, or controlled panel.

html2pdf.js wraps the same general workflow in a chain: .from() -> .toContainer() -> .toCanvas() -> .toImg() -> .toPdf() -> .save(). Its options can reduce boilerplate and help with page-break handling, but you still need to test long layouts, unsupported CSS, fonts, and cross-origin assets. Both approaches inherit browser same-origin and canvas-taint restrictions.

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

Performance, reliability, and cost considerations

  • Memory: canvas memory grows with pixel dimensions. A large full-page element at a high scale can exceed mobile-device limits.
  • Speed: simplify expensive effects, capture only the required element, and avoid needlessly large images.
  • Repeat clicks: disable the button while rendering and re-enable it in finally to prevent duplicate downloads.
  • Validation: check canvas dimensions before calculating ratios, and log the original error so failures are diagnosable.
  • Browser behavior: downloads can be blocked when triggered outside a user gesture. Keep the initial call in the click handler; asynchronous work started from that handler normally retains the intended interaction.

Common failures and fixes

“Cannot read properties of undefined”

The selector matched nothing, so $('#content')[0] is undefined. Verify the ID, run the handler after the DOM exists, and check the element before calling html2canvas.

The PDF downloads before the page is rendered

pdf.save() is outside the Promise callback or follows an un-awaited call. Move all PDF code into await html2canvas(...), .then(), or a function that returns the Promise.

Images are missing or toDataURL() throws

Inspect cross-origin assets. Serve them from the same origin or configure CORS on the image host; then enable useCORS. A browser policy cannot be bypassed in JavaScript.

The output is blank

Capture only after the target has dimensions and visible content. Check for display:none, zero width or height, a failed data request, or a canvas size that exceeds device limits.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
HP Smart Tank 5000 Wireless All-in-One Ink Tank Printer, Scanner, Copier with 2 Years of Ink Included, Best-for-Home, Cartridge-Free, Refillable and AI-Enabled. (5D1B6A)
  • 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.

The PDF is one tiny page

Your entire tall canvas was scaled to fit one sheet. Slice the canvas into multiple pages or capture logical sections separately.

Styles look different

html2canvas supports a DOM/CSS subset, not every browser feature. Replace unsupported effects for the export state, wait for web fonts, and test the exact browsers your users run.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server when you need a clean capture without wiring a browser renderer into your page. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed; the response identifies the result with X-Page-Verdict and X-Billed headers. Its MCP tools—take_screenshot, get_page_info, and capture_pdf—work with Claude, Cursor, and other MCP clients.

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 parameters such as full-page capture, CSS-selector element capture, dark mode, device presets, retina scale, PDF paper settings, custom CSS and JavaScript, click actions, waits, request blocking, headers, cookies, user agents, timezone and geolocation, transparent backgrounds, resizing, cache TTLs, signed links, asynchronous webhooks, bulk capture, and usage reporting.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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}`);

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

FAQ

Can I pass a jQuery object directly to html2canvas?

No. Pass the DOM node extracted with [0] or .get(0).

Does this produce a searchable PDF?

Not usually. The workflow embeds a rendered image, so text is generally not native PDF text.

Rank #4
NDYIN Portable Printers Wireless for Travel, N80 Bluetooth Thermal Printer
  • 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

Will useCORS load every remote image?

No. The remote server must explicitly permit the request with CORS headers.

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

How should I export a very long page?

Capture sections separately or slice the canvas across multiple PDF pages rather than shrinking the complete canvas onto one sheet.

Frequently Asked Questions

Can I pass a jQuery object directly to html2canvas?

No. Pass the DOM node extracted with [0] or .get(0).

Does this produce a searchable PDF?

Not usually. The workflow embeds a rendered image, so text is generally not native PDF text.

Will useCORS load every remote image?

No. The remote server must explicitly permit the request with CORS headers.

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

How should I export a very long page?

Capture sections separately or slice the canvas across multiple PDF pages rather than shrinking the complete canvas onto one sheet.

Quick 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.

Leave a Reply

Your email address will not be published. Required fields are marked *

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

Read next

Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.