October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober 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 Render SVG Images with html2canvas and jsPDF in React

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.

To export an SVG together with its surrounding React content, render the containing DOM element with html2canvas, pass the resulting canvas to jsPDF.addImage(), and save the PDF. This is a raster-image workflow: the PDF contains pixels, not editable vector SVG. Explicit dimensions, a suitable capture scale, and valid CORS access for external images are the main factors that determine whether the result looks right.

Choose the right export path

Use html2canvas when the export should include an SVG alongside HTML, text, and other DOM content. It reconstructs a DOM region into a canvas; it does not take a native pixel screenshot of the browser. Its rendering can differ from the page, because CSS support is implemented property by property and browser security rules still apply. The project cautions that its output may not exactly match the page as displayed: html2canvas documentation.

If you only have SVG markup as a string and do not need the surrounding DOM, jsPDF also provides addSvgAsImage. That route parses SVG through canvg and a canvas, then places the result in the PDF as an image; it does not preserve vector semantics either. See the jsPDF SVG module documentation.

  • DOM plus SVG: use html2canvas(element), then pdf.addImage(...).
  • SVG string only: consider addSvgAsImage, while checking its canvg and canvas-element dependencies and browser support.
  • Need editable vector content: neither of these image-insertion paths produces a vector SVG object in the PDF. Choose a vector-oriented PDF workflow instead.

Install the libraries and prepare the React content

Install html2canvas and jspdf in the React project using its package manager. The example below uses TypeScript and the documented package imports. No specific package version is assumed; check the versions installed in your application if an API differs.

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

Put the content to export inside a stable container. Give the container and SVG explicit dimensions, and specify an SVG viewBox that matches its intended coordinate system. This avoids relying on surrounding layout or intrinsic sizing to determine the capture dimensions.

import { useRef } from 'react';
import html2canvas from 'html2canvas';
import { jsPDF } from 'jspdf';

export function SvgPdfButton() {
  const ref = useRef<HTMLDivElement>(null);

  async function exportPdf() {
    if (!ref.current) return;
    const element = ref.current;

    const canvas = await html2canvas(element, {
      scale: Math.min(window.devicePixelRatio || 1, 3),
      useCORS: true,
      backgroundColor: '#ffffff',
      windowWidth: element.scrollWidth,
      windowHeight: element.scrollHeight,
    });

    const pdf = new jsPDF({ unit: 'mm', format: 'a4', orientation: 'p' });
    const pageWidth = pdf.internal.pageSize.getWidth();
    const imageHeight = (canvas.height * pageWidth) / canvas.width;
    pdf.addImage(canvas, 'PNG', 0, 0, pageWidth, imageHeight);
    pdf.save('svg-export.pdf');
  }

  return (
    <>
      <div ref={ref} style={{ width: 800, background: '#fff' }}>
        <svg
          width="800"
          height="450"
          viewBox="0 0 800 450"
          role="img"
          aria-label="Exportable SVG example"
        >
          <rect width="800" height="450" fill="#fff" />
          <text x="24" y="48" fontSize="28">Exportable SVG</text>
        </svg>
      </div>
      <button onClick={exportPdf}>Download PDF</button>
    </>
  );
}

The central pipeline is html2canvas(element) → canvas → pdf.addImage(). The html2canvas examples show canvas rendering, and the jsPDF addImage documentation describes inserting canvas/image data into a PDF.

Understand the capture and PDF settings

Dimensions and page fit

The example captures the referenced element, not the entire browser page. scrollWidth and scrollHeight are passed as the capture window dimensions so content that extends beyond the visible viewport has a chance to be included. Give the actual target a deliberate width and ensure that its children are laid out at that width; setting the capture window alone does not repair a clipped or incorrectly sized component.

The PDF page width is measured in millimetres, while the source canvas has pixel dimensions. The code derives image height from the canvas aspect ratio, so the image is scaled proportionally to the A4 page width. This preserves proportions but may make a tall capture extend beyond one page. A single addImage call does not automatically paginate a long canvas. For content that must span pages, design a page-aware export: capture or compose page-sized sections and add each section to a separate PDF page. Do not squeeze a long chart into one page if labels become unreadable.

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

Scale, sharpness, and memory

scale controls the resolution of the rendered canvas relative to the CSS-sized content. A larger scale can make fine SVG details and text sharper when printed or zoomed, but it increases canvas dimensions and memory use. The example caps device pixel ratio at 3 as a starting point, not a universally ideal value. Test representative content and target browsers, then choose the smallest scale that meets the output-quality requirement.

Canvas dimension and area limits vary among browsers and devices, and an oversized canvas may fail or render incompletely. html2canvas documents this variability in its FAQ. A bigger scale is not a safe fix for every blurry result: check SVG sizing and PDF fit as well.

Background and output type

backgroundColor: '#ffffff' gives the capture a white background, useful when transparent areas should print on white. Set it to another desired color if appropriate. The example passes the canvas to jsPDF as PNG, which is suitable for graphics with sharp edges and transparency needs, and saves it as svg-export.pdf. Despite the SVG source, the inserted result is raster image data.

Wait for React content to settle

Run the export after the target SVG and its data have mounted. If application state, chart data, or layout changes immediately before the button handler runs, wait until React has committed the updated content before calling html2canvas. If the SVG uses web fonts, wait for them to load as well; otherwise the capture may use a fallback font. These are practical timing precautions, not a guarantee that every asynchronous asset is ready automatically.

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

Handle external images and CORS

An SVG can reference remote images, and the captured DOM can contain external images too. For the resulting canvas to be readable as a data URL or used as an image, those resources must be same-origin, served with suitable CORS headers, or fetched through a proxy. If a remote server does not allow cross-origin access, the browser can taint the canvas and block reading it.

The sample sets useCORS: true. That asks html2canvas to use CORS for eligible image requests; it does not override the remote server’s policy. The server must send a permissive Access-Control-Allow-Origin header for the requesting origin. If it does not, remove the option or arrange a proxy that fetches the asset and serves it under a policy you control. Consult the html2canvas CORS and canvas FAQ before treating the flag as a fix.

Do not attempt to bypass a site’s access controls. If you own the asset, configure the server or host the image in a same-origin location. If you do not control it, ask whether the site permits the intended use and use an authorized source.

Use jsPDF directly for an SVG string

When the input is already SVG XML rather than a React DOM region, jsPDF’s SVG module exposes addSvgAsImage(svg, x, y, width, height, ...). It parses the XML using canvg, renders through canvas, and adds the rendered image. That can avoid capturing unrelated HTML, but it remains a rasterization path and has dependencies and browser support to verify for your bundle.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import { jsPDF } from 'jspdf';

const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="800" height="450" viewBox="0 0 800 450">
  <rect width="800" height="450" fill="#fff" />
  <text x="24" y="48" font-size="28">SVG string</text>
</svg>`;

const pdf = new jsPDF({ unit: 'mm', format: 'a4', orientation: 'p' });
pdf.addSvgAsImage(svg, 0, 0, 210, 118.125);
pdf.save('svg-string.pdf');

Use dimensions that preserve the SVG’s aspect ratio and fit the intended page area. The SVG module’s documented API and dependencies are described at jsPDF’s SVG module reference.

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

Troubleshoot blurry, missing, or clipped exports

Symptom Likely cause What to check or change
SVG looks blurry in the PDF Canvas scale is too low for the viewing or print size, or the image is enlarged to fit the PDF. Increase scale moderately, preserve the SVG viewBox and aspect ratio, and confirm the PDF placement size. Keep canvas limits in mind; browser capacity varies. html2canvas FAQ.
Remote image inside or beside the SVG is missing It is cross-origin without permission, or it fails to load before capture. Verify same-origin access or a server CORS response; use an authorized proxy if needed. useCORS: true cannot grant permission the server has not supplied. html2canvas FAQ.
Shadows, filters, or other styling differ The renderer does not implement every CSS property or reproduce the browser’s native pixels. Check html2canvas’s CSS coverage, simplify the effect, or express the visual with SVG-native primitives where suitable. html2canvas documentation and FAQ.
Capture is blank or cut off The target dimensions, capture window, placement, or browser canvas limits are wrong. Inspect the target’s actual width and height, ensure the SVG has explicit dimensions, pass suitable windowWidth/windowHeight, and reduce scale or content size if limits are reached. html2canvas configuration and FAQ.
Latest chart data or text does not appear Capture started before React updated the DOM, or fonts/assets were not ready. Trigger export after the updated UI has rendered and required fonts or images have loaded; inspect the referenced element immediately before capture.
Canvas cannot be exported or read A cross-origin resource tainted the canvas. Locate the remote asset and fix its origin/CORS setup or proxy it with authorization. Do not expect toDataURL() to work on a tainted canvas. html2canvas FAQ.

Performance, reliability, and output trade-offs

  • Keep capture areas purposeful: capture only the container the user needs, rather than a full page, when possible. Larger canvases consume more memory and are more exposed to browser limits.
  • Test at the final page size: a PDF can look sharp on-screen yet become small when a wide layout is fitted to portrait A4. Choose portrait or landscape and a page layout appropriate to the content.
  • Expect visual differences: DOM reconstruction is not a pixel-perfect browser screenshot. If a particular CSS property matters, validate it in the actual export path and simplify or replace unsupported styling.
  • Plan for multiple pages deliberately: long content needs a page-break strategy. A single oversized image may clip, exceed canvas limits, or shrink details when fitted.
  • Check assets and timing: images, fonts, and asynchronously updated charts need to be available at capture time. Cross-origin resources have both loading and canvas-read restrictions.

Or skip the browser setup

If your goal is a screenshot of a published webpage rather than a PDF export of a particular React component, ScreenshotNeo provides a website screenshot API. It is a different workflow from capturing your in-memory React state: send a URL and receive an image or PDF. Its API documentation is at ScreenshotNeo docs.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

ScreenshotNeo accepts cookie or consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each of those steps can be turned off. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers report the page verdict and billing status. Its MCP server gives AI agents tools named take_screenshot, get_page_info, and capture_pdf. The free plan includes 1,000 shots a month with no card; paid plans start at $5 for 3,000 shots. Every feature is available on every plan.

Sign up for 1,000 free screenshots a month with no card.

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

FAQ

Does the resulting PDF contain editable SVG paths?

No. In the methods above, SVG is rendered to a canvas and inserted as image content, so it is not retained as editable vector paths.

Frequently Asked Questions

Does the resulting PDF contain editable SVG paths?

No. In these methods, SVG is rendered to a canvas and inserted as image content, so it is not retained as editable vector paths.

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
Windows Errors? Fix Them Before They SpreadFree repair scan

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.