kandi background
Explore Kits

html2canvas | Screenshots with JavaScript | Image Editing library

 by   niklasvh TypeScript Version: v1.4.0 License: MIT

 by   niklasvh TypeScript Version: v1.4.0 License: MIT

Download this library from

kandi X-RAY | html2canvas Summary

html2canvas is a TypeScript library typically used in Media, Image Editing, jQuery applications. html2canvas has no bugs, it has no vulnerabilities, it has a Permissive License and it has medium support. You can download it from GitHub.
[Homepage](https://html2canvas.hertzen.com) | [Downloads](https://github.com/niklasvh/html2canvas/releases) | [Questions](https://github.com/niklasvh/html2canvas/discussions/categories/q-a). [![Gitter](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/niklasvh/html2canvas?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) ![CI](https://github.com/niklasvh/html2canvas/workflows/CI/badge.svg?branch=master) [![NPM Downloads](https://img.shields.io/npm/dm/html2canvas.svg)](https://www.npmjs.org/package/html2canvas) [![NPM Version](https://img.shields.io/npm/v/html2canvas.svg)](https://www.npmjs.org/package/html2canvas).
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • html2canvas has a medium active ecosystem.
  • It has 25335 star(s) with 4251 fork(s). There are 511 watchers for this library.
  • There were 2 major release(s) in the last 12 months.
  • There are 689 open issues and 1618 have been closed. On average issues are closed in 780 days. There are 27 open pull requests and 0 closed requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of html2canvas is v1.4.0
html2canvas Support
Best in #Image Editing
Average in #Image Editing
html2canvas Support
Best in #Image Editing
Average in #Image Editing

quality kandi Quality

  • html2canvas has 0 bugs and 0 code smells.
html2canvas Quality
Best in #Image Editing
Average in #Image Editing
html2canvas Quality
Best in #Image Editing
Average in #Image Editing

securitySecurity

  • html2canvas has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • html2canvas code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
html2canvas Security
Best in #Image Editing
Average in #Image Editing
html2canvas Security
Best in #Image Editing
Average in #Image Editing

license License

  • html2canvas is licensed under the MIT License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
html2canvas License
Best in #Image Editing
Average in #Image Editing
html2canvas License
Best in #Image Editing
Average in #Image Editing

buildReuse

  • html2canvas releases are available to install and integrate.
  • Installation instructions are not available. Examples and code snippets are available.
  • It has 5575 lines of code, 0 functions and 267 files.
  • It has low code complexity. Code complexity directly impacts maintainability of the code.
html2canvas Reuse
Best in #Image Editing
Average in #Image Editing
html2canvas Reuse
Best in #Image Editing
Average in #Image Editing
Top functions reviewed by kandi - BETA

kandi's functional review helps you automatically verify the functionalities of the libraries and avoid rework.
Currently covering the most popular Java, JavaScript and Python libraries. See a Sample Here

Get all kandi verified functions for this library.

Get all kandi verified functions for this library.

html2canvas Key Features

Screenshots with JavaScript

html2canvas Examples and Code Snippets

See all related Code Snippets

default

copy iconCopydownload iconDownload
The script allows you to take "screenshots" of webpages or parts of it, directly on the users browser. The screenshot is based on the DOM and as such may not be 100% accurate to the real representation as it does not make an actual screenshot, but builds the screenshot based on the information available on the page.

Usage

copy iconCopydownload iconDownload
html2canvas(document.body).then(function(canvas) {
    document.body.appendChild(canvas);
});

Building

copy iconCopydownload iconDownload
$ git clone git://github.com/niklasvh/html2canvas.git

How to send pdf generated from screen shot in JavaScript

copy iconCopydownload iconDownload
async function takeSS() {
  const canvas = await html2canvas(document.body);
  const data = canvas.toDataURL();
  const docDefinition = {
    content: [{
      image: data,
      width: 900,
    }]
  };
  
  const pdfDocGenerator = pdfMake.createPdf(docDefinition);
  const blob = await new Promise(resolve => {
    pdfDocGenerator.getBlob(resolve);
  });
  
  const formData = new FormData();
  formData.append('pdf', blob, 'test.pdf');
  
  try {
    const response = await fetch('myapi-url', {
      method: 'POST',
      body: formData
    });
    
    if (!response.ok) {
      throw new Error('POST request failed');
    }

    const message = await response.text();
    console.log(message);
  } catch (error) {
    console.error(error);
  }
}

Wait for a promise to be resolved before continuing with function

copy iconCopydownload iconDownload
const { body } = document;

async function takeScreenshot() {
  const screenshot = await html2canvas(body);
  return screenshot.toDataURL();
}

async function main() {
  const canvas = await takeScreenshot();
  body.appendChild(canvas);
}

main();

html making div to image

copy iconCopydownload iconDownload
<html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>
</head>

<body>
    <div id="html-content-holder" style="background-color: #F0F0F1; color: #00cc65; width: 500px;
        padding-left: 25px; padding-top: 10px;">
        <strong>Codepedia.info</strong>
        <hr/>
        <h3 style="color: #3e4b51;">
            Html to canvas, and canvas to proper image
        </h3>
        <p style="color: #3e4b51;">
            <b>Codepedia.info</b> is a programming blog. Tutorials focused on Programming ASP.Net, C#, jQuery, AngularJs, Gridview, MVC, Ajax, Javascript, XML, MS SQL-Server, NodeJs, Web Design, Software</p>
        <p style="color: #3e4b51;">
            <b>html2canvas</b> script allows you to take "screenshots" of webpages or parts of it, directly on the users browser. The screenshot is based on the DOM and as such may not be 100% accurate to the real representation.
        </p>
    </div>
    <input download="download.png" id="btn-Preview-Image" type="button" value="Download" />
    <br/>


    <script>
        $(document).ready(function() {


            var element = $("#html-content-holder"); // global variable
            var getCanvas; // global variable
            var newData;

            $("#btn-Preview-Image").on('click', function() {
                html2canvas(element, {
                    onrendered: function(canvas) {
                        getCanvas = canvas;
                        var imgageData = getCanvas.toDataURL("image/png");
                        var a = document.createElement("a");
                        a.href = imgageData; //Image Base64 Goes here
                        a.download = "Image.png"; //File name Here
                        a.click(); //Downloaded file
                    }
                });
            });


        });
    </script>
</body>

</html>

Created image with use-react-screenshot is incorrectly rendered

copy iconCopydownload iconDownload
import * as htmlToImage from "html-to-image";
...
  const takeScreenShot = async (node) => {
    const dataURI = await htmlToImage.toJpeg(node);
    return dataURI;
  };

  const download = (image, { name = "img", extension = "jpg" } = {}) => {
    const a = document.createElement("a");
    a.href = image;
    a.download = createFileName(extension, name);
    a.click();
  };

  const downloadScreenshot = () => takeScreenShot(ref.current).then(download);
...
npm add html2canvas --legacy-peer-deps

Use html2canvas to capture a page at a fixed width no matter the screen size

copy iconCopydownload iconDownload
// capture my on screen html
let html = document.documentElement.outerHTML;
// create the iframe
// there is css to push it off screen (ie. left: -1024px;)
let iframe = document.createElement("iframe");
iframe.style.width = "1024px";
iframe.style.height = "100%";
document.body.appendChild(iframe);
// add html to iframe
iframe.srcdoc = html;

// wait for iframe to load
iframe.addEventListener("load", () => {
   // use html2canvas to save the webpage
   html2canvas(iframe.contentWindow.document.body).then(function(canvas) {
     let filename = "image.jpg";
     let link = document.createElement("a");
     link.download = filename.toLowerCase();
     canvas.toBlob( function(blob) {
            link.href = URL.createObjectURL(blob);
            link.click();
        }, 'image/jpg');
     });
});

How to download the full to-do (vue.js)list using JsPdf?

copy iconCopydownload iconDownload
download() {

    var dom = document.getElementById('tabalo'); //'tabalo' is an Id in my to-do list table
    html2canvas(dom).then(function(canvas) {
        var img = canvas.toDataURL("image/png");
        var doc = new jsPDF();
        doc.addImage(img, 'JPEG', 20, 20);
        doc.save('mydestination.pdf');
    });
var dom = document.getElementById('tabalo'); //'tabalo' is an Id in my to-do list table
html2canvas(dom).then(function(canvas) {
    var img = canvas.toDataURL("image/png");
    var doc = new jsPDF();
    doc.addImage(img, 'JPEG', 20, 20);
    doc.save('mydestination.pdf');
});
this is working but when we have an image it not display the image 

Live preview with React, Html2Canvas and JsPDF

copy iconCopydownload iconDownload
import React from "react";
import { PDFObject } from "react-pdfobject";
import { jsPDF } from "jspdf";

const PreView = () => {
  const doc = new jsPDF();
  doc.text("Hello world!", 10, 10);
  const url = doc.output("bloburi");

  return <PDFObject url={url} />;
};

export default PreView;

html2canvas bigger size of download image

copy iconCopydownload iconDownload
html2canvas(document.getElementById("imagewrap"), {
  onrendered: function(canvas) {
    var  _canvas = document.createElement("canvas");
    _canvas.setAttribute('width', 1080);
    _canvas.setAttribute('height', 1920);
    var ctx = _canvas.getContext('2d');
    ctx.drawImage(canvas, 0, 0, canvas.width, canvas.height, 0, 0, 1080, 1920);
    var dataURL = _canvas.toDataURL();  
    document.getElementById("canvasWrapper").appendChild(_canvas);
    var image = _canvas.toDataURL("image/png");
    document.getElementById("downloadLink").href = image;
  },
  useCORS: true
});

NG_PERSISTENT_BUILD_CACHE=1 ng serve not working

copy iconCopydownload iconDownload
NG_PERSISTENT_BUILD_CACHE=1 ng serve
// 1st command to set the environment variable
set NG_PERSISTENT_BUILD_CACHE=1

// 2nd command
ng serve
set NG_PERSISTENT_BUILD_CACHE=1&&ng serve
"scripts": {
  "start": "set NG_PERSISTENT_BUILD_CACHE=1&&ng serve",
  ...
}
NG_PERSISTENT_BUILD_CACHE=1 ng serve
// 1st command to set the environment variable
set NG_PERSISTENT_BUILD_CACHE=1

// 2nd command
ng serve
set NG_PERSISTENT_BUILD_CACHE=1&&ng serve
"scripts": {
  "start": "set NG_PERSISTENT_BUILD_CACHE=1&&ng serve",
  ...
}
NG_PERSISTENT_BUILD_CACHE=1 ng serve
// 1st command to set the environment variable
set NG_PERSISTENT_BUILD_CACHE=1

// 2nd command
ng serve
set NG_PERSISTENT_BUILD_CACHE=1&&ng serve
"scripts": {
  "start": "set NG_PERSISTENT_BUILD_CACHE=1&&ng serve",
  ...
}
NG_PERSISTENT_BUILD_CACHE=1 ng serve
// 1st command to set the environment variable
set NG_PERSISTENT_BUILD_CACHE=1

// 2nd command
ng serve
set NG_PERSISTENT_BUILD_CACHE=1&&ng serve
"scripts": {
  "start": "set NG_PERSISTENT_BUILD_CACHE=1&&ng serve",
  ...
}

How to resolve the error: Document not attached to a Window?

copy iconCopydownload iconDownload
  const html = "<div>Hello World!</div>";
  const iframe = document.createElement("iframe");
  document.body.appendChild(iframe); // 👈 still required
  iframe.contentWindow.document.open();
  iframe.contentWindow.document.write(html);
  iframe.contentWindow.document.close();
  html2canvas(iframe.contentWindow.document.body);

See all related Code Snippets

Community Discussions

Trending Discussions on html2canvas
  • How to send pdf generated from screen shot in JavaScript
  • Wait for a promise to be resolved before continuing with function
  • html making div to image
  • Created image with use-react-screenshot is incorrectly rendered
  • Use html2canvas to capture a page at a fixed width no matter the screen size
  • How to download the full to-do (vue.js)list using JsPdf?
  • Live preview with React, Html2Canvas and JsPDF
  • html2canvas bigger size of download image
  • NG_PERSISTENT_BUILD_CACHE=1 ng serve not working
  • How to resolve the error: Document not attached to a Window?
Trending Discussions on html2canvas

QUESTION

How to send pdf generated from screen shot in JavaScript

Asked 2022-Apr-10 at 12:57

Objective - Take a screenshot of the page, then make pdf of that and send that pdf to the spring boot backend.

I have implemented the functionality to take the screenshot and convert it into pdf using html2canvas and pdfmake JavaScript libraries.

Issue - I don't know how to send the generated pdf to the backend. I got to know about base64 encode but I am still confused.

Code -

function takeSS() {
    html2canvas(document.body, {
        onrendered: function(canvas) {
            var data = canvas.toDataURL();
            var docDefinition = {
                content: [{
                    image: data,
                    width: 900,
                }]
            };
            pdfMake.createPdf(docDefinition).download("test.pdf"); // to download
        }
    });
}

The above code is taking the screenshot of the page converting it to pdf and downloading it. Instead of downloading it, how can I send this pdf to backend? Do I need to base64 encode canvas.toDataURL()?

Edit Changed my code - jsFiddle

ANSWER

Answered 2022-Apr-10 at 12:57

According to the docs of pdfmake you're able to get the generated PDF as a Blob with the getBlob method. The Blob will be a binary representation of your PDF which you can send to your server.

Blobs need to be wrapped inside a FormData object before they can be sent.

Edit: Switch to the latest version (1.4.1) of html2canvas. The older version didn't work properly. The latest versions uses Promises which allows us to use async functions and, in my opinion, makes your code more readable.

The beta version of pdfmake uses Promises instead of a callback function, but the latest stable version (0.2.5) does not. But we can solve this by wrapping the callback with a Promise to still be able to use the async / await syntax.

async function takeSS() {
  const canvas = await html2canvas(document.body);
  const data = canvas.toDataURL();
  const docDefinition = {
    content: [{
      image: data,
      width: 900,
    }]
  };
  
  const pdfDocGenerator = pdfMake.createPdf(docDefinition);
  const blob = await new Promise(resolve => {
    pdfDocGenerator.getBlob(resolve);
  });
  
  const formData = new FormData();
  formData.append('pdf', blob, 'test.pdf');
  
  try {
    const response = await fetch('myapi-url', {
      method: 'POST',
      body: formData
    });
    
    if (!response.ok) {
      throw new Error('POST request failed');
    }

    const message = await response.text();
    console.log(message);
  } catch (error) {
    console.error(error);
  }
}

Source https://stackoverflow.com/questions/71793808

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install html2canvas

You can download it from GitHub.

Support

If you wish to contribute to the project, please send the pull requests to the develop branch. Before submitting any changes, try and test that the changes work with all the support browsers. If some CSS property isn’t supported or is incomplete, please create appropriate tests for it as well before submitting any code changes.

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases
Explore Kits

Save this library and start creating your kit

Explore Related Topics

Share this Page

share link
Consider Popular Image Editing Libraries
Try Top Libraries by niklasvh
Compare Image Editing Libraries with Highest Support
Compare Image Editing Libraries with Highest Quality
Compare Image Editing Libraries with Highest Security
Compare Image Editing Libraries with Permissive License
Compare Image Editing Libraries with Highest Reuse
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases
Explore Kits

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.