websnap/laravel

A Laravel wrapper for the Websnap PHP Client

1.5.0 2023-03-09 20:01 UTC

This package is auto-updated.

Last update: 2024-04-10 10:10:56 UTC


README

coverage report

Installation

Install with composer: composer require websnap/laravel

Summary

Websnap is a service to generate images/pdf from html. Either provided as a html string or an url which content's will be fetched and processed.

Getting started

  1. Register for free at https://www.websnap.app and obtain a token
  2. Add your token as an environment variable WEBSNAP_TOKEN={YOUR_TOKEN}

Usage

1. Websnap Facade

Allows you to request a websnap anywhere in your code and process the response to fit your needs.

// Screenshot from url
$response = \Websnap\Laravel\Facades\Websnap::screenshot('https://www.websnap.app');

// Screenshot from html
$response = \Websnap\Laravel\Facades\Websnap::screenshot('<h1>Hello world!</h1>');

// PDF from url
$response = \Websnap\Laravel\Facades\Websnap::pdf('https://www.websnap.app');

// PDF from html
$response = \Websnap\Laravel\Facades\Websnap::pdf('<h1>Hello world!</h1>');

The screenshot/pdf method will return a PSR-7 response object.

2. Middleware

You can add the websnap middleware to any route. This will pass the route's content through Websnap and return the screenshot as an image response.

Route::middleware('websnap')->get('share-image', fn() => view('share-image'));

We can also pass the websnap options in a query string format to the middleware:

Route::middleware('websnap:viewport_width=1200&viewport_height=600')->get('share-image', fn() => view('share-image'));

As an alternative we also take the GET parameter websnap into consideration and forward the options to the websnap request.

<meta property="og:image" content="/share-image?websnap[viewport_width]=1200&websnap[viewport_height]=630">

For testing purposes you can bypass the middleware by setting the WEBSNAP_MIDDLEWARE_BYPASS=true environment variable and always force the route's return value. Eg. a view.

3. Response

For convenience, we added macros to the response factory to return an image or pdf response with just one line of code.

// Image response from a route
Route::get('share-image', fn() => response()->screenshot('https://www.websnap.app'));

// PDF response from a route
Route::get('share-image', fn() => response()->pdf('<h1>Hello World!</h1>'));

Contact

Did you found a bug or need a certain feature? Please get in touch with us or raise an issue.