devture/browserless

Library for communicating with the Browserless.io API (generating PDFs, etc.)

2.0 2024-11-26 11:58 UTC

This package is auto-updated.

Last update: 2024-11-26 11:59:49 UTC


README

This is a library for interacting with the Browserless.io APIs.

For the time being, this library only supports these APIs:

  • /pdf - for generating PDFs from a URL or inline HTML (like wkhtmltopdf, but better -- more up-to-date browser engine, etc.)

Prerequisites

You either need to use your own self-hosted Browserless instance (see how to do it with Docker) or their hosted offering (see Pricing).

You could use the following compose.yml setup:

version: '2.1'

services:
  browserless:
    image: ghcr.io/browserless/chromium:v2.23.0
    restart: unless-stopped
    # Matches the owner (`blessuser:blessuser`) of `/usr/src/app`
    user: 999:999
    environment:
      CONCURRENT: 10
      TOKEN: SOME_TOKEN_HERE
    # Not exposing the port is recommended, if PHP is running in a container alongisde this one
    ports:
      - "127.0.0.1:3000:3000"
    tmpfs:
      - /tmp

Usage

Creating a Browserless API client

$browserlessApiUrl = 'http://localhost:3000'; // Or 'http://browserless:3000', etc.
$browserlessToken = 'SOME_TOKEN_HERE';
$browserlessTimeoutSeconds = 15;

$client = new \Devture\Component\Browserless\Client(
	new \GuzzleHttp\Client(),
	$browserlessApiUrl,
	$browserlessToken,
	$browserlessTimeoutSeconds,
);

Generating a PDF from a URL

$url = 'https://devture.com';

$pdfCreationRequest = new \Devture\Component\Browserless\Model\PdfCreationRequest();
$pdfCreationRequest->setUrl($url);
$pdfCreationRequest->setOptions([
	'printBackground' => true,
	'format' => 'A4',
	'landscape' => true,
]);

$pdfBytes = $client->createPdfFromRequest($pdfCreationRequest);

Generating a PDF from inline HTML

$html = '<html><body>Some <strong>HTML</strong> here</body></html>';

$pdfCreationRequest = new \Devture\Component\Browserless\Model\PdfCreationRequest();
$pdfCreationRequest->setHtml($html);
$pdfCreationRequest->setOptions([
	'printBackground' => true,
	'format' => 'A4',
	'margin' => [
		'top' => '20mm',
		'bottom' => '10mm',
		'left' => '10mm',
		'right' => '10mm',
	],
]);

$pdfBytes = $client->createPdfFromRequest($pdfCreationRequest);

Alternatives