Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

user capture div as image and save to computer

I have a Div on my site, I want to place a button/link (or other things of the sort) that when clicked will save the div and all its contents to the users computer, much like the printing code which is used to print divs. I'm a coding novice so all help will be apreciated.

like image 932
Jack Notman Avatar asked Feb 03 '23 12:02

Jack Notman


2 Answers

There is a browser support limit doing this. HTML2Canvas can render your HTML content into a canvas element. Then you can use canvas.toDataURL("image/png"); (docs in MDN) method to export the canvas element to an jpeg or png image.

It's not widely supported but it's still possible.

like image 77
Mohsen Avatar answered Feb 05 '23 17:02

Mohsen


Easy way

 var MyDiv1 = document.getElementById('DIV1');
 var MyDiv3 = document.getElementById('DIV2');
 MyDiv3.innerHTML = MyDiv1.innerHTML;


 html2canvas(MyDiv3, {
                    useCORS: true,
                    onrendered: function (canvas) {
                    var dataUrl = canvas.toDataURL("image/png");
                    document.getElementById("HiddenField1").value = dataUrl;

                    }
                });

use a button and call ur hidden field value

ButtonClick1()
{
    string imgval = HiddenField1.Value;
    imgval = imgval.Replace("data:image/png;base64,", "");
    byte[] imgData = Convert.FromBase64String(imgval);

    using (System.Drawing.Image image = System.Drawing.Image.FromStream(new MemoryStream(imgData)))
    {
        String path = Server.MapPath("~/imgFolder");
         image.Save(path + "\\output.jpg", ImageFormat.Jpeg);  // Or Png

    }
}
like image 44
Anoop B.K Avatar answered Feb 05 '23 15:02

Anoop B.K