phantomjs/_posts/documentation/learn/2000-01-03-screen-capture.md

2.4 KiB

layout title categories permalink
post Screen Capture docs docs-learn screen-capture.html

Since PhantomJS is using WebKit, a real layout and rendering engine, it can capture a web page as a screenshot. Because PhantomJS can render anything on the web page, it can be used to convert contents not only in HTML and CSS, but also SVG and Canvas.

The following script demonstrates the simplest use of page capture. It loads the Github homepage and then saves it as an image, github.png.

var page = require('webpage').create();
page.open('http://github.com/', function() {
  page.render('github.png');
  phantom.exit();
});

To run this example create a new file called github.js. Copy and paste the above code into the github.js file. In the commandline, run this newly created script with PhantomJS:

phantomjs github.js

Beside PNG format, PhantomJS supports JPEG, GIF, and PDF.

In the examples subdirectory, there is a script rasterize.js (30 lines) which demonstrates a more complete rendering feature of PhantomJS. An example to produce the rendering of the famous Tiger (from SVG):

phantomjs rasterize.js http://ariya.github.io/svg/tiger.svg tiger.png

which gives the following tiger.png:

Rendered Tiger

Another example is to show polar clock (from RaphaelJS):

phantomjs rasterize.js http://raphaeljs.com/polar-clock.html clock.png

Polar Clock

Producing PDF output is also easy, e.g. from a Wikipedia article:

phantomjs rasterize.js 'http://en.wikipedia.org/w/index.php?title=Jakarta&printable=yes' jakarta.pdf

Canvas can be easily constructed and converted to an image. The included example colorwheel.js (50 lines) produces the following color wheel:

Color Wheel

It is possible to build a web screenshot service using PhantomJS. Some [related projects]({{ site.url }}/related-projects.html) make it easy to create such a service.