Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rasterize a fragment of HTML to PNG

Tags:

html

css

png

render

I have a page with a series of divs. Each div represents a slide in a slide deck. I need a series of thumbnails, one for each slide. Ideally these thumbnails would be rasterized versions of the slides: a PNG data: url would be perfect. I'd like the work to be done in the browser, and I'm okay with things that only work in one of the modern browsers (e.g. chrome, or firefox). I suspect this is impossible, but would love to hear otherwise.

The method toDataURL() on the canvas object is essentially what I want, but the divs in question aren't instances of canvas, so that won't work.

like image 323
Benson Avatar asked Dec 13 '22 15:12

Benson


2 Answers

One solution can be to render HTML to a canvas by embedding the HTML into an SVG image as a <foreignObject> and then drawing the resulting image via ctx.drawImage().

Read the article on MDN here, or take a look at rasterizeHTML.js which is an implementation of said approach.

The limitations are that your content should all be same-origin clean (i.e. accessible by AJAX).

Disclaimer: I am the author of rasterizeHTML.js.

like image 118
cburgmer Avatar answered Dec 30 '22 10:12

cburgmer


It isn't possible on the client side as this is forbidden to protect from potential frauds like for ie script that would take a screenshot of your page with some private data and send it god one knows where.

Although...

  • it is possible to copy whole HTML to use it as a thumb preview/whatever and use CSS3 transformations (scaling) + add overlay over it to prevent interactions/text selection etc to mimic a thumbnail of a div.

  • and there was an option in firefox/chrome extensions to save page to an image - though not sure if it was possible to take only part of the page as an image

  • or you can always do like google does on its search results page with their page preview (click the magnifying lens near the result title) - have a robot machine which enters the page and takes a screenshot of whatever to produce the preview of the page using this data - don't know how much you WANT to do that but if you wanted it that bad... :)

I'm afraid there is no easy way to do what you want and the CSS3 trick one seems to be the easiest one to pull of.

like image 36
Tom Tu Avatar answered Dec 30 '22 10:12

Tom Tu