PhantomJS - render()



Render helps to take the image buffer and save it as per the format specified. The formats supported are PDF, PNG, JPEG, BMP, PPM, GIF (support depends on the build of QT used).

Quality

It supports integers between 0 and 100. It is used mainly for JPEG and PNG formats. For JPEG, it is used in percentage. Level 0 will produce a very small and low quality file and 100 produces high quality file. The default value is 75. For PNG, it sets as a compression level with 0 having small file and 100 having higher one.

You can use clipRect, viewportSize, paperSize with render methods for rendering the image buffer in formats as required.

Syntax

Its syntax is as follows −

wpage.render(filename,  {format: PDF|PNG|JPEG|BMP|PPM|GIF, quality: '100'}); 

Example: Image

Let us take an example to understand the use of render() method.

var wpage = require('webpage').create(); 
wpage.viewportSize = { width: 1920, height: 1080 }; 

wpage.open("http://www.google.com", function start(status) { 
   wpage.render('image.jpeg', {format: 'jpeg', quality: '100'}); 
   phantom.exit(); 
});

The above program generates the following output.

ZoomFator Search

Example: PDF

Let us consider another example.

var wpage = require('webpage').create(); 
var url = "https://jquery.com/download/"; 
var output = "display.pdf";  

wpage.paperSize = { 
   width: '600px', 
   height: '1500px', 
   margin: {
      'top':'50px', 
      'left':'50px', 
      'rigth':'50px'  
   }, 
   orientation:'portrait', 
   
   header: { 
      height: "1cm", 
      contents: phantom.callback(function(pageNumber, nPages) { 
         return "<h5>Header <b>" + pageNumber + " / " + nPages + "</b></h5>"; 
      }) 
   }, 
   footer: { 
      height: "1cm", 
      contents: phantom.callback(function(pageNumber, nPages) { 
         return <h5>Footer <b>" + pageNumber + " / " + nPages + "</b></h5>"; 
      }) 
   } 
}  
wpage.open(url, function (status) { 
   if (status !== 'success') { 
      console.log('Page is not opening'); 
      phantom.exit(); 
   } else { 
      wpage.render(output); 
      phantom.exit(); 
   } 
});

The above program generates the following output.

Saves as display.pdf with header and footer. 
phantomjs_webpage_module_methods.htm
Advertisements