Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cropping PhantomJS screen capture sized to content

Tags:

phantomjs

PhantomJS is doing a great job of capturing web pages into image files for me. I am using a script based on rasterize.js.

However, for certain web elements of a fixed size, I need the resulting image to match the size of the web element.

e.g. I have a page like this:

<html>
<body>
    <div id="wrapper" style="width:600px; height:400px;">
       Content goes here...
    </div>
</body>
</html>

In this example, I need it to produce an image sized at 600x400. Is thre a way to get the viewport size dynamically based on a web element in the page I am rasterizing.

I know this one is not a easy one... Ideas?

Thanks

like image 967
PrecisionPete Avatar asked Feb 01 '13 04:02

PrecisionPete


1 Answers

Wow. Not that hard after all. Just set the viewport really big and use the cropRect function. What a great tool!

Mods to rasterize.js:

page.open(address, function (status) {
    if (status !== 'success') {
        console.log('Unable to load the address!');
    } else {
        var height = page.evaluate(function(){
            return document.getElementById('wrapper').offsetHeight;
        }); 
        var width = page.evaluate(function(){
            return document.getElementById('wrapper').offsetWidth;
        }); 
        console.log('Crop to: '+width+"x"+height);

        page.clipRect = { top: 0, left: 0, width: width, height: height };
        window.setTimeout(function () {
            page.render(output);
            phantom.exit();
        }, 200);
    }
});
like image 67
PrecisionPete Avatar answered Nov 08 '22 21:11

PrecisionPete