Is there a way to render html to image like PNG? I know that it is possible with canvas but I would like to render standard html element like div for example.
-
To create some sort of user assistance, for example. Sadly, that's not possible (for security reasons?). You have to ask the user to press PrintScreen in order to do something. – MaxArt May 23 '12 at 14:21
-
1possible duplicate of How to convert HTML of a website to an image? – Ernest Friedman-Hill May 23 '12 at 14:24
-
I want to use HTML/CSS to design a logo. – Martin Delille Jun 11 '12 at 5:04
-
2@ErnestFriedman-Hill not a duplicate: the question you mentioned is specific to java. – Martin Delille Jun 11 '12 at 5:07
-
Here's a Step by Step tutorial for Converting HTML to IMAGE png or jpeg format codepedia.info/2016/02/… – Satinder singh Feb 19 '16 at 6:55
All the answers here use third party libraries while rendering HTML to an image can be relatively simple in pure Javascript. There is was even an article about it on the canvas section on MDN.
The trick is this:
- create an SVG with a foreignObject node containing your XHTML
- set the src of an image to the data url of that SVG
drawImageonto the canvas- set canvas data to target image.src
const {body} = document
const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
canvas.width = canvas.height = 100
const tempImg = document.createElement('img')
tempImg.addEventListener('load', onTempImageLoad)
tempImg.src = 'data:image/svg+xml,' + encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100"><foreignObject width="100%" height="100%"><div xmlns="http://www.w3.org/1999/xhtml"><style>em{color:red;}</style><em>I</em> lick <span>cheese</span></div></foreignObject></svg>')
const targetImg = document.createElement('img')
body.appendChild(targetImg)
function onTempImageLoad(e){
ctx.drawImage(e.target, 0, 0)
targetImg.src = canvas.toDataURL()
}
Some things to note
- The HTML inside the SVG has to be XHTML
- For security reasons the SVG as data url of an image acts as an isolated CSS scope for the HTML since no external sources can be loaded. So a Google font for instance has to be inlined using a tool like this one.
- Even when the HTML inside the SVG exceeds the size of the image it wil draw onto the canvas correctly. But the actual height cannot be measured from that image. A fixed height solution will work just fine but dynamic height will require a bit more work. The best is to render the SVG data into an iframe (for isolated CSS scope) and use the resulting size for the canvas.
-
Nice! Removing external library dependency is indeed the good way to go. I changed my accepted answer :-) – Martin Delille Oct 31 '18 at 16:19
-
-
Strange, does't look moved but simply deleted. I'll try and replace it with a waybackmachine url when I find a computer. – Sjeiti Nov 22 '18 at 14:03
-
1This answer stackoverflow.com/questions/12637395/… seems to indicate you can go quite far. Mozilla and Chrome have unlimited data uri lenght and even current IE allows 4GB, which boils down to about 3GB images (due to base64). But this would be a good thing to test. – Sjeiti Jan 1 at 14:14
-
1- some quick and dirty tests later - jsfiddle.net/Sjeiti/pcwudrmc/75965 Chrome, Edge and Firefox go up to a width height of at least 10,000 pixels which (in this case) is a character count of about 10,000,000 and a png filesize of 8MB. Haven't tested rigourously but it's enough for most use cases. – Sjeiti Jan 1 at 15:20
Yes. HTML2Canvas exists to render HTML onto <canvas> (which you can then use as an image).
NOTE: There is a known issue, that this will not work with SVG
-
It seems interesting but I didn't manage to make it work so I choose John Fisher solution. Thanks for the info, I'll watch this project in the future! – Martin Delille Jun 7 '12 at 22:04
-
@MartinDelille: here an article of using HTML2Canvas to create IMAGE and you can also download it at client side codepedia.info/2016/02/… – Satinder singh Feb 19 '16 at 6:59
-
3dom-to-image (see tsayen's answer) does a much better job to render an accurate picture. – JBE May 6 '16 at 13:44
-
2
-
2another issue, if the element is hidden or behind another element this will not work – Yousef Sep 7 '17 at 15:25
May I recommend dom-to-image library, that was written solely to address this problem (I'm the maintainer).
Here is how you use it (some more here):
var node = document.getElementById('my-node');
domtoimage.toPng(node)
.then (function (dataUrl) {
var img = new Image();
img.src = dataUrl;
document.appendChild(img);
})
.catch(function (error) {
console.error('oops, something went wrong!', error);
});
-
2
-
-
2First thing that comes to my mind - try to render your image to SVG (using
domtoimage.toSvg), then render it yourself on canvas and try to play with that canvas' resolution somehow. It's probably possible to implement such feature as some kind of rendering option in the lib itself, so you can pass image dimensions in pixels. If you need it, I'd appreciate you creating an issue on github. – tsayen Feb 12 '16 at 9:14 -
6
-
1
There is a lot of options and they all have their pro and cons.
Option 1: Use one of the many available libraries
- dom-to-image
- wkhtmltoimage (included in the wkhtmltopdf tool)
- IMGKit (for ruby and based on wkhtmltoimage)
- imgkit (for python and based on wkhtmltoimage)
- python-webkit2png
- ...
Pros
- Conversion is quite fast most of the time
Cons
- Bad rendering
- Does not execute javascript
- No support for recent web features (FlexBox, Advanced Selectors, Webfonts, Box Sizing, Media Queries, ...)
- Sometimes not so easy to install
- Complicated to scale
Option 2: Use PhantomJs and maybe a wrapper library
- PhantomJs
- node-webshot (javascript wrapper library for PhantomJs)
- ...
Pros
- Execute Javascript
- Quite fast
Cons
- Bad rendering
- No support for recent web features (FlexBox, Advanced Selectors, Webfonts, Box Sizing, Media Queries, ...)
- Complicated to scale
- Not so easy to make it work if there is images to be loaded ...
Option 3: Use Chrome Headless and maybe a wrapper library
- Chrome Headless
- chrome-devtools-protocol
- Puppeteer (javascript wrapper library for Chrome headless)
- ...
Pros
- Execute Javascript
- Near perfect rendering
Cons
- Not so easy to have exactly the wanted result regarding:
- page load timing
- viewport dimensions
- Complicated to scale
- Quite slow and even slower if the html contains external links
Option 4: Use an API
- ApiFlash (based on chrome)
- EvoPDF (has an option for html)
- Grabzit
- HTML/CSS to Image API
- ...
Pros
- Execute Javascript
- Near perfect rendering
- Fast when caching options are correctly used
- Scale is handled by the APIs
- Precise timing, viewport, ...
- Most of the time they offer a free plan
Cons
- Not free if you plan to use them a lot
Disclaimer: I'm the founder of ApiFlash. I did my best to provide an honest and useful answer.
-
2
-
wkhtmltoimage/pdf does support javascript rendering. You can set a javascript delay or let wkhtml check for a specifc window.status (which you can set with javascript when you know your js stuff is done) – Daniel Ziegler Apr 5 '18 at 9:16
You could use PhantomJS, which is a headless webkit (the rendering engine in safari and (up until recently) chrome) driver. You can learn how to do screen capture of pages here. Hope that helps!
-
This technique works well. However, 2 years have passed since your comment. Have you come across anything that operates faster than PhantomJS? Image Generation typically takes 2-5 seconds in Phantom, in my experience. – Brian Webster Dec 14 '15 at 22:16
-
Headless Chrome is now possible. I don't know if it's faster, but if you want accurate screenshots, this is a good way to go. – Josh Maag Aug 8 '17 at 16:32
You can use an HTML to PDF tool like wkhtmltopdf. And then you can use a PDF to image tool like imagemagick. Admittedly this is server side and a very convoluted process...
-
12Or you could just run wkhtmltopdf's image brother, wkhtmltoimage. – Roman Starkov Apr 16 '15 at 11:34
-
1
-
The only library that I got to work for Chrome, Firefox and MS Edge was rasterizeHTML. It outputs better quality that HTML2Canvas and is still supported unlike HTML2Canvas.
Getting Element and Downloading as PNG
var node= document.getElementById("elementId");
var canvas = document.createElement("canvas");
canvas.height = node.offsetHeight;
canvas.width = node.offsetWidth;
var name = "test.png"
rasterizeHTML.drawHTML(node.outerHTML, canvas)
.then(function (renderResult) {
if (navigator.msSaveBlob) {
window.navigator.msSaveBlob(canvas.msToBlob(), name);
} else {
const a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
a.href = canvas.toDataURL();
a.download = name;
a.click();
document.body.removeChild(a);
}
});
-
1
-
1
-
I don't expect this to be the best answer, but it seemed interesting enough to post.
Write an app that opens up your favorite browser to the desired HTML document, sizes the window properly, and takes a screen shot. Then, remove the borders of the image.
-
AKX post an interesting answer but I didn't manage to make it work... – Martin Delille Jun 7 '12 at 22:03
You can't do this 100% accurately with JavaScript alone.
There's a Qt Webkit tool out there, and a python version. If you want to do it yourself, I've had success with Cocoa:
[self startTraverse:pagesArray performBlock:^(int collectionIndex, int pageIndex) {
NSString *locale = [self selectedLocale];
NSRect offscreenRect = NSMakeRect(0.0, 0.0, webView.frame.size.width, webView.frame.size.height);
NSBitmapImageRep* offscreenRep = nil;
offscreenRep = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes:nil
pixelsWide:offscreenRect.size.width
pixelsHigh:offscreenRect.size.height
bitsPerSample:8
samplesPerPixel:4
hasAlpha:YES
isPlanar:NO
colorSpaceName:NSCalibratedRGBColorSpace
bitmapFormat:0
bytesPerRow:(4 * offscreenRect.size.width)
bitsPerPixel:32];
[NSGraphicsContext saveGraphicsState];
NSGraphicsContext *bitmapContext = [NSGraphicsContext graphicsContextWithBitmapImageRep:offscreenRep];
[NSGraphicsContext setCurrentContext:bitmapContext];
[webView displayRectIgnoringOpacity:offscreenRect inContext:bitmapContext];
[NSGraphicsContext restoreGraphicsState];
// Create a small + large thumbs
NSImage *smallThumbImage = [[NSImage alloc] initWithSize:thumbSizeSmall];
NSImage *largeThumbImage = [[NSImage alloc] initWithSize:thumbSizeLarge];
[smallThumbImage lockFocus];
[[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
[offscreenRep drawInRect:CGRectMake(0, 0, thumbSizeSmall.width, thumbSizeSmall.height)];
NSBitmapImageRep *smallThumbOutput = [[NSBitmapImageRep alloc] initWithFocusedViewRect:CGRectMake(0, 0, thumbSizeSmall.width, thumbSizeSmall.height)];
[smallThumbImage unlockFocus];
[largeThumbImage lockFocus];
[[NSGraphicsContext currentContext] setImageInterpolation:NSImageInterpolationHigh];
[offscreenRep drawInRect:CGRectMake(0, 0, thumbSizeLarge.width, thumbSizeLarge.height)];
NSBitmapImageRep *largeThumbOutput = [[NSBitmapImageRep alloc] initWithFocusedViewRect:CGRectMake(0, 0, thumbSizeLarge.width, thumbSizeLarge.height)];
[largeThumbImage unlockFocus];
// Write out small
NSString *writePathSmall = [issueProvider.imageDestinationPath stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@-collection-%03d-page-%03d_small.png", locale, collectionIndex, pageIndex]];
NSData *dataSmall = [smallThumbOutput representationUsingType:NSPNGFileType properties: nil];
[dataSmall writeToFile:writePathSmall atomically: NO];
// Write out lage
NSString *writePathLarge = [issueProvider.imageDestinationPath stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@-collection-%03d-page-%03d_large.png", locale, collectionIndex, pageIndex]];
NSData *dataLarge = [largeThumbOutput representationUsingType:NSPNGFileType properties: nil];
[dataLarge writeToFile:writePathLarge atomically: NO];
}];
Hope this helps!
Install phantomjs
$ npm install phantomjs
Create a file github.js with following code
var page = require('webpage').create();
//viewportSize being the actual size of the headless browser
page.viewportSize = { width: 1024, height: 768 };
page.open('http://github.com/', function() {
page.render('github.png');
phantom.exit();
});
Pass the file as argument to phantomjs
$ phantomjs github.js
You certainly can. GrabzIt's JavaScript API allows you to capture a div from a webpage like this:
<script type="text/javascript" src="grabzit.min.js"></script>
<script type="text/javascript">
GrabzIt("Your Application Key").ConvertURL("http://www.example.com/my-page.html",
{"target": "#features", "bheight": -1, "height": -1, "width": -1}).Create();
</script>
Where #features is the ID of the div to capture. If you wanted to convert HTML to a image. You could use this technique:
GrabzIt("Your Application Key").ConvertHTML(
"<html><body><h1>Hello World!</h1></body></html>").Create();
Disclaimer I built this API!
Use html2canvas just include plugin and call method to convert HTML to Canvas then download as image PNG
html2canvas(document.getElementById("image-wrap")).then(function(canvas) {
var link = document.createElement("a");
document.body.appendChild(link);
link.download = "manpower_efficiency.jpg";
link.href = canvas.toDataURL();
link.target = '_blank';
link.click();
});
Source: http://www.freakyjolly.com/convert-html-document-into-image-jpg-png-from-canvas/
Drawing DOM objects into a canvas shows a quick way to accomplish that.
From a performance point of view this method should be light. Because the svg renderer and the dom renderer can apparently pass buffers back & forth as needed. Which makes sense because it's all core code.
I don't have any benchmarks of this, but MDN documents are rather well maintained and not only for gecko. So I'm guessing you can at least know that bad performance is an issue which will be addressed at some point.
Use this code, it will surely work:
<script type="text/javascript">
$(document).ready(function () {
setTimeout(function(){
downloadImage();
},1000)
});
function downloadImage(){
html2canvas(document.querySelector("#dvContainer")).then(canvas => {
a = document.createElement('a');
document.body.appendChild(a);
a.download = "test.png";
a.href = canvas.toDataURL();
a.click();
});
}
</script>
Just do not forget to include Html2CanvasJS file in your program. https://html2canvas.hertzen.com/dist/html2canvas.js
You can add reference HtmlRenderer to your project and do the following,
string htmlCode ="<p>This is a sample html.</p>";
Image image = HtmlRender.RenderToImage(htmlCode ,new Size(500,300));