October 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 ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
html2canvas

How to Make html2canvas and jsPDF Render SVG Images

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

Short answer: html2canvas does not take a pixel-perfect screenshot. It rebuilds the target DOM with the CSS and elements it knows how to render, then paints that representation to a canvas. SVGs can therefore lose styling, external assets, or fine detail. Start with the normal renderer, verify the SVG and its resources, enable CORS only when the remote server permits it, and test foreignObjectRendering: true in each browser you support. If the input is a standalone SVG rather than an HTML region, use jsPDF’s SVG-specific addSvgAsImage method instead of sending the SVG through html2canvas.

Choose the rendering path first

The correct fix depends on what you are putting in the PDF. There are two different workflows:

Input and goal Recommended path What to expect
An HTML element containing an inline or image-based SVG html2canvas(element, options), then add the resulting canvas image to jsPDF The result is a raster canvas representation. Unsupported CSS, filters, fonts, or DOM features may differ from the browser.
A standalone SVG that you want to place in a PDF Use jsPDF’s addSvgAsImage SVG module This bypasses the surrounding HTML capture. Confirm that your installed jsPDF build exposes the method.
An HTML region whose normal rendering misses important presentation details Test html2canvas with foreignObjectRendering: true The option is off by default and is browser-dependent; it is a testable alternative, not a universal SVG fix.

Capture an HTML region that contains an SVG

1. Make the SVG measurable and visible

Before changing libraries, inspect the actual element. Give the SVG a declared width and height, or a viewBox plus CSS dimensions. Make sure it is not display:none, outside the viewport because of an application state, or dependent on an image, font, stylesheet, mask, filter, or pattern that has not loaded. An SVG that looks correct in the live page can still be missing a referenced resource when the clone is rendered.

<div id="invoice-chart">
  <svg width="640" height="360" viewBox="0 0 640 360" role="img" aria-label="Revenue chart">
    <!-- paths, text, gradients, masks, and images -->
  </svg>
</div>

2. Use the default renderer first

Install the libraries in your application and wait for the SVG’s assets before capturing. The example below captures a DOM element, creates a PNG data URL, and inserts it into a PDF.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Wacom Intuos Small, Wired Graphic Drawing Tablet with Pen + Software
  • Wacom Intuos Small Graphics Drawing Tablet: Enjoy industry leading tablet performance in superior control and precision with Wacom's EMR, battery free technology that feels like pen on paper
  • Works With All Software: Wacom Intuos tablet can be used in any software program to explore new facets of digital creativity; draw, paint, edit photos/videos, create designs, and mark up documents
  • What the Professionals Use: Wacom's industry leading pen technology and pen to paper feeling makes it the preferred drawing tablet of professional graphic designers
  • Software and Training Included: Only Wacom gives you software with every purchase. Register your Intuos tablet and gain access to some of the best creative software and Wacom's online training
  • Wacom is the Global Leader in Drawing Tablet and Displays: For over 40 years in pen display and tablet market, you can trust that Wacom to help you bring your vision, ideas and creativity to life
import html2canvas from 'html2canvas';
import { jsPDF } from 'jspdf';

async function exportSvgRegion() {
  const element = document.querySelector('#invoice-chart');
  if (!element) throw new Error('Missing #invoice-chart');

  const canvas = await html2canvas(element, {
    backgroundColor: '#ffffff',
    imageTimeout: 15000,
    onclone: (clonedDocument) => {
      // Optional: make export-only changes in the cloned DOM.
      const clonedChart = clonedDocument.querySelector('#invoice-chart');
      if (clonedChart) clonedChart.style.background = '#ffffff';
    }
  });

  const pdf = new jsPDF({ unit: 'px', format: [canvas.width, canvas.height] });
  pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, canvas.width, canvas.height);
  pdf.save('chart.pdf');
}

html2canvas recreates a DOM representation; it is not a literal browser screenshot. Its documentation therefore cautions that every CSS property must be implemented manually and that full CSS support is not possible. SVG support in the source and support for foreign-object rendering are separate capability checks.

3. Try the alternate renderer deliberately

If the normal route loses SVG presentation that is important to your page, compare it with:

const canvas = await html2canvas(document.querySelector('#invoice-chart'), {
  foreignObjectRendering: true,
  backgroundColor: '#fff',
  imageTimeout: 15000
});

foreignObjectRendering defaults to false. It asks the browser to render more of the cloned HTML through an SVG foreignObject path, but support varies by browser and by the content being embedded. Test the exact SVG, CSS, fonts, and target browsers rather than assuming this option fixes every mismatch.

Handle cross-origin SVGs and referenced images

A canvas becomes tainted when it draws an image that the browser loaded from another origin without permission. A tainted canvas cannot be read with toDataURL() or toBlob(), which commonly appears as a security exception during PDF export. This applies to an external SVG itself and to images referenced inside that SVG.

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

Use CORS only when the server opts in

const canvas = await html2canvas(element, {
  useCORS: true,
  imageTimeout: 20000
});

useCORS: true makes the browser request eligible images with CORS, but it cannot grant permission. The image or SVG host must return an appropriate Access-Control-Allow-Origin header for your page. Check the Network panel for the actual response, including redirects; a redirect to a host without CORS headers can still fail.

Rank #2
Sale
XPPen Deco 01 V3 10x6 Drawing Tablet, 16K Battery-Free Stylus, 8 Keys
  • Word-first 16K Pressure Levels: The upgraded stylus features 16,384 levels of pressure sensitivity and supports up to 60 degrees of tilt, delivering smoother lines and shading for a natural drawing experience. With no battery or charging needed, it operates like a real pen, making it easy for beginners to create effortlessly. This functionality helps novice artists develop their skills and explore their creativity without the intimidation of complex tools
  • Designed for Beginners: This drawing pad desinged with 8 customizable shortcuts for both right and left-hand users, express keys create a highly ergonomic and convenient work platform
  • Perfectly Adapted for Android: The XPPen Deco 01 V3 art tablet supports connections with Android devices running version 10.0 and above. It is recommended to download the XPPen Tools Android application, which adapts to your smartphone's screen aspect ratio, ensuring accurate mapping. It also supports mapping on Android screens with different aspect ratios in portrait mode
  • Large Drawing Space, Bigger Bold Inspiration: This expansive drawing pad has10 x 6.25-inch helps you break through the limit between shortcut keys and drawing area
  • Easy Connectivity for Beginners: The Deco 01 V3 offers USB-C to USB-C connectivity, plus adapters for USB C. This ensures easy connection to various devices, allowing beginner artists to set up quickly and focus on their creativity without compatibility concerns. Whether using a laptop, tablet, or desktop, the Deco 01 V3 provides a seamless experience, making it an ideal choice for those just starting their digital art journey

Use a same-origin proxy when you control the backend

When the asset host cannot provide CORS headers, proxy the asset through your own origin, validate the destination to avoid an open proxy, preserve the correct content type, and then point the SVG or image at that same-origin URL. html2canvas also exposes a proxy configuration for this situation. Do not assume allowTaint: true makes export readable: it permits drawing but does not make a tainted canvas safe to inspect.

Inline critical SVG data when practical

Inlining the SVG markup and small images as data URLs removes a network-origin dependency. It does not solve unsupported CSS or an SVG that references a missing font, and large data URLs increase document size, so use it selectively.

Add a standalone SVG directly with jsPDF

If you do not need to capture surrounding HTML, direct insertion is a different and often cleaner route. The jsPDF SVG module documents addSvgAsImage. The exact availability depends on the jsPDF version and build you installed, so inspect the exported API before shipping.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import { jsPDF } from 'jspdf';
import 'svg2pdf.js'; // Include the SVG support required by your jsPDF setup.

async function svgToPdf(svgElement) {
  const pdf = new jsPDF({ unit: 'pt', format: 'a4' });
  const svgText = new XMLSerializer().serializeToString(svgElement);

  // x, y, width and height are PDF units (points in this example).
  pdf.addSvgAsImage(svgText, 40, 40, 515, 290);
  pdf.save('standalone.svg.pdf');
}

const svg = document.querySelector('#invoice-chart svg');
if (svg) await svgToPdf(svg);

Use this method when vector-like SVG insertion is more important than reproducing the complete HTML layout. Test gradients, masks, filters, external styles, embedded fonts, text, and image references in the SVG you actually ship. A direct SVG API does not automatically reproduce CSS applied by unrelated page stylesheets.

Control timing, fonts, and export-only styles

Wait for resources before capture

await document.fonts?.ready;
await Promise.all(
  [...document.images].map(img => img.complete
    ? Promise.resolve()
    : new Promise(resolve => {
        img.addEventListener('load', resolve, { once: true });
        img.addEventListener('error', resolve, { once: true });
      }))
);

This prevents a common race in which the live page is visible but the cloned document captures before a web font or image has finished. It cannot repair a failed request; inspect the console and Network panel as well.

Rank #3
Sale
HUION Inspiroy H1060P Graphics Drawing Tablet, 10 x 6.25 in, 12+16 Hot Keys
  • Working Area Configuration - HUION art tablet equips with a 10 x 6.25 inches working area, providing the user with the most comfortable size to work; the 10mm slim structure and minimalist design of appearance make the drawing tablet more attractive.
  • Tilt Function Battery-free Stylus: This computer graphics tablet come with a battery-free stylus PW100, no need to charge, allowing for constant uninterrupted drawing. ±60° tilt support enables imitation of lines input with diverse drawing gestures, with accuracy ensured.
  • Press Keys:12 programmable press keys plus 16 programmable soft keys, you can set shortcut keys on drawing tablet's driver based on your preferences, such as erase, zoom in/out, scroll up and down, and so on.
  • Compatibility: HUION graphics tablet supports Windows 7 or later/ macOS 10.12 or later/ Android 6.0 or later/ Linux (Ubuntu). A USB adapter is required to connect to a Mac computer. H1060P supports various mainstream design and drawing software, including PS, SAI, AI, CDR, etc. (Please note: The H1060P is compatible with Ubuntu, but it requires the use of the Xorg display server. Wayland is not supported.)
  • NOTE: You can easily connect your phone to the art tablet via the OTG connector; while iPhone and iPad are NOT at the moment. The cursor will not show up in the SAMSUNG Galaxy S series at present. If you are not sure whether the product is compatible with your Phone or any help, please contact us.

Use onclone instead of mutating the live page

In onclone, hide controls, force a white background, remove animations, or set print-specific dimensions in the cloned document. This keeps the user interface unchanged and makes the export deterministic.

Record failures

Set a finite imageTimeout and provide onError while diagnosing:

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.
const canvas = await html2canvas(element, {
  imageTimeout: 15000,
  onError: error => console.warn('html2canvas resource error', error)
});

A timeout or callback error points to a loading problem; a completed canvas with the wrong appearance points to a rendering or unsupported-feature problem.

Diagnose the common failure modes

Symptom Likely cause Fix to try
SVG area is blank The SVG is hidden, has no usable dimensions, or a referenced resource failed Check computed dimensions and visibility, wait for assets, and inspect Network and console errors.
toDataURL throws a security error A cross-origin SVG or image tainted the canvas Use useCORS: true only with server CORS headers, or proxy through your origin.
Colors, filters, masks, or layout differ html2canvas does not implement the relevant CSS or SVG feature Try foreignObjectRendering: true, simplify export CSS, or use direct addSvgAsImage for a standalone SVG.
Text uses a fallback font Capture ran before the web font loaded or the font is unavailable to the browser Await document.fonts.ready, confirm the font response, and capture again.
addSvgAsImage is undefined The SVG module is absent from the installed jsPDF build or the API differs by version Check the installed package and build, include the required SVG module, and verify the method before calling it.
Works in Chrome but not Safari or Firefox Browser support for foreignObject, SVG features, or canvas APIs differs Test every supported browser with the production SVG; choose a simpler SVG or a server-side route where identical output is required.
Node.js throws browser API errors html2canvas depends on browser APIs and is not a Node.js renderer Run it in a real browser, or use a browser-based capture service.

Choose raster capture or direct SVG insertion

  • Use html2canvas plus jsPDF when the PDF must match an HTML card, dashboard, or invoice region that includes more than the SVG. Accept that the canvas stage rasterizes the result and that unsupported CSS may change.
  • Use foreignObjectRendering when the default renderer misses presentation that the browser can render, and only after testing your target browsers.
  • Use addSvgAsImage when the input is the SVG itself and you want to avoid capturing unrelated HTML. Verify the module and test the SVG’s actual dependencies.

Performance, reliability, and PDF quality

Large full-page captures consume memory because html2canvas builds a bitmap whose cost grows with pixel dimensions and device scale. Capture the smallest element that answers the user’s need, avoid unnecessarily high scale values, and release temporary canvases after adding them to the PDF. For long pages, capture deliberate sections and place them on separate PDF pages rather than creating one enormous bitmap.

PNG preserves sharp text and transparent details but can produce larger files. JPEG is smaller for photographic content but introduces compression artifacts and does not preserve transparency. The PDF page size and image dimensions should be chosen together; stretching a small canvas to fill a page cannot restore lost detail.

Rank #4
Sale
XPPen Artist 13.3 Pro V2 Drawing Tablet with Screen, 16K, Full-Laminated
  • PLEASE NOTE:XPPen Artist13.3 Pro drawing tablet Need to connect with computer,you need to use it with your computer or laptop, the 3 in 1 cable is included
  • Drawing Tablet with Screen: Tilt Function- XPPen Artist 13.3 Pro supports up to 60 degrees of tilt function, so now you don't need to adjust the brush direction in the software again and again. Simply tilt to add shading to your creation and enjoy smoother and more natural transitions between lines and strokes
  • Graphics Tablets: High Color Gamut- The 13.3 inch fully-laminated FHD Display pairs a superb color accuracy of 88% NTSC (Adobe RGB≧91%,sRGB≧123%) with a 178-degree viewing angle and delivers rich colors, vivid images, and dazzling details in a wider view. Your creative world is now as powerful as it is colorful
  • Drawing Pad: One is enough- The sleek Red Dial on the display is expertly designed with creators in mind, its strategic placement allows for natural drawing postures. With just one wheel, you can effortlessly zoom in and out, adjust brush sizes, and flip the canvas—all tailored to suit the habits of everyday artists. The 8 customizable shortcut keys allow you to personalize your setup, streamlining your workflow and enhancing creative efficiency
  • Universal Compatibility & Software Support:supports Windows 7 (or later), Mac OS X 10.10 (or later), Chrome OS 88 (or later), and Linux systems. Fully compatible with major creative software including Photoshop, Illustrator, SAI, and Blender 3D. Register your device to access additional programs like ArtRage 5 and openCanvas for expanded creative possibilities.

For production reliability, test cold loads as well as cached loads, slow networks, failed image requests, consent states, dark mode, web fonts, and each browser you support. Keep a small fixture page containing the SVG features your application relies on so library upgrades can be compared before deployment.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
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 you need a clean website screenshot rather than a browser-side SVG debugging workflow, ScreenshotNeo provides a GET-based screenshot API and an MCP server for AI agents. It accepts consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each step can be disabled. Bot checks, CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and the response identifies the page verdict and billing status in X-Page-Verdict and X-Billed headers.

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 capture options such as full-page lazy-image loading, CSS-selector element capture, dark mode, device presets, custom viewport and retina scale, PDF output, custom CSS and JavaScript, clicks, waits, request blocking, headers, cookies, user agents, timezone, geolocation, transparent backgrounds, resizing, TTL caching, signed image links, asynchronous webhooks, bulk capture, usage reporting, and the OpenAPI specification. Its parameter names are compatible with those used by many screenshot APIs, which can simplify migration.

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 failed: ${res.status}`);

An MCP server supplies take_screenshot, get_page_info, and capture_pdf tools to 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, and every feature is available on every plan. Create a free ScreenshotNeo account.

FAQ

Does html2canvas preserve SVG as vector data?

No. When you capture an HTML region, html2canvas paints a canvas representation; adding that canvas to jsPDF is an image workflow. Use the SVG-specific jsPDF method when direct SVG insertion is the goal.

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

Will foreignObjectRendering always fix an SVG?

No. It is disabled by default and depends on browser support and the exact SVG, CSS, and external resources. Treat it as a controlled comparison.

Best Value
16 Inch Large LCD Writing Tablet for Kids, Colorful Reusable Electronic Doodle Board with Stylus, Educational Drawing Pad for Math Practice & Learning, Travel Essential Toys for Boys Girls (Pink)
  • 【16-INCH JUMBO SCREEN & EYE PROTECTION】Upgrade your child's creativity with our extra-large 16" LCD writing tablet. Providing 50% more drawing space than standard boards, it uses advanced pressure-sensitive technology. No glare, no blue light, and no radiation—completely safe for toddlers to doodle for hours without eye strain.
  • 【ONE-TAP CLEAR & ANTI-ERASE LOCK】Is it easy to clean? Absolutely! Simply press the erase button to instantly clear the screen like magic, leaving zero mess, ink, or dust. The built-in lock switch on the back protects your child's masterpiece from accidental deletion, making it perfect for saving important notes or drawings.
  • 【STYLUS INCLUDED & PERFECT FOR MATH PRACTICE】Comes with a dedicated stylus that glides smoothly for colorful lines. It's not just a drawing pad; it's an interactive educational tool! Ideal for preschool learning, spelling, handwriting practice, and solving math problems without wasting hundreds of sheets of paper.
  • 【MESS-FREE TRAVEL ESSENTIAL】Made from durable, drop-resistant ABS plastic, this lightweight electronic doodle board is the ultimate travel activity for kids. Keep toddlers quietly entertained during long car rides, airplane trips, church, or at restaurants, without the mess of crayons or markers.
  • 【IDEAL GIFT FOR BOYS & GIRLS】Packaged beautifully, this reusable magic slate is a fantastic gift choice for birthdays, Christmas, Back-to-School, or Thanksgiving. Suitable for 3, 4, 5, 6, 7, 8-year-old toddlers, kids, and even adults for daily office memos.

Can allowTaint: true solve cross-origin export errors?

No. It does not make a tainted canvas readable. Configure CORS correctly or use a same-origin proxy.

Can I run html2canvas in a Node.js script without a browser?

Not directly. html2canvas depends on browser APIs; use a real browser environment or a browser-based screenshot service.

Frequently Asked Questions

Should I use PNG or JPEG for the PDF image?

PNG is the safer default for charts, text, transparency, and sharp edges. JPEG can reduce size for photographic content but loses transparency and introduces compression.

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

Why does the SVG look correct on screen but not in the PDF?

The live browser and html2canvas’s reconstructed DOM do not use identical rendering paths. Unsupported CSS or SVG features, missing fonts, failed external resources, and cross-origin restrictions are the usual differences.

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
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

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.