Rendering options in PhantomJS

Rajeswari K

1 min read

Recently, we got a chance to learn about PhantomJS. It’s a great tool for front-end testing and also contains interesting features like screen captures, screen scraping and so on. In Rails application, we can use PhantomJS with Capybara instead of Capybara-webkit driver. Moreover, PhantomJS is faster than Capybara-webkit driver.
Lets have a look at three types of rendering options of web page using PhantomJS which are listed below.

  • Rendering and saving the web page as image
  • Rendering and saving the web page as PDF
  • Rendering as Base64

Rendering and saving the web page as image
To capture a web page as an image, we can run the following script.
[source language=”ruby”]
var webpage = require(‘webpage’).create(), filename = ‘index.png’;
webpage.viewportSize = { width: 1024, height: 384 }; webpage.open(‘http://www.changebadtogood.com’, function(status)
{
webpage.render(filename);
console.log(‘webpage rendered as ‘ + filename);
phantom.exit();
});
[/source]
The above script creates a web page instance and also assigns our target image filename. When the webpage.open() method is called with the specified target, it loads the web page and renders the page as specified in filename variable.
On successful completion of the script, the specified web page is rendered and saved in the same directory.

  • Rendering and saving the web page as PDF
    To capture a webpage as PDF, we simply change the following render option in the same script.
    [source language=”ruby”]
    var webpage = require(‘webpage’).create(), filename = ‘demo.pdf’;
    webpage.viewportSize = { width: 1024, height: 384 };
    webpage.paperSize = {format: ‘Letter’,orientation: ‘portrait’,border: ‘0.5in’};
    webpage.open(‘http://www.changebadtogood.com’, function(status)
    {
    webpage.render(filename);
    console.log(‘webpage rendered as ‘ + filename);
    phantom.exit();
    });
    [/source]
  • Rendering as Base64
    To capture a webpage as Base64 string in PhantomJS, we just change the render method as below.
    [source language=”ruby”]
    console.log(webpage.renderBase64(filename));
    [/source]
Related posts:

Leave a Reply

Your email address will not be published. Required fields are marked *