How to take a PNG screenshot using html2canvas Lib and PHP
Accidently this week i found on github the html2canvas Lib with allows to take screenshots of webpages or parts of them. And then I had instantly the feeling that the script perfectly fits into an WebSnap Application because Canvas ist perfect to be saved as image on server. I found also that Canvas solution is better than HTML2PDF + PDF2JPEG because Canvas is exactly what you get on screen and doesn't needs special rendering from DOM into intermediary format (PDF,PS), I tested dom2pdf php class and the result was unsuccessful. The Limitations of html2canvas is that all the images that the script uses must reside under the same origin for it to be able to read, so must be a local copy of website images to get a Canvas with full website view, otherwise Canvas is reading only the HTML/CSS and nothing else.
So this is how HTML2Png experiment started, I had to make a code flow, a plan , how to get images and how to save the images after Canvas is redered.
Main steps in code are:
------------------------------------
1. Read DOM from address url
2. Render/Format the DOM before displayed
3. Make a local copy of images located in address url domain
4. Make a canvas print after page is loaded (onready)
5. Save canvas as png file using ajax
Some explanations to the code:
Step 1. is easy, with file_get_contents() function, the source page is readed and that passed to formatting Step 2. Because source came with whole DOM structure, I had to clean some parts of DOM source, for example I removed scripts, comments, inline styles and replaced the body, html and head. Thru this procces runs also Step 3., the verifying/changing routine for image paths, the domani path became local path for all images. When everything is done came Step 4. where html2canvas creates a Canvas screenshot from local page with looks now almost like online page after rendering. On Step 5. ajax is passing the data:image base64 string to makefile.php where image is writen in tmp folder and resized after.
After completing this code I made a ToDo list to Build a WebSnap Application for my website bookmarks links, which looks like this:
From External Server
-------------------------------
1. Read links from database on request
2. Return a json array with links
-------------------------------
3. Read Json file with php
4. For each json elemen do:
4.1. Read DOM from address url
4.2. Render/Format the DOM before displayed
4.3. Make a local copy of images located in address url domain
4.4. Make a canvas print after page is loaded (onready)
4.5. Save canvas as png file using ajax
4.6. Set a cookie with current id
5. after 10 seconds do a refresh and get next id ( with next url )
Download links:
-------------------------------
If you want to test the HTML2Png code, try the repository from github:
https://github.com/maranemil/HTML2Png
More info about html2canvas Lib can be found here:
http://html2canvas.hertzen.com/