Last Updated: June 12, 2018
·
5.844K
· eresendez

How to take a screenshot of a website with PHP PhantomJs

PhantomJS is a headless WebKit scriptable with a Javascript API and PHP PhatomJS is a flexible PHP library to load pages through the PhantomJS headless browser.

Prerequisites

  • PHP 5.3.* OR greater
  • PHP Bz2

The steps to install PHP PhantomJS can be followed here.

A quick example with Laravel that take a screenshot and save it in storage.

use JonnyW\PhantomJs\Client;

$client = Client::getInstance();

// isLazy() is useful when we want to wait for all resources on the page to load.
$client->isLazy();

// Something important, set the absolute path to phatomjs bin file
$client->getEngine()->setPath(base_path('bin/phantomjs'));

// Some options
$client->getEngine()->addOption('--load-images=true');
$client->getEngine()->addOption('--ignore-ssl-errors=true')

// Here specify the page to take the screenshot
$request = $client->getMessageFactory->createCaptureRequest('https://eresendez.com', 'GET')

$request->setBodyStyles(['backgroundColor' => '#ffffff']);
$request->setOutputFile(storage_path('sample.jpg'));

$response = $client->getMessageFactory()->createResponse()
// Send the request
$client->send($request, $response);

With this, it's possible to obtain and store the screenshot in storage. PhantomJs has the option of exporting to PDF, however, if we want to do more operations with the PDF, it's better to use another tool such as DOMPDF and pass that image.

// Send to DOM PDF
$image = storage_path('sample.jpg');

$view = \View::make('pdf.sample', compact('image')->render();
$pdf = \App::make('dompdf.wrapper');

$pdf->loadHTML($view)->setPaper('letter', 'landscape');
return $pdf->stream();

Finished, PhantomJS has many more options, it's very robust, but for this simple example, it helped me to obtain an image of a site, save it and later treat it with DOM PDF.