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 DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
Angular 7

How to Import html2canvas in Angular 7

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

Install the html2canvas package you intend to use, then make the import match that exact package name. For the legacy package, run npm install html2canvas and write import html2canvas from 'html2canvas';. The current html2canvas documentation also uses the scoped package, @html2canvas/html2canvas; install that package before importing it by that name. The sources document both forms, but do not establish an Angular 7-specific compatibility matrix, so verify the selected package against your project’s TypeScript, browser, and dependency versions.

Install the package that matches your import

Run the install command from the Angular workspace root—the directory containing package.json. Do not install one package name and import another.

Legacy package name

npm install html2canvas

Then import the default export in the component or service that needs it:

import html2canvas from 'html2canvas';

Scoped package name

The current html2canvas documentation uses the scoped package. If you choose that form, install and import it consistently:

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.
npm install @html2canvas/html2canvas
import html2canvas from '@html2canvas/html2canvas';

These are alternative package forms, not interchangeable import spellings for one installation. Check package.json and the lockfile if you are unsure which one the project already uses. The documentation identifies both import patterns but does not publish a tested Angular 7 compatibility matrix; a documented import is not, by itself, proof that a particular package release fits every Angular 7 project.

Capture an Angular element after the view renders

html2canvas needs an actual browser DOM element. In Angular, obtain the element with @ViewChild and call the library in a browser-side method after view initialization—for example, in response to a button click. This is a practical lifecycle pattern, not a hook specifically prescribed by html2canvas.

import { AfterViewInit, Component, ElementRef, ViewChild } from '@angular/core';
import html2canvas from 'html2canvas';

@Component({
  selector: 'app-capture',
  template: `
    <section #captureArea>
      <h2>Capture me</h2>
      <p>This content is rendered by Angular.</p>
    </section>
    <button type="button" (click)="capture()">Save image</button>
  `
})
export class CaptureComponent implements AfterViewInit {
  @ViewChild('captureArea') captureArea: ElementRef;

  ngAfterViewInit(): void {
    // The view and its captureArea element are now available.
  }

  async capture(): Promise<void> {
    const element = this.captureArea.nativeElement;
    const canvas = await html2canvas(element);
    const dataUrl = canvas.toDataURL('image/png');

    const link = document.createElement('a');
    link.href = dataUrl;
    link.download = 'capture.png';
    link.click();
  }
}

The call returns a Promise that resolves to a canvas. Await it before using toDataURL; calling canvas methods before the Promise resolves will not work. This example uses the legacy import. If the scoped package is installed instead, change only the import string to '@html2canvas/html2canvas'. If your project enables stricter TypeScript checks, declare and initialize the ViewChild property in a way compatible with its TypeScript version and compiler settings.

Choose the capture boundary deliberately

Pass the element you want represented, not an Angular component class or template reference string. The template reference #captureArea lets Angular expose the rendered element through ViewChild; nativeElement is the DOM node passed to html2canvas. Keep the capture action out of the constructor: at construction time, the view has not been initialized.

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

Use a browser-only call

html2canvas depends heavily on browser APIs and is not suitable for Node.js execution. If the Angular application is rendered on a server, do not invoke it during server rendering. Run the capture only in the browser, such as from a user-triggered method after the view is available. A DOM element cannot be captured on the server merely by importing the package there.

Choose between the scoped and legacy forms carefully

For an existing Angular 7 application, first inspect the dependency already present rather than changing package forms just to match a newer example. Consider these checks before installation or migration:

  • Package name: determine whether the project already depends on html2canvas or @html2canvas/html2canvas.
  • Import path: make the TypeScript import exactly match the installed package.
  • Lockfile: keep package manager changes reflected in the lockfile, and use the same package manager convention as the project.
  • Project versions: check the package’s installed release and your Angular, TypeScript, and browser requirements. The available documentation does not confirm a universal Angular 7 compatibility combination.
  • Existing dependency tree: check whether the project already brings in one form transitively; avoid adding a second package form without a reason.

If you change package forms, update the dependency and import together, then build and test the capture in the browsers your application supports. A successful TypeScript import only confirms module resolution; it does not establish that every CSS feature or remote asset will render as expected.

Understand image restrictions and visual differences

Cross-origin images can taint the canvas

html2canvas cannot override browser content-security rules. An image hosted on another origin may be unavailable to the capture or taint the canvas, which can prevent exporting it as a data URL. The documented workaround is to use a proxy that accepts a ?url= parameter and returns the image as a base64 data URI, then provide that proxy through html2canvas’s proxy option. Configure and secure your own proxy; do not treat the option as a way to bypass an origin’s access policy.

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

The output is reconstructed, not a native screenshot

html2canvas rebuilds an image from the DOM and styles rather than asking the browser for a native screenshot. Unsupported or differently interpreted CSS can therefore make the result differ from the page as displayed. If exact visual fidelity matters, check the specific elements and styles your application uses rather than assuming that every browser-rendered effect is captured pixel for pixel.

Legacy browser support may need a Promise polyfill

The legacy package documentation notes that older browsers need a Promise polyfill. If Angular 7 must support older browsers, check the project’s browser targets and existing polyfills before relying on the Promise returned by html2canvas.

Troubleshoot common Angular 7 errors

Symptom Likely cause What to check or change
Cannot find module 'html2canvas' The package is not installed in this workspace, or the import does not match the installed package name. From the workspace root, inspect package.json. Install the intended package and use its matching import path; then restart the development build if needed.
Module-resolution error for @html2canvas/html2canvas The scoped package is being imported while only the legacy package is installed, or vice versa. Align the dependency and import. Do not use the scoped import unless that package is present.
Cannot read properties of undefined or no target element The capture ran before Angular populated the view, or the template reference does not match the ViewChild query. Confirm that the element has the expected #captureArea reference and call capture after view initialization, typically from a button click.
Capture fails during server rendering The code is invoking a browser-dependent library in a Node.js rendering context. Keep the call browser-only. Server-side code has no rendered browser DOM element for html2canvas to capture.
Remote image missing or canvas export fails A cross-origin asset is blocked or has tainted the canvas. Check the image origin and browser access rules. If appropriate, use a proxy that returns a base64 data URI and configure the html2canvas proxy option.
Image looks different from the page The library reconstructs DOM and styles, and the output may not match native browser rendering. Check the CSS and assets used by the affected element. Do not assume unsupported effects can be made pixel-perfect by changing the import.
Promise-related failure in an older browser The browser may lack native Promise support. Review the Angular application’s supported browser set and add a Promise polyfill if required for those browsers.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance and reliability considerations

Capture only the part of the page the user needs; a smaller DOM subtree generally gives the library less content to process than the entire application view. Make sure images and other content in that subtree have loaded before starting the capture, and handle the returned Promise so your UI can show completion or an error rather than assuming the image is immediately available.

For a long-running capture or a large target, avoid triggering multiple overlapping captures from repeated clicks. Disable or otherwise guard the action while one is in progress, and release any temporary object URLs if you choose a Blob-based download approach. Test with the real page content, including remote images and the target browsers: a successful capture of a simple local element does not demonstrate that all application pages or assets will succeed.

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

The browser-based approach is useful when the target is an element in the currently rendered Angular application. It is not a general server-side screenshot mechanism: the target is a DOM node in the browser, not an arbitrary URL processed by Node.js.

Or skip the browser setup

If you need a screenshot of a publicly reachable page rather than a specific element in the user’s current Angular DOM, ScreenshotNeo offers a URL-based screenshot API. It does not replace html2canvas for capturing an unsaved or local DOM element in the browser. For a page you can address by URL, a cURL request is:

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 request options. Equivalent Python and Node.js examples are:

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

Replace the example target URL with the public page you want to capture and provide an API key. ScreenshotNeo accepts consent banners as a visitor and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; those steps can be turned off. Bot checks, blank pages, failed loads, timeouts, and cache hits are not billed, and response headers indicate the page verdict and billing status. Its 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.

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

Sign up for ScreenshotNeo’s free plan: 1,000 screenshots a month, no card required.

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 *

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.

Read next

Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver 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.