0

I am working on a project and one of it's requirement is to take screenshot of web page and store that as an Image in local drive.

I gone through a blog and got how can we take screenshot using JavaScript. I am able to get screenshot but how to save that as an Image in local drive ?

My JQuery Code:

(function (exports) {
function urlsToAbsolute(nodeList) {
    if (!nodeList.length) {
        return [];
    }
    var attrName = 'href';
    if (nodeList[0].__proto__ === HTMLImageElement.prototype 
    || nodeList[0].__proto__ === HTMLScriptElement.prototype) {
        attrName = 'src';
    }
    nodeList = [].map.call(nodeList, function (el, i) {
        var attr = el.getAttribute(attrName);
        if (!attr) {
            return;
        }
        var absURL = /^(https?|data):/i.test(attr);
        if (absURL) {
            return el;
        } else {
            return el;
        }
    });
    return nodeList;
}

function screenshotPage() {
    urlsToAbsolute(document.images);
    urlsToAbsolute(document.querySelectorAll("link[rel='stylesheet']"));
    var screenshot = document.documentElement.cloneNode(true);
    var b = document.createElement('base');
    b.href = document.location.protocol + '//' + location.host;
    var head = screenshot.querySelector('head');
    head.insertBefore(b, head.firstChild);
    screenshot.style.pointerEvents = 'none';
    screenshot.style.overflow = 'hidden';
    screenshot.style.webkitUserSelect = 'none';
    screenshot.style.mozUserSelect = 'none';
    screenshot.style.msUserSelect = 'none';
    screenshot.style.oUserSelect = 'none';
    screenshot.style.userSelect = 'none';
    screenshot.dataset.scrollX = window.scrollX;
    screenshot.dataset.scrollY = window.scrollY;
    var script = document.createElement('script');
    script.textContent = '(' + addOnPageLoad_.toString() + ')();';
    screenshot.querySelector('body').appendChild(script);
    var blob = new Blob([screenshot.outerHTML], {
        type: 'text/html'
    });
    return blob;
}

function addOnPageLoad_() {
    window.addEventListener('DOMContentLoaded', function (e) {
        var scrollX = document.documentElement.dataset.scrollX || 0;
        var scrollY = document.documentElement.dataset.scrollY || 0;
        window.scrollTo(scrollX, scrollY);
    });
}

function generate() {
    window.URL = window.URL || window.webkitURL;
    window.open(window.URL.createObjectURL(screenshotPage()));
}
exports.screenshotPage = screenshotPage;
exports.generate = generate;
})(window);

This is my Fiddle

As shown in my fiddle, I want to provide a button/link to user so that user can take snapshot of current window/web page. And able to download/save that snapshot as an image (png, jpeg, jpg any format).

AkshayP
  • 2,141
  • 2
  • 18
  • 27
  • Thanks to all, I found better solution using [html2canvas with an example](http://www.kubilayerdogan.net/html2canvas-take-screenshot-of-web-page-and-save-it-to-server-javascript-and-php/). And here is [Live Demo](http://share.ccsudo.com/html2canvas/). – AkshayP Jun 27 '14 at 06:35

3 Answers3

1

You can't access the file system of the client directly. However, you can prompt them to download a file.

Data URLs

Data URLs are URLs where the link contains the contents of a file. For example:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAioAAAO0CAYAAACLKx00

That URL is cropped, so won't actually work.

Here is a fiddle: http://jsfiddle.net/x876K/6/

You can force it to be downloaded by using a link like this:

<a download="file.png" href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAioAAAO0CAYAAACLKx00">text</a>

Try reading:

Please tell me if I have misunderstood.

Canvas and Image

You could also write to an canvas, and allow the user to right click and save as.

Community
  • 1
  • 1
rubenwardy
  • 679
  • 5
  • 21
1

Here is my answer :

My index.php

<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="js/html2canvas.js"></script>
<script type="text/javascript" src="js/jquery.plugin.html2canvas.js"></script>

<form method="POST" enctype="multipart/form-data" action="save.php" id="myForm">
<input type="hidden" name="img_val" id="img_val" value="" />
</form>

<input type="submit" value="Take Screenshot Of Div Below" onclick="capture();" />

<div id="target">
  DIV TO TAKE PHOTO OF.
</div>

<script>
function capture() {
    $('#target').html2canvas({
        onrendered: function (canvas) {
            //Set hidden field's value to image data (base-64 string)
            $('#img_val').val(canvas.toDataURL("image/png"));
            //Submit the form manually
            document.getElementById("myForm").submit();
        }
    });
}
</script>

My save.php

<?php
//Get the base-64 string from data
$filteredData=substr($_POST['img_val'], strpos($_POST['img_val'], ",")+1);

//Decode the string
$unencodedData=base64_decode($filteredData);

//Save the image
file_put_contents('img.png', $unencodedData);

$file = 'img.png';

if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}

?>

This solution I found at a blog.

Live Demo

AkshayP
  • 2,141
  • 2
  • 18
  • 27
0

An example from https://retifrav.github.io/blog/2018/07/23/html-js-screenshot/

<head>
  <script src="html2canvas.min.js"></script>
</head>
<div>
    <a id="a-make" href="#">Make a screenshot</a>
    <a id="a-download" href="#" style="display:none;">Download a screenshot</a>
</div>

<div id="main">
    <div id="screenshot">
        ...
    </div>
</div>

<script>
    function makeScreenshot()
    {
        html2canvas(document.getElementById("screenshot"), {scale: 2}).then(canvas =>
        {
            canvas.id = "canvasID";
            var main = document.getElementById("main");
            while (main.firstChild) { main.removeChild(main.firstChild); }
            main.appendChild(canvas);
        });
    }

    document.getElementById("a-make").addEventListener('click', function()
    {
        document.getElementById("a-make").style.display = "none";
        makeScreenshot();
        document.getElementById("a-download").style.display = "inline";
    }, false);

    document.getElementById("a-download").addEventListener('click', function()
    {
        this.href = document.getElementById("canvasID").toDataURL();
        this.download = "canvas-image.png";
    }, false);
</script>
Alex M
  • 77
  • 8