### Install Browsershot via Composer
Source: https://github.com/spatie/browsershot/blob/main/docs/installation-setup.md
Installs the Spatie Browsershot package using the Composer dependency manager.
```bash
composer require spatie/browsershot
```
--------------------------------
### Install Poppler Utilities
Source: https://github.com/spatie/browsershot/blob/main/README.md
Installs the poppler-utils package using Homebrew, which provides the pdftotext CLI. This is a requirement for certain functionalities of Browsershot, particularly related to PDF processing.
```bash
brew install poppler-utils
```
--------------------------------
### Install Puppeteer
Source: https://github.com/spatie/browsershot/blob/main/README.md
Installs Puppeteer globally using npm, which is a dependency for Browsershot to run headless Chrome. This command is typically run in a terminal.
```bash
npm -g i puppeteer
```
--------------------------------
### Install Puppeteer on macOS
Source: https://github.com/spatie/browsershot/blob/main/docs/requirements.md
Installs the Puppeteer Node library on macOS, either locally within a project or globally.
```bash
npm install puppeteer
```
```bash
npm install puppeteer --location=global
```
--------------------------------
### Run Tests
Source: https://github.com/spatie/browsershot/blob/main/README.md
Executes the test suite for the Browsershot package. This command requires the project's dependencies to be installed via Composer.
```bash
composer test
```
--------------------------------
### Set Initial Page Number
Source: https://github.com/spatie/browsershot/blob/main/docs/usage/creating-pdfs.md
Demonstrates how to set the starting page number for the PDF, which is particularly useful when combined with headers that display page numbers.
```php
Browsershot::html($someHtml)
->showBrowserHeaderAndFooter()
->hideFooter()
->headerHtml('')
->initialPageNumber(8)
->save('example.pdf');
```
--------------------------------
### Automate Form Submission and Screenshot with Browsershot
Source: https://github.com/spatie/browsershot/blob/main/docs/miscellaneous-options/typing-on-the-page.md
This example shows how to chain `type` and `click` methods to fill out a form, submit it, wait for potential dynamic content, and then save a screenshot of the resulting page.
```php
Browsershot::url('https://example.com')
->type('#firstName', 'My name')
->click('#submit')
->delay($millisecondsToWait)
->save($pathToImage);
```
--------------------------------
### Install Puppeteer and Chromium on Forge Server
Source: https://github.com/spatie/browsershot/blob/main/docs/requirements.md
Installs Puppeteer globally and the latest stable Chrome version using npx on a Forge provisioned Ubuntu server, along with essential system dependencies for proper functioning.
```bash
# Check if node and npm are installed
node -v && npm -v
# Install puppeteer
sudo npm install -g puppeteer
# Install chromium
npx puppeteer browsers install chrome
# Install dependencies
sudo apt update
sudo apt install libx11-xcb1 libxcomposite1 libasound2t64 libatk1.0-0 libatk-bridge2.0-0 libcairo2 libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgbm1 libgcc1 libglib2.0-0 libgtk-3-0 libnspr4 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 libxtst6
```
--------------------------------
### Image Manipulation (Greyscale)
Source: https://github.com/spatie/browsershot/blob/main/docs/usage/creating-images.md
Applies image manipulations to the screenshot after it's captured. Requires the `spatie/image` package. This example converts the screenshot to greyscale.
```bash
composer require spatie/image
```
```php
Browsershot::url('https://example.com')
->windowSize(640, 480)
->greyscale()
->save($pathToImage);
```
--------------------------------
### Setting Initial PDF Page Number (Browsershot, PHP)
Source: https://github.com/spatie/browsershot/blob/main/docs/usage/creating-pdfs.md
Sets the starting page number for the PDF using the `initialPageNumber` method, often used in conjunction with custom headers/footers displaying page numbers.
```php
Browsershot::html($someHtml)
->showBrowserHeaderAndFooter()
->hideFooter()
->headerHtml('')
->initialPageNumber(8)
->save('example.pdf');
```
--------------------------------
### Get Triggered Requests
Source: https://github.com/spatie/browsershot/blob/main/docs/introduction.md
Retrieves an array containing details of all network requests initiated by the page during rendering. Each request includes its URL.
```php
$requests = Browsershot::url('https://example.com')
->triggeredRequests();
foreach ($requests as $request) {
$url = $request['url']; //https://example.com/
}
```
--------------------------------
### Passing Font Rendering Arguments to Chromium (PHP)
Source: https://github.com/spatie/browsershot/blob/main/docs/requirements.md
Provides an example of using `addChromiumArguments` to pass a specific flag (`--font-render-hinting=none`) to Chromium, which can help fix font rendering issues on some Linux distributions.
```php
Browsershot::html('Foo')
->addChromiumArguments([
'font-render-hinting' => 'none',
]);
```
--------------------------------
### Configure Chrome/Chromium Executable Path
Source: https://github.com/spatie/browsershot/blob/main/docs/requirements.md
Allows specifying a custom path to the Chrome or Chromium executable, overriding the one installed by Puppeteer.
```php
Browsershot::html('Foo')
->setChromePath("/path/to/my/chrome")
```
--------------------------------
### Get Screenshot as Base64
Source: https://github.com/spatie/browsershot/blob/main/docs/usage/creating-images.md
Retrieves the screenshot data directly as a base64 encoded string, avoiding the need to save the image to disk. This is useful for embedding images in data streams or APIs.
```php
$base64Data = Browsershot::url('https://example.com')
->base64Screenshot();
```
--------------------------------
### Export Specific Pages
Source: https://github.com/spatie/browsershot/blob/main/docs/usage/creating-pdfs.md
Details how to export only specific pages of a document by providing a print range string to the `pages` method. Examples include single pages, page ranges, and comma-separated lists of pages.
```php
Browsershot::html($someHtml)
->pages('1-5, 8, 11-13')
->save('example.pdf');
```
--------------------------------
### Get Triggered Requests
Source: https://github.com/spatie/browsershot/blob/main/README.md
Fetches an array containing details of all network requests initiated by a web page, including those triggered by JavaScript. Each request in the array includes its URL.
```php
use Spatie\Browsershot\Browsershot;
$requests = Browsershot::url('https://example.com')
->triggeredRequests();
foreach ($requests as $request) {
$url = $request['url']; //https://example.com/
}
```
--------------------------------
### Configure Node and NPM Binaries
Source: https://github.com/spatie/browsershot/blob/main/docs/requirements.md
Allows manual specification of Node.js and npm binary paths for Browsershot if they are not found automatically in the system's PATH.
```php
Browsershot::html('Foo')
->setNodeBinary('/usr/local/bin/node')
->setNpmBinary('/usr/local/bin/npm');
```
--------------------------------
### Mobile and Touch Emulation
Source: https://github.com/spatie/browsershot/blob/main/docs/usage/creating-images.md
Emulates a mobile browser environment by setting a mobile user agent, viewport, and touch capabilities. This allows for testing mobile-specific layouts and interactions.
```php
Browsershot::url('https://example.com')
->userAgent('My Mobile Browser 1.0')
->mobile()
->touch()
->save($pathToImage);
```
--------------------------------
### Get Failed Requests in Browsershot
Source: https://github.com/spatie/browsershot/blob/main/docs/miscellaneous-options/getting-failed-requests.md
Retrieves an array of failed requests encountered during page loading. Each item in the array represents a failed resource (e.g., broken image, missing CSS) and includes its status code and URL.
```php
$consoleMessages = Browsershot::url('https://example.com')->failedRequests(); // returns an array
// Example structure of a failed request item:
// [
// 'status' => 404,
// 'url' => 'https://example.com/image.jpg'
// ]
```
--------------------------------
### Configure Binary Path
Source: https://github.com/spatie/browsershot/blob/main/docs/requirements.md
Sets a custom path to the main script or binary that Browsershot will execute.
```php
Browsershot::html('Foo')
->setBinPath("/path/to/my/project/my_script.js")
```
--------------------------------
### Device Emulation
Source: https://github.com/spatie/browsershot/blob/main/docs/usage/creating-images.md
Emulates a specific device by applying its predefined user agent, window size, device scale factor, and touch capabilities. This provides a convenient way to test against various device profiles.
```php
$browsershot = new Browsershot('https://example.com', true);
$browsershot
->device('iPhone X')
->save($pathToImage);
```
```php
Browsershot::url('https://example.com')
->userAgent('Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1')
->windowSize(375, 812)
->deviceScaleFactor(3)
->mobile()
->touch()
->landscape(false)
->save($pathToImage);
```
--------------------------------
### Import Browsershot Namespace
Source: https://github.com/spatie/browsershot/blob/main/docs/usage/introduction.md
This snippet shows the necessary namespace import for using the Browsershot package in PHP.
```php
use Spatie\Browsershot\Browsershot;
```
--------------------------------
### Get HTML Body After JS Execution
Source: https://github.com/spatie/browsershot/blob/main/docs/usage/creating-html.md
Retrieves the HTML content of the body of a web page after all JavaScript has been executed. This is useful for capturing the fully rendered DOM.
```php
Browsershot::url('https://example.com')->bodyHtml();
```
--------------------------------
### Control Backgrounds and Transparency
Source: https://github.com/spatie/browsershot/blob/main/docs/usage/creating-pdfs.md
Explains how to include the background of the HTML page in the PDF using `showBackground`. It also covers setting a transparent background instead of the default white using `transparentBackground`.
```php
Browsershot::html($someHtml)
->showBackground()
->save('example.pdf');
```
```php
Browsershot::html($someHtml)
->transparentBackground()
->save('example.pdf');
```
--------------------------------
### Convert HTML to PDF
Source: https://github.com/spatie/browsershot/blob/main/docs/introduction.md
Converts arbitrary HTML content directly into a PDF file. The `html` method is used instead of `url` for this purpose.
```php
Browsershot::html('
Hello world!!
')->save('example.pdf');
```
--------------------------------
### Connect Browsershot via Pipe
Source: https://github.com/spatie/browsershot/blob/main/docs/miscellaneous-options/using-a-pipe-instead-of-a-websocket.md
Demonstrates how to use the `usePipe()` method in Spatie's Browsershot to establish a connection to the browser using a pipe instead of a WebSocket. This is useful for specific deployment scenarios or network configurations.
```php
Browsershot::url('https://example.com')
->usePipe()
...
```
--------------------------------
### Set Browsershot Timeout
Source: https://github.com/spatie/browsershot/blob/main/docs/miscellaneous-options/setting-the-timeout.md
Demonstrates how to set a custom timeout value for Browsershot operations. The default timeout is 60 seconds, but this example shows how to increase it to 120 seconds.
```php
Browsershot::url('https://example.com')
->timeout(120)
->save($pathToImage);
```
--------------------------------
### Capture Chrome Console Messages
Source: https://github.com/spatie/browsershot/blob/main/docs/miscellaneous-options/getting-console-ouput.md
Retrieves all console output from Chrome during the rendering process. The method returns an array where each element contains the message type, the message content, and its location.
```php
$consoleMessages = Browsershot::url('https://example.com')->consoleMessages(); // returns an array
```
--------------------------------
### Output Directly to Browser
Source: https://github.com/spatie/browsershot/blob/main/docs/usage/creating-images.md
Output the image directly to the browser using the `screenshot()` method.
```php
$image = Browsershot::url('https://example.com')->screenshot()
```
--------------------------------
### Get Base64 Encoded PDF
Source: https://github.com/spatie/browsershot/blob/main/docs/usage/creating-pdfs.md
Shows how to retrieve a PDF as a base64 encoded string, useful for environments where file saving is restricted, such as Heroku. The base64 data can then be used with libraries for direct upload.
```php
$base64Data = Browsershot::url('https://example.com')
->base64pdf();
```
--------------------------------
### Basic Screenshot
Source: https://github.com/spatie/browsershot/blob/main/docs/usage/creating-images.md
Captures a screenshot of a given URL and saves it to a specified path. The default image format is PNG.
```php
Browsershot::url('https://example.com')->save($pathToImage);
```
--------------------------------
### Convert URL to PDF
Source: https://github.com/spatie/browsershot/blob/main/docs/usage/introduction.md
Demonstrates how to use Browsershot to convert a given URL into a PDF file. It takes a URL as input and saves the output to a specified file path.
```php
Browsershot::url('https://example.com')->save('example.pdf');
```
--------------------------------
### Get Body HTML after JavaScript Execution
Source: https://github.com/spatie/browsershot/blob/main/README.md
Retrieves the HTML content of the `` tag from a web page after all JavaScript has been executed. This is useful for capturing the fully rendered DOM.
```php
use Spatie\Browsershot\Browsershot;
Browsershot::url('https://example.com')->bodyHtml(); // returns the html of the body
```
--------------------------------
### Perform Clicks on Web Page
Source: https://github.com/spatie/browsershot/blob/main/docs/miscellaneous-options/clicking-on-the-page.md
This snippet demonstrates how to use the `click` method in Spatie Browsershot to simulate clicks on web page elements. It shows a basic click on an element identified by '#selector1' and a more complex scenario involving right clicks, multiple clicks, and click durations on '#selector2'.
```php
Browsershot::url('https://example.com')
->click('#selector1')
// Right click 5 times on #selector2, each click lasting 200 milliseconds.
->click('#selector2', 'right', 5, 200);
```
--------------------------------
### Select and Screenshot Element
Source: https://github.com/spatie/browsershot/blob/main/docs/usage/creating-images.md
Takes a screenshot of a specific HTML element identified by a CSS selector. An optional index can be provided to select the nth matching element.
```php
Browsershot::url('https://example.com')
->select('.some-selector', $selectorIndex)
->save($pathToImage);
```
--------------------------------
### Passing Custom Arguments to Chromium (PHP)
Source: https://github.com/spatie/browsershot/blob/main/docs/requirements.md
Demonstrates how to pass custom command-line arguments to the underlying Chromium process using the `addChromiumArguments` method, accepting an array of values or key-value pairs.
```php
Browsershot::html('Foo')
->addChromiumArguments([
'some-argument-without-a-value',
'keyed-argument' => 'argument-value',
]);
```
--------------------------------
### Get Redirect History in Browsershot
Source: https://github.com/spatie/browsershot/blob/main/docs/miscellaneous-options/read-redirect-history.md
Retrieves the redirect history for a given URL using Browsershot. The history includes URLs, HTTP statuses, reasons, and headers for each redirect. This is helpful for diagnosing rendering issues caused by site redirects.
```php
$redirects = Browsershot::url('https://www.spatie.be')
->redirectHistory();
foreach ($redirects as $redirect) {
print $redirect['url'] . PHP_EOL;
print $redirect['status'] . PHP_EOL;
print $redirect['reason'] . PHP_EOL;
foreach ($redirect['headers'] as $name => $value) {
print $name . ' : ' . $value . PHP_EOL;
}
print PHP_EOL;
}
```
--------------------------------
### Add CSS
Source: https://github.com/spatie/browsershot/blob/main/docs/usage/creating-images.md
Add CSS styles prior to the screenshot or output using `setOption('addStyleTag', ...)`. Follows Puppeteer's `page.addStyleTag` options.
```php
Browsershot::url('https://example.com')
->setOption('addStyleTag', json_encode(['content' => 'body{ font-size: 14px; }']))
->save($pathToImage);
```
--------------------------------
### Configure Include Path
Source: https://github.com/spatie/browsershot/blob/main/docs/requirements.md
Sets a custom include path for Browsershot, which can be useful for resolving issues where Node.js or npm are not found automatically.
```php
Browsershot::html('Foo')
->setIncludePath('$PATH:/usr/local/bin')
```
--------------------------------
### Convert URL to PDF
Source: https://github.com/spatie/browsershot/blob/main/docs/introduction.md
Converts a given URL to a PDF file. This is achieved by specifying a file path with a '.pdf' extension when calling the save method.
```php
// a pdf will be saved
Browsershot::url('https://example.com')->save('example.pdf');
```
--------------------------------
### Convert URL to Image
Source: https://github.com/spatie/browsershot/blob/main/docs/introduction.md
Converts a given URL to an image file. The output format is determined by the file extension of the save path.
```php
use Spatie\Browsershot\Browsershot;
// an image will be saved
Browsershot::url('https://example.com')->save($pathToImage);
```
--------------------------------
### Configure Headers and Footers
Source: https://github.com/spatie/browsershot/blob/main/docs/usage/creating-pdfs.md
Illustrates how to display browser-generated headers and footers, and how to provide custom HTML templates for them. Specific classes within the HTML (`date`, `title`, `url`, `pageNumber`, `totalPages`) are used to inject dynamic content. Methods `hideHeader` and `hideFooter` are available to disable them.
```php
Browsershot::html($someHtml)
->showBrowserHeaderAndFooter()
->headerHtml($someHtml)
->footerHtml($someHtml)
->save('example.pdf');
```
```php
Browsershot::html($someHtml)
->showBrowserHeaderAndFooter()
->hideFooter()
->headerHtml('')
->initialPageNumber(8)
->save('example.pdf');
```
--------------------------------
### Convert HTML to PDF
Source: https://github.com/spatie/browsershot/blob/main/docs/usage/introduction.md
Illustrates how to convert an arbitrary HTML string into a PDF file using Browsershot. This method is useful when you have HTML content directly available.
```php
Browsershot::html('Hello world!!
')->save('example.pdf');
```
--------------------------------
### Set Proxy Server for Browsershot
Source: https://github.com/spatie/browsershot/blob/main/docs/miscellaneous-options/specifying-a-proxy-server.md
Configures Browsershot to use a specified proxy server. The provided proxy server string is passed directly to Chromium's `--proxy-server=` command-line option.
```php
Browsershot::url('https://example.com')
->setProxyServer("1.2.3.4:8080")
...
```
--------------------------------
### Wait For Selector
Source: https://github.com/spatie/browsershot/blob/main/docs/usage/creating-images.md
Wait for a specific CSS selector to appear on the page using `waitForSelector()`. Useful for ensuring elements are present before taking a screenshot.
```php
Browsershot::url('https://example.com')
->waitForSelector('#my_selector')
->save($pathToImage);
```
--------------------------------
### Wait Until Network Idle
Source: https://github.com/spatie/browsershot/blob/main/docs/usage/creating-images.md
Wait for a period of 500 ms with no network activity before taking the screenshot, ensuring all additional resources are loaded. Can be made less strict by passing `false` to allow 2 network connections in the waiting period.
```php
Browsershot::url('https://example.com')
->waitUntilNetworkIdle()
->save($pathToImage);
// Less strict version:
// Browsershot::url('https://example.com')
// ->waitUntilNetworkIdle(false)
// ->save($pathToImage);
```
--------------------------------
### Setting Viewport and Full Page Screenshot
Source: https://github.com/spatie/browsershot/blob/main/docs/_index.md
Illustrates how to configure the viewport size for screenshots and how to capture the entire scrollable height of a webpage.
```PHP
require 'vendor/autoload.php';
use Spatie\Browsershot\Browsershot;
$browsershot = Browsershot::url('https://example.com')
->setViewport(1366, 768)
->fullPage()
->save('fullpage.png');
echo 'Full page screenshot saved to fullpage.png';
```
--------------------------------
### Set Screenshot Format and Quality
Source: https://github.com/spatie/browsershot/blob/main/docs/usage/creating-images.md
Allows setting the screenshot format to JPEG with a specified quality level. This is useful for controlling image file size and quality.
```php
Browsershot::url('https://example.com')
->setScreenshotType('jpeg', 100)
->save($pathToImage);
```
--------------------------------
### Write Browsershot Options to File
Source: https://github.com/spatie/browsershot/blob/main/docs/miscellaneous-options/writing-options-to-a-file.md
This snippet demonstrates how to use the `writeOptionsToFile()` method in Browsershot. This is useful when the number of options passed to Puppeteer exceeds the command-line character limit. By writing the options to a file, Browsershot can then pass this file to Puppeteer, circumventing the overflow issue.
```php
Browsershot::url('https://example.com')
->writeOptionsToFile()
...
```
--------------------------------
### Set Window Size
Source: https://github.com/spatie/browsershot/blob/main/docs/usage/creating-images.md
Defines the dimensions (width and height) of the browser window for the screenshot. This allows for consistent sizing across different captures.
```php
Browsershot::url('https://example.com')
->windowSize(640, 480)
->save($pathToImage);
```
--------------------------------
### Block Domains
Source: https://github.com/spatie/browsershot/blob/main/docs/usage/creating-images.md
Completely block connections to specific domains using the `blockDomains()` method. Useful for blocking advertisements and trackers to make screenshot creation faster.
```php
$domainsList = array("googletagmanager.com", "googlesyndication.com", "doubleclick.net", "google-analytics.com");
Browsershot::url('https://example.com')
->blockDomains($domainsList)
->save($pathToImage);
```
--------------------------------
### Full Page Screenshot
Source: https://github.com/spatie/browsershot/blob/main/docs/usage/creating-images.md
Captures the entire scrollable height of the webpage, not just the visible viewport. This is useful for documenting long pages.
```php
Browsershot::url('https://example.com')
->fullPage()
->save($pathToImage);
```
--------------------------------
### Outputting PDF Directly (Browsershot, PHP)
Source: https://github.com/spatie/browsershot/blob/main/docs/usage/creating-pdfs.md
Generates a PDF from a URL and returns the raw PDF content as a string using the `pdf()` method, suitable for direct output to a browser or variable.
```php
$pdf = Browsershot::url('https://example.com')->pdf();
```
--------------------------------
### HTTP Authentication with Browsershot
Source: https://github.com/spatie/browsershot/blob/main/docs/miscellaneous-options/using-http-authentication.md
Provides credentials for HTTP basic authentication. This is useful for accessing web pages that require a username and password.
```php
Browsershot::url('https://example.com')
->authenticate('username', 'password')
...
```
--------------------------------
### Set User Data Directory
Source: https://github.com/spatie/browsershot/blob/main/docs/usage/creating-images.md
Set the user data directory used to store the browser session and additional data. Needs to be an absolute path. Setting this to a static value may introduce cache problems and could increase performance.
```php
$image = Browsershot::url('https://example.com')
->userDataDir('/tmp/session-1')
->screenshot()
```
--------------------------------
### Tagged (Accessible) PDF Export
Source: https://github.com/spatie/browsershot/blob/main/docs/usage/creating-pdfs.md
Demonstrates how to generate a tagged PDF, which improves accessibility, by calling the `taggedPdf` method.
```php
Browsershot::html($someHtml)
->taggedPdf()
->save('example.pdf');
```
--------------------------------
### Wait For JavaScript Function
Source: https://github.com/spatie/browsershot/blob/main/docs/usage/creating-images.md
Wait for a JavaScript function to return `true` using `waitForFunction()`. Useful for waiting for tasks not related to network status.
```php
Browsershot::url('https://example.com')
->waitForFunction('window.innerWidth < 100', $pollingInMilliseconds, $timeoutInMilliseconds)
->save($pathToImage);
```
--------------------------------
### Add JavaScript
Source: https://github.com/spatie/browsershot/blob/main/docs/usage/creating-images.md
Add JavaScript prior to the screenshot or output using `setOption('addScriptTag', ...)`. Follows Puppeteer's `page.addScriptTag` options.
```php
Browsershot::url('https://example.com')
->setOption('addScriptTag', json_encode(['content' => 'alert("Hello World")']))
->save($pathToImage);
```
--------------------------------
### Set Arbitrary Option with setOption
Source: https://github.com/spatie/browsershot/blob/main/docs/miscellaneous-options/setting-an-arbirary-option.md
Demonstrates how to set an arbitrary option, such as 'landscape', using the `setOption` method in Browsershot. This allows for flexible configuration of browser behavior.
```php
Browsershot::url('https://example.com')
->setOption('landscape', true)
->save($pathToImage);
```
--------------------------------
### Set Device Scale Factor
Source: https://github.com/spatie/browsershot/blob/main/docs/usage/creating-images.md
Captures the webpage at a higher pixel density (e.g., 2 or 3) to simulate high-resolution displays like Retina screens.
```php
Browsershot::url('https://example.com')
->deviceScaleFactor(2)
->save($pathToImage);
```
--------------------------------
### Set Paper Size and Format
Source: https://github.com/spatie/browsershot/blob/main/docs/usage/creating-pdfs.md
Explains how to define the dimensions of the PDF using `paperSize` with custom width and height, optionally specifying units. It also covers using predefined paper formats like 'A4' via the `format` method.
```php
Browsershot::html($someHtml)
->paperSize($width, $height)
->save('example.pdf');
```
```php
Browsershot::url('https://example.com')->format('A4')->save('example.pdf');
```
--------------------------------
### Using a Remote Browser Instance
Source: https://github.com/spatie/browsershot/blob/main/docs/_index.md
Details how to connect Browsershot to a remote browser instance, such as one running in a Docker container or on a separate server, using the Puppeteer API.
```PHP
require 'vendor/autoload.php';
use Spatie\Browsershot\Browsershot;
$browsershot = Browsershot::url('https://example.com')
->useRemoteBrowser('http://127.0.0.1:9222') // Example remote URL
->save('remote.png');
echo 'Screenshot from remote browser saved to remote.png';
```
--------------------------------
### Set Landscape Orientation
Source: https://github.com/spatie/browsershot/blob/main/docs/usage/creating-pdfs.md
Shows how to configure the PDF output to be in landscape orientation by calling the `landscape` method.
```php
Browsershot::html($someHtml)
->landscape()
->save('example.pdf');
```
--------------------------------
### Configure Node Module Path
Source: https://github.com/spatie/browsershot/blob/main/docs/requirements.md
Specifies an alternative path to the `node_modules` directory for Browsershot to use.
```php
Browsershot::html('Foo')
->setNodeModulePath("/path/to/my/project/node_modules/")
```
--------------------------------
### Block URLs
Source: https://github.com/spatie/browsershot/blob/main/docs/usage/creating-images.md
Completely block connections to specific URLs using the `blockUrls()` method. Useful for blocking advertisements and trackers to make screenshot creation faster.
```php
$urlsList = array("example.com/cm_notify?pi=outbrain", "sync.outbrain.com/cookie-sync?p=bidswitch");
Browsershot::url('https://example.com')
->blockUrls($urlsList)
->save($pathToImage);
```
--------------------------------
### Save Web Page as PDF
Source: https://github.com/spatie/browsershot/blob/main/README.md
Converts a given URL into a PDF document and saves it to a specified file path. The file must have a '.pdf' extension for the PDF format to be used.
```php
use Spatie\Browsershot\Browsershot;
// a pdf will be saved
Browsershot::url('https://example.com')->save('example.pdf');
```
--------------------------------
### Use Chrome's New Headless Mode
Source: https://github.com/spatie/browsershot/blob/main/README.md
Enables Chrome's latest headless mode for rendering web pages. This option should be used when the default headless mode is not sufficient or when leveraging newer headless features.
```php
use Spatie\Browsershot\Browsershot;
Browsershot::url('https://example.com')->newHeadless()->save($pathToImage);
```
--------------------------------
### Convert to PDF
Source: https://github.com/spatie/browsershot/blob/main/docs/_index.md
Shows how to use Browsershot to convert an HTML string into a PDF document. This is useful for generating reports or printable versions of web content.
```PHP
require 'vendor/autoload.php';
use Spatie\Browsershot\Browsershot;
$html = 'Hello world!
';
$browsershot = Browsershot::html($html)
->savePdf('example.pdf');
echo 'PDF saved to example.pdf';
```
--------------------------------
### Set Base URL for HTML Content
Source: https://github.com/spatie/browsershot/blob/main/docs/miscellaneous-options/using-url-for-html-content.md
Use the `setContentUrl` method to define the base URL for HTML content. This ensures that relative paths within the HTML are fetched correctly when rendering the page with Puppeteer.
```php
Browsershot::html('... relative paths to fetch ...')
->setContentUrl('https://www.example.com')
...
```
--------------------------------
### Set Margins
Source: https://github.com/spatie/browsershot/blob/main/docs/usage/creating-pdfs.md
Details how to set the top, right, bottom, and left margins for the PDF document. Custom units can also be provided as an additional parameter.
```php
Browsershot::html($someHtml)
->margins($top, $right, $bottom, $left)
->save('example.pdf');
```
--------------------------------
### Pass Custom Arguments to Chromium
Source: https://github.com/spatie/browsershot/blob/main/docs/requirements.md
Enables passing custom arguments, either as simple flags or key-value pairs, to the Chromium executable launched by Browsershot. This is useful for configuring rendering or fixing specific issues.
```php
Browsershot::html('Foo')
->addChromiumArguments([
'some-argument-without-a-value',
'keyed-argument' => 'argument-value',
]);
```
```php
Browsershot::html('Foo')
->addChromiumArguments([
'font-render-hinting' => 'none',
]);
```
--------------------------------
### Scale PDF Content
Source: https://github.com/spatie/browsershot/blob/main/docs/usage/creating-pdfs.md
Explains how to scale the content of the PDF, with a default scale of 1. The scale amount must be between 0.1 and 2.
```php
Browsershot::html($someHtml)
->scale(0.5)
->save('example.pdf');
```
--------------------------------
### Convert HTML File to PDF
Source: https://github.com/spatie/browsershot/blob/main/README.md
Converts the content of a local HTML file into a PDF document. The method accepts the file path of the HTML file and saves the output to a specified PDF file path.
```php
use Spatie\Browsershot\Browsershot;
Browsershot::htmlFromFilePath('/local/path/to/file.html')->save('example.pdf');
```
--------------------------------
### Styling PDF Output
Source: https://github.com/spatie/browsershot/blob/main/docs/_index.md
Explains how to apply custom CSS to the generated PDF for better formatting and branding. This allows for precise control over the PDF's appearance.
```PHP
require 'vendor/autoload.php';
use Spatie\Browsershot\Browsershot;
$html = 'Styled PDF
';
$css = 'body { font-family: Arial, sans-serif; } h1 { color: blue; }';
$browsershot = Browsershot::html($html)
->addStyle($css)
->savePdf('styled.pdf');
echo 'Styled PDF saved to styled.pdf';
```
--------------------------------
### Set User Agent in Browsershot
Source: https://github.com/spatie/browsershot/blob/main/docs/miscellaneous-options/setting-the-user-agent.md
Demonstrates how to specify a custom user agent string for the browser when using the Spatie Browsershot package to take screenshots. This is useful for simulating different browser environments.
```php
Browsershot::url('https://example.com')
->userAgent('My Special Snowflake Browser 1.0')
->save($pathToImage);
```
--------------------------------
### Basic Usage - Convert to Image
Source: https://github.com/spatie/browsershot/blob/main/docs/_index.md
Demonstrates the fundamental usage of Browsershot to capture a screenshot of a given URL and save it as an image file. Requires the 'spatie/browsershot' package and Puppeteer.
```PHP
require 'vendor/autoload.php';
use Spatie\Browsershot\Browsershot;
$html = 'Hello world!
';
$browsershot = Browsershot::html($html)
->save('example.png');
echo 'Screenshot saved to example.png';
```
--------------------------------
### Hide Background
Source: https://github.com/spatie/browsershot/blob/main/docs/usage/creating-images.md
Ignores the website's background content when taking the screenshot, resulting in a transparent background if the image format supports it (like PNG).
```php
Browsershot::url('https://example.com')
->hideBackground()
->save($pathToImage);
```
--------------------------------
### Output PDF Directly to Browser
Source: https://github.com/spatie/browsershot/blob/main/docs/usage/creating-pdfs.md
Shows how to output the generated PDF directly to the browser using the `pdf()` method, without saving it to a file.
```php
$pdf = Browsershot::url('https://example.com')->pdf()
```
--------------------------------
### Set Delay for Screenshots
Source: https://github.com/spatie/browsershot/blob/main/docs/usage/creating-images.md
Delay the taking of a screenshot using `setDelay()`. Useful for waiting for JavaScript completion or capturing lazy-loaded resources.
```php
Browsershot::url('https://example.com')
->setDelay($delayInMilliseconds)
->save($pathToImage);
```