Closed oliverini closed 5 years ago
Solved this as follows: The PrintToPDFResponse Object data is base64 encoded (see https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF) so all I was missing was to decode it before saving, so for anyone wanting a working example you have this...
First install with composer...
composer require jakubkulhan/chrome-devtools-protocol
Then this saves a PDF...
require_once "vendor/autoload.php";
use ChromeDevtoolsProtocol\Context;
use ChromeDevtoolsProtocol\Instance\Launcher;
use ChromeDevtoolsProtocol\Model\Page\NavigateRequest;
use ChromeDevtoolsProtocol\Model\Page\PrintToPDFRequest;
// context creates deadline for operations
$ctx = Context::withTimeout(Context::background(), 30 /* seconds */);
// launcher starts chrome process ($instance)
$launcher = new Launcher();
$instance = $launcher->launch($ctx);
try {
// work with new tab
$tab = $instance->open($ctx);
$tab->activate($ctx);
$devtools = $tab->devtools();
try {
$devtools->page()->enable($ctx);
$devtools->page()->navigate($ctx, NavigateRequest::builder()->setUrl("https://www.google.com/")->build());
$devtools->page()->awaitLoadEventFired($ctx);
$response = $devtools->page()->printToPDF($ctx, PrintToPDFRequest::make());
file_put_contents('sample.pdf', base64_decode( $response->data ));
} finally {
$devtools->close();
}
} finally {
$instance->close();
}
I was using the basic example as well and could not get a screenshot generated with:
$response = $devtools->page()->captureScreenshot($ctx, CaptureScreenshotRequest::builder()->setFormat("jpg")->setQuality(95)->build());
The response data is an empty string. It should also be base64 encoded. Any suggestions?
The basic sample for screenshot is incorrect you need to use "jpeg" in the setFormat not "jpg"
I have your Basic Usage demo working with the addition of the necessary autoload and use classes, but nothing happens on printToPDF. No PDF is created. $devtools->page()->printToPDF($ctx, PrintToPDFRequest::make()) returns a PrintToPDFResponse Object with data. I've tried saving that data using file_put_contents but it's not a valid PDF. Am I missing something?