Convert html to an image, pdf or string

Overview

Social Card of Spatie's Browsershot

Convert a webpage to an image or pdf using headless Chrome

Latest Version MIT Licensed run-tests Total Downloads

The package can convert a webpage to an image or pdf. The conversion is done behind the scenes by Puppeteer which controls a headless version of Google Chrome.

Here's a quick example:

use Spatie\Browsershot\Browsershot;

// an image will be saved
Browsershot::url('https://example.com')->save($pathToImage);

It will save a pdf if the path passed to the save method has a pdf extension.

// a pdf will be saved
Browsershot::url('https://example.com')->save('example.pdf');

You can also use an arbitrary html input, simply replace the url method with html:

Browsershot::html('<h1>Hello world!!</h1>')->save('example.pdf');

Browsershot also can get the body of an html page after JavaScript has been executed:

Browsershot::url('https://example.com')->bodyHtml(); // returns the html of the body

If you wish to retrieve an array list with all of the requests that the page triggered you can do so:

$requests = Browsershot::url('https://example.com')
    ->triggeredRequests();

foreach ($requests as $request) {
    $url = $request['url']; //https://example.com/
}

triggeredRequests() works well with waitUntilNetworkIdle as described here

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Requirements

This package requires node 7.6.0 or higher and the Puppeteer Node library.

On MacOS you can install Puppeteer in your project via NPM:

npm install puppeteer

Or you could opt to just install it globally

npm install puppeteer --global

On a Forge provisioned Ubuntu 16.04 server you can install the latest stable version of Chrome like this:

curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash -
sudo apt-get install -y nodejs gconf-service libasound2 libatk1.0-0 libc6 libcairo2 libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgbm1 libgcc1 libgconf-2-4 libgdk-pixbuf2.0-0 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 ca-certificates fonts-liberation libappindicator1 libnss3 lsb-release xdg-utils wget libgbm-dev
sudo npm install --global --unsafe-perm puppeteer
sudo chmod -R o+rx /usr/lib/node_modules/puppeteer/.local-chromium

Custom node and npm binaries

Depending on your setup, node or npm might be not directly available to Browsershot. If you need to manually set these binary paths, you can do this by calling the setNodeBinary and setNpmBinary method.

Browsershot::html('Foo')
    ->setNodeBinary('/usr/local/bin/node')
    ->setNpmBinary('/usr/local/bin/npm');

By default, Browsershot will use node and npm to execute commands.

Custom include path

If you don't want to manually specify binary paths, but rather modify the include path in general, you can set it using the setIncludePath method.

Browsershot::html('Foo')
    ->setIncludePath('$PATH:/usr/local/bin')

Setting the include path can be useful in cases where node and npm can not be found automatically.

Custom node module path

If you want to use an alternative node_modules source you can set it using the setNodeModulePath method.

Browsershot::html('Foo')
  ->setNodeModulePath("/path/to/my/project/node_modules/")

Custom binary path

If you want to use an alternative script source you can set it using the setBinPath method.

Browsershot::html('Foo')
  ->setBinPath("/path/to/my/project/my_script.js")

Custom chrome/chromium executable path

If you want to use an alternative chrome or chromium executable from what is installed by puppeteer you can set it using the setChromePath method.

Browsershot::html('Foo')
  ->setChromePath("/path/to/my/chrome")

Pass custom arguments to Chromium

If you need to pass custom arguments to Chromium, use the addChromiumArguments method.

The method accepts an array of key/value pairs, or simply values. All of these arguments will automatically be prefixed with --.

Browsershot::html('Foo')
  ->addChromiumArguments([
      'some-argument-without-a-value',
      'keyed-argument' => 'argument-value',
  ]);

If no key is provided, then the argument is passed through as-is.

Example array Flags that will be passed to Chromium
['foo'] --foo
['foo', 'bar'] --foo --bar
['foo', 'bar' => 'baz' ] --foo --bar=baz

This method can be useful in order to pass a flag to fix font rendering issues on some Linux distributions (e.g. CentOS).

Browsershot::html('Foo')
  ->addChromiumArguments([
      'font-render-hinting' => 'none',
  ]);

Installation

This package can be installed through Composer.

composer require spatie/browsershot

Usage

In all examples it is assumed that you imported this namespace at the top of your file

use Spatie\Browsershot\Browsershot;

Screenshots

Here's the easiest way to create an image of a webpage:

Browsershot::url('https://example.com')->save($pathToImage);

Formatting the image

By default the screenshot's type will be a png. (According to Puppeteer's Config) But you can change it to jpeg with quality option.

Browsershot::url('https://example.com')
    ->setScreenshotType('jpeg', 100)
    ->save($pathToImage);

Sizing the image

By default the screenshot's size will match the resolution you use for your desktop. Want another size of screenshot? No problem!

Browsershot::url('https://example.com')
    ->windowSize(640, 480)
    ->save($pathToImage);

You can also set the size of the output image independently of the size of window. Here's how to resize a screenshot take with a resolution of 1920x1080 and scale that down to something that fits inside 200x200.

Browsershot::url('https://example.com')
    ->windowSize(1920, 1080)
    ->fit(Manipulations::FIT_CONTAIN, 200, 200)
    ->save($pathToImage);

You can screenshot only a portion of the page by using clip.

Browsershot::url('https://example.com')
    ->clip($x, $y, $width, $height)
    ->save($pathToImage);

You can take a screenshot of an element matching a selector using select and an optional $selectorIndex which is used to select the nth element (e.g. use $selectorIndex = 3 to get the fourth element like div:eq(3)). By default $selectorIndex is 0 which represents the first matching element.

Browsershot::url('https://example.com')
    ->select('.some-selector', $selectorIndex)
    ->save($pathToImage);

Getting a screenshot as base64

If you need the base64 version of a screenshot you can use the base64Screenshot method. This can come in handy when you don't want to save the screenshot on disk.

$base64Data = Browsershot::url('https://example.com')
    ->base64Screenshot();

Manipulating the image

You can use all the methods spatie/image provides. Here's an example where we create a greyscale image:

Browsershot::url('https://example.com')
    ->windowSize(640, 480)
    ->greyscale()
    ->save($pathToImage);

Taking a full page screenshot

You can take a screenshot of the full length of the page by using fullPage().

Browsershot::url('https://example.com')
    ->fullPage()
    ->save($pathToImage);

Setting the device scale

You can also capture the webpage at higher pixel densities by passing a device scale factor value of 2 or 3. This mimics how the webpage would be displayed on a retina/xhdpi display.

Browsershot::url('https://example.com')
    ->deviceScaleFactor(2)
    ->save($pathToImage);

Mobile emulation

You can emulate a mobile view with the mobile and touch methods. mobile will set the display to take into account the page's meta viewport, as Chrome mobile would. touch will set the browser to emulate touch functionality, hence allowing spoofing for pages that check for touch. Along with the userAgent method, these can be used to effectively take a mobile screenshot of the page.

Browsershot::url('https://example.com')
    ->userAgent('My Mobile Browser 1.0')
    ->mobile()
    ->touch()
    ->save($pathToImage);

Device emulation

You can emulate a device view with the device method. The devices' names can be found Here.

$browsershot = new Browsershot('https://example.com', true);
$browsershot
        ->device('iPhone X')
        ->save($pathToImage);

is the same as

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);

Backgrounds

If you want to ignore the website's background when capturing a screenshot, use the hideBackground() method.

Browsershot::url('https://example.com')
    ->hideBackground()
    ->save($pathToImage);

Dismiss dialogs

Javascript pop ups such as alerts, prompts and confirmations cause rendering of the site to stop, which leads to an empty screenshot. Calling dismissDialogs() method automatically closes such popups allowing the screenshot to be taken.

Browsershot::url('https://example.com')
    ->dismissDialogs()
    ->save($pathToImage);

Disable Javascript

If you want to completely disable javascript when capturing the page, use the disableJavascript() method. Be aware that some sites will not render correctly without javascript.

Browsershot::url('https://example.com')
    ->disableJavascript()
    ->save($pathToImage);

Disable Images

You can completely remove all images and elements when capturing a page using the disableImages() method.

Browsershot::url('https://example.com')
    ->disableImages()
    ->save($pathToImage);

Block Urls

You can completely block connections to specific Urls using the blockUrls() method. Useful to block advertisements and trackers to make screenshot creation faster.

$urlsList = array("example.com/cm-notify?pi=outbrain", "sync.outbrain.com/cookie-sync?p=bidswitch");
Browsershot::url('https://example.com')
    ->blockUrls($urlsList)
    ->save($pathToImage);

Block Domains

You can completely block connections to specific domains using the blockDomains() method. Useful to block advertisements and trackers to make screenshot creation faster.

$domainsList = array("googletagmanager.com", "googlesyndication.com", "doubleclick.net", "google-analytics.com");
Browsershot::url('https://example.com')
    ->blockDomains($domainsList)
    ->save($pathToImage);

Waiting for lazy-loaded resources

Some websites lazy-load additional resources via ajax or use webfonts, which might not be loaded in time for the screenshot. Using the waitUntilNetworkIdle() method you can tell Browsershot to wait for a period of 500 ms with no network activity before taking the screenshot, ensuring all additional resources are loaded.

Browsershot::url('https://example.com')
    ->waitUntilNetworkIdle()
    ->save($pathToImage);

Alternatively you can use less strict waitUntilNetworkIdle(false), which allows 2 network connections in the 500 ms waiting period, useful for websites with scripts periodically pinging an ajax endpoint.

Delayed screenshots

You can delay the taking of screenshot by setDelay(). This is useful if you need to wait for completion of javascript or if you are attempting to capture lazy-loaded resources.

Browsershot::url('https://example.com')
    ->setDelay($delayInMilliseconds)
    ->save($pathToImage);

Waiting for javascript function

You can also wait for a javascript function until is returns true by using waitForFunction(). This is useful if you need to wait for task on javascript which is not related to network status.

Browsershot::url('https://example.com')
    ->waitForFunction('window.innerWidth < 100', $pollingInMilliseconds, $timeoutInMilliseconds)
    ->save($pathToImage);

Adding JS

You can add javascript prior to your screenshot or output using the syntax for Puppeteer's addScriptTag.

Browsershot::url('https://example.com')
    ->setOption('addScriptTag', json_encode(['content' => 'alert("Hello World")']))
    ->save($pathToImage);

Adding CSS

You can add CSS styles prior to your screenshot or output using the syntax for Puppeteer's addStyleTag.

Browsershot::url('https://example.com')
    ->setOption('addStyleTag', json_encode(['content' => 'body{ font-size: 14px; }']))
    ->save($pathToImage);

Output directly to the browser

You can output the image directly to the browser using the screenshot() method.

$image = Browsershot::url('https://example.com')
    ->screenshot()

PDFs

Browsershot will save a pdf if the path passed to the save method has a pdf extension.

// a pdf will be saved
Browsershot::url('https://example.com')->save('example.pdf');

Alternatively you can explicitly use the savePdf method:

Browsershot::url('https://example.com')->savePdf('example.pdf');

You can also pass some html which will be converted to a pdf.

Browsershot::html($someHtml)->savePdf('example.pdf');

Sizing the pdf

You can specify the width and the height.

Browsershot::html($someHtml)
   ->paperSize($width, $height)
   ->save('example.pdf');

Optionally you can give a custom unit to the paperSize as the third parameter.

Using a predefined format

You can use the format method and provide a format size:

Browsershot::html('https://example.com')->format('A4')->save('example.pdf');

The format options available by puppeteer are:

Letter: 8.5in  x  11in
Legal: 8.5in  x  14in
Tabloid: 11in  x  17in
Ledger: 17in  x  11in
A0: 33.1in  x  46.8in
A1: 23.4in  x  33.1in
A2: 16.54in  x  23.4in
A3: 11.7in  x  16.54in
A4: 8.27in  x  11.7in
A5: 5.83in  x  8.27in
A6: 4.13in  x  5.83in

Setting margins

Margins can be set.

Browsershot::html($someHtml)
   ->margins($top, $right, $bottom, $left)
   ->save('example.pdf');

Optionally you can give a custom unit to the margins as the fifth parameter.

Headers and footers

By default a PDF will not show the header and a footer generated by Chrome. Here's how you can make the header and footer appear. You can also provide a custom HTML template for the header and footer.

Browsershot::html($someHtml)
   ->showBrowserHeaderAndFooter()
   ->headerHtml($someHtml)
   ->footerHtml($someHtml)
   ->save('example.pdf');

In the header and footer HTML, any tags with the following classes will have its printing value injected into its contents.

  • date formatted print date
  • title document title
  • url document location
  • pageNumber current page number
  • totalPages total pages in the document

To hide the header or footer, you can call either hideHeader or hideFooter.

Backgrounds

By default, the resulting PDF will not show the background of the html page. If you do want the background to be included you can call showBackground:

Browsershot::html($someHtml)
   ->showBackground()
   ->save('example.pdf');

Landscape orientation

Call landscape if you want to resulting pdf to be landscape oriented.

Browsershot::html($someHtml)
   ->landscape()
   ->save('example.pdf');

Scale

Scale can be set. Defaults to 1. Scale amount must be between 0.1 and 2.

Browsershot::html($someHtml)
    ->scale(0.5)
    ->save('example.pdf');

Only export specific pages

You can control which pages should be export by passing a print range to the pages method. Here are some examples of valid print ranges: 1, 1-3, 1-5, 8, 11-13.

Browsershot::html($someHtml)
   ->pages('1-5, 8, 11-13')
   ->save('example.pdf');

Output directly to the browser

You can output the PDF directly to the browser using the pdf() method.

$pdf = Browsershot::url('https://example.com')
    ->pdf()

HTML

Browsershot also can get the body of an html page after JavaScript has been executed:

Browsershot::url('https://example.com')->bodyHtml(); // returns the html of the body

Evaluate

Browsershot can get the evaluation of an html page:

Browsershot::url('https://example.com')
  ->deviceScaleFactor(2)
  ->evaluate("window.devicePixelRatio"); // returns 2

Misc

Setting an arbitrary option

You can set any arbitrary options by calling setOption:

Browsershot::url('https://example.com')
   ->setOption('landscape', true)
   ->save($pathToImage);

Fixing cors issues

If you experience issues related to cors, you can opt to disable cors checks with --disable-web-security.

Browsershot::url('https://example.com')
   ->setOption('args', ['--disable-web-security'])
   ->save($pathToImage);

Changing the language of the browser

You can use setOption to change the language of the browser. In order to load a page in a specific language for example.

Browsershot::url('https://example.com')
   ->setOption('args', '--lang=en-GB')
   ...

Setting the user agent

If you want to set the user agent Google Chrome should use when taking the screenshot you can do so:

Browsershot::url('https://example.com')
    ->userAgent('My Special Snowflake Browser 1.0')
    ->save($pathToImage);

Setting the CSS media type of the page

You can emulate the media type, especially useful when you're generating pdf shots, because it will try to emulate the print version of the page by default.

Browsershot::url('https://example.com')
    ->emulateMedia('screen') // "screen", "print" (default) or null (passing null disables the emulation).
    ->savePdf($pathToPdf);

Setting the timeout

The default timeout of Browsershot is set to 60 seconds. Of course, you can modify this timeout:

Browsershot::url('https://example.com')
    ->timeout(120)
    ->save($pathToImage);

Disable sandboxing

When running Linux in certain virtualization environments it might need to disable sandboxing.

Browsershot::url('https://example.com')
   ->noSandbox()
   ...

Ignore HTTPS errors

You can ignore HTTPS errors, if necessary.

Browsershot::url('https://example.com')
   ->ignoreHttpsErrors()
   ...

Specify a proxy Server

You can specify a proxy server to use when connecting. The argument passed to setProxyServer will be passed to the --proxy-server= option of Chromium. More info here: https://www.chromium.org/developers/design-documents/network-settings#TOC-Command-line-options-for-proxy-settings

Browsershot::url('https://example.com')
   ->setProxyServer("1.2.3.4:8080")
   ...

Setting extraHTTPHeaders

To send custom HTTP headers, set the extraHTTPHeaders option like so:

Browsershot::url('https://example.com')
    ->setExtraHttpHeaders(['Custom-Header-Name' => 'Custom-Header-Value'])
   ...

Using HTTP Authentication

You can provide credentials for HTTP authentication:

Browsershot::url('https://example.com')
    ->authenticate('username', 'password')
   ...

Using Cookies

You can add cookies to the request to the given url:

Browsershot::url('https://example.com')
    ->useCookies(['Cookie-Key' => 'Cookie-Value'])
   ...

You can specify the domain to register cookies to, if necessary:

Browsershot::url('https://example.com')
    ->useCookies(['Cookie-Key' => 'Cookie-Value'], 'ui.example.com')
   ...

Sending POST requests

By default, all requests sent using GET method. You can make POST request to the given url by using the post method. Note: POST request sent using application/x-www-form-urlencoded content type.

Browsershot::url('https://example.com')
    ->post(['foo' => 'bar'])
   ...

Clicking on the page

You can specify clicks on the page.

Browsershot::url('https://example.com')
    ->click('#selector1')
    // Right click 5 times on #selector2, each click lasting 200 milliseconds.
    ->click('#selector2', 'right', 5, 200)

Typing on the page

You can type on the page (you can use this to fill form fields).

Browsershot::url('https://example.com')
    ->type('#selector1', 'Hello, is it me you are looking for?')

You can combine type and click to create a screenshot of a page after submitting a form:

Browsershot::url('https://example.com')
    ->type('#firstName', 'My name')
    ->click('#submit')
    ->delay($millisecondsToWait)
    ->save($pathToImage);

Changing the value of a dropdown value

You can change the value of a dropdown on the page (you can use this to change form select fields).

Browsershot::url('https://example.com')
    ->selectOption('#selector1', '100')

You can combine selectOption, type and click to create a screenshot of a page after submitting a form:

Browsershot::url('https://example.com')
    ->type('#firstName', 'My name')
    ->selectOption('#state', 'MT')
    ->click('#submit')
    ->delay($millisecondsToWait)
    ->save($pathToImage);

Writing options to file

When the amount of options given to puppeteer becomes too big, Browsershot will fail because of an overflow of characters in the command line. Browsershot can write the options to a file and pass that file to puppeteer and so bypass the character overflow.

Browsershot::url('https://example.com')
   ->writeOptionsToFile()
   ...

Connection to a remote chromium/chrome instance

If you have a remote endpoint for a running chromium/chrome instance, properly configured with the param --remote-debugging-port, you can connect to it using the method setRemoteInstance. You only need to specify it's ip and port (defaults are 127.0.0.1 and 9222 accordingly). If no instance is available at the given endpoint (instance crashed, restarting instance, etc), this will fallback to launching a chromium instance.

Browsershot::url('https://example.com')
   ->setRemoteInstance('1.2.3.4', 9222)
   ...

Using a pipe instead of a WebSocket

If you want to connect to the browser over a pipe instead of a WebSocket, you can use:

Browsershot::url('https://example.com')
   ->usePipe()
   ...

Passing environment variables to the browser

If you want to set custom environment variables which affect the browser instance you can use:

Browsershot::url('https://example.com')
   ->setEnvironmentOptions(['TZ' => 'Pacific/Auckland'])
   ...

Related packages

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Alternatives

If you're not able to install Node and Puppeteer, take a look at v2 of browsershot, which uses Chrome headless CLI to take a screenshot. v2 is not maintained anymore, but should work pretty well.

If using headless Chrome does not work for you take a look at at v1 of this package which uses the abandoned PhantomJS binary.

Credits

And a special thanks to Caneco for the logo

License

The MIT License (MIT). Please see License File for more information.

Comments
  • Configureable node binary

    Configureable node binary

    This pull requests adds the possibility to configure the node binary manually by calling the setNodeBinary method.

    Furthermore, the default environment in browser.js is removed. This fixed environment caused an error to occur when rendering a PDF within a web request. My best guess as to why this happens is because nginx doesn't use the same include paths as the terminal. The result was that PDFs could not be rendered on the fly in a Mac/nginx setup, because node was not a known environment.

    By making the node binary configurable, this problem can be solved regardless of which system is running the library. A path to the node binary can be specified, and will default to node.

    opened by brendt 19
  • Rework to use Puppeteer instead of Chrome headless cli directly

    Rework to use Puppeteer instead of Chrome headless cli directly

    Hey, this PR is a rework of the package internals using Puppeteer instead of the Chrome headless CLI directly, while keeping and expanding the public API.

    Puppeteer is an official Node library from the Chrome team which provides an easy to use API for controlling Chrome over the DevTools protocol. This gives us access to a richer APIs allowing for a lot of customization options for the generated screenshots and pdfs that are not possible with the Chrome CLI.

    Pros

    • way more customization options for generating screenshots and pdfs including some really useful ones
    • not reinventing the wheel, using an official and actively developed 3rd party library
    • not having to add and install Chrome from Google repositories (included in Puppeteer)

    Cons

    • dependency on Node and Puppeteer (kinda like back in 1.x)
    • breaking changes requiring a major release
    • a slight performance hit (about 6s -> 8s for the original test suite)

    New options in this PR

    Screenshots

    • clip - clipping a region of the page (might be redundant since we have the image manipulations api)
    • fullPage - takes screenshot of the full scrollable page 👌

    PDFs

    • browserHeaderAndFooter - show/hide the browser header and footer
    • includeBackground - include/exclude backgrounds
    • landscape - landscape page orientation
    • pages - printed page ranges, eg. 1-5, 8, 11-13
    • pageSize - page width/height in millimetres
    • margins - page top/right/bottom/left margin in millimetres

    Removed APIs

    I've removed these APIs since Puppeteer provides defaults in both cases.

    • disableGpu/enableGpu
    • hideScrollbars/showScrollbars

    The Puppeteer API provides a lot more options, not only for the screenshots and pdfs. I've decided to add only the most useful ones so the Browsershot API doesn't get out of hand.

    Note that this can all be implemented in pure PHP since the DevTools protocol works over WebSockets. I've tried to hack on that solution, but it also required a large amount of composer dependencies and I didn't really like the code nor wanted to reinvent the wheel, so I went with Puppeteer.

    This is a pretty big PR that has both pros and cons, so I have no expectations of you merging it. I've needed to write this anyway for my own use, so I might as well try to contribute back. 🙃

    Thanks for the consideration! 🚀

    opened by itsgoingd 17
  • Add evaluate() function

    Add evaluate() function

    I've created a PR to add puppeteer's evaluate() function https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#pageevaluatepagefunction-args

    opened by darron1217 9
  • Fixed background color

    Fixed background color

    Hey @freekmurze, I was having issues with some pages not rendering the <body> background. The page http://ianwillia.ms for example came out like so:

    screen_160311_113554

    The PR implements the fix that Eivind Uggedal apparently uses for his site http://mediaqueri.es. http://uggedal.com/journal/phantomjs-default-background-color/

    opened by carlcs 7
  • Hotfix/readme update

    Hotfix/readme update

    I have added the example of format method available for generating pdf and added available option to pass on to format method. Because there was an open issue regarding this method. (issue no. #325)

    opened by MJunaidAhmad 6
  • Add the ability to allow arbitrary options to be passed to puppeteer

    Add the ability to allow arbitrary options to be passed to puppeteer

    This PR adds a setOption($key, $value) method which will allow users to pass options to Puppeteer that are not explicitly covered by the rest of this package.

    Options can be set using dot notation, like so:

    Browsershot::url('https://example.com')
                ->showBackground()
                ->landscape()
                ->setOption('margin.top', '2cm')
                ->pages('1-3')
                ->paperSize(210, 148)
                ->createPdfCommand('screenshot.pdf');
    
    opened by rydurham 5
  • Dismiss dialogs feature.

    Dismiss dialogs feature.

    Javascript dialog pop up such as alert, prompt, confirm cause rendering of the site to stop what leads to being unable to take a screenshot. dismissDialogs() method automatically close such popups allowing the screenshot to be taken.

    opened by code2prog 5
  • Allow the use of the 'omitBackground' option when capturing screenshots

    Allow the use of the 'omitBackground' option when capturing screenshots

    This PR uses the showBackground value in the Browsershot class to dictate whether or not Puppeteer's omitBackground option should be set when capturing screenshots.

    This could potentially be seen as a breaking change because the showBackground value defaults to false, which means that this flag might be set for users without them wanting it to be there.

    I will send a separate PR for the setOption idea.

    Thanks! ~Ryan

    opened by rydurham 5
  • Fixed issue Error: Request is already handled! in NodeJs v17.8.0

    Fixed issue Error: Request is already handled! in NodeJs v17.8.0

    Fixes this error that happens when using blockUrls() with NodeJs v17.8.0:

    Exit Code: 1(General error)
    
    Working directory: /root/browsershot
    
    Output:
    ================
    
    
    Error Output:
    ================
    /root/node_modules/puppeteer/lib/cjs/puppeteer/common/assert.js:26
            throw new Error(message);
                  ^
    
    Error: Request is already handled!
        at assert (/root/node_modules/puppeteer/lib/cjs/puppeteer/common/assert.js:26:15)
        at HTTPRequest.continue (/root/node_modules/puppeteer/lib/cjs/puppeteer/common/HTTPRequest.js:304:32)
        at /root/browsershot/vendor/spatie/browsershot/bin/browser.js:143:40
        at /root/node_modules/puppeteer/lib/cjs/puppeteer/common/Page.js:219:52
        at processTicksAndRejections (node:internal/process/task_queues:96:5)
        at async HTTPRequest.finalizeInterceptions (/root/node_modules/puppeteer/lib/cjs/puppeteer/common/HTTPRequest.js:151:9)
    
    Node.js v17.8.0
     in /root/browsershot/vendor/spatie/browsershot/src/Browsershot.php:824
    Stack trace:
    #0 /root/browsershot/vendor/spatie/browsershot/src/Browsershot.php(533): Spatie\Browsershot\Browsershot->callBrowser()
    #1 /root/browsershot/test.php(45): Spatie\Browsershot\Browsershot->save()
    #2 {main}
      thrown in /root/browsershot/vendor/spatie/browsershot/src/Browsershot.php on line 824
    
    

    After thix fix on browser.js it works fine:

    root@server:~/browsershot# php -f test.php https://www.google.com
    Screenshot created successfully!
    
    opened by webaddicto 4
  • PHPUnit to Pest Converter

    PHPUnit to Pest Converter

    This pull request contains changes for migrating your test suite from PHPUnit to Pest automated by the Pest Converter.

    Before merging, you need to:

    • Checkout the shift-57949 branch
    • Review all of the comments below for additional changes
    • Run composer update to install Pest with your dependencies
    • Run vendor/bin/pest to verify the conversion
    opened by freekmurze 4
  • Introduce a selectorIndex to bypass querySelector restrictions.

    Introduce a selectorIndex to bypass querySelector restrictions.

    I would like to get the screenshot of the nth element on a page but document.querySelector cannot handle eq:(xx) like

    document.querySelector('body:eq(0)')
    

    The solution would be to use

    document.querySelectorAll('body')[0]
    
    opened by evrpress 4
  • Node & NPM Permission Errors

    Node & NPM Permission Errors

    Hi,

    I was looking to get some insight on why Browsershot is struggling to use node and npm.

    To give you a bit of background, the machine is running Ubuntu 22.04, with Laravel , InertiaJS and VueJS. The machine is on a corporate network so we as installed by a root account and we were given a "sudo" account.

    We install node with NVM from the "sudo" account and up to this point we haven't had any issues with node or npm.

    The error I'm getting is as below. The command "PATH=$PATH:/usr/local/bin:/opt/homebrew/bin NODE_PATH=/home/infosec/.nvm/versions/node/v16.17.1/bin/node /home/infosec/.nvm/versions/node/v16.17.1/bin/npm root -g /home/infosec/.nvm/versions/node/v16.17.1/bin/node '/var/www/CSAPortal_Production/vendor/spatie/browsershot/src/../bin/browser.js' '{"url":"file:\/\/\/tmp\/568908599-0033634001671026490\/index.html","action":"pdf","options":{"path":"test.pdf","args":[],"viewport":{"width":800,"height":600},"displayHeaderFooter":false}}'" failed. Exit Code: 126(Invoked command cannot execute) Working directory: /var/www/CSAPortal_Production/public Output: ================ Error Output: ================ sh: 1: /home/infosec/.nvm/versions/node/v16.17.1/bin/node: Permission denied sh: 1: /home/infosec/.nvm/versions/node/v16.17.1/bin/node: Permission denied

    I had to manually set the node binary and npm binary as Browsershot wasn't picking them up automatically. `$html = view('pdf.report')->render();

        Browsershot::html($html)->setNodeBinary('/home/infosec/.nvm/versions/node/v16.17.1/bin/node')->setNpmBinary('/home/infosec/.nvm/versions/node/v16.17.1/bin/npm')->save('test.pdf');`
    

    Any help would be appreciated.

    Thanks, Nathan

    opened by ZERODayZServers 0
  • Security fix: Patch local file read bypass through untrusted js imports

    Security fix: Patch local file read bypass through untrusted js imports

    Hi Freek !

    In this patch, the user can define secure URL's in a whitelist. This will prevent an attacker from embedding malicious JS from arbitrary domains.

    security-fix.mp4

    Regards.

    opened by Retr02332 4
  • Add an Option to inject pagedjs polyfill

    Add an Option to inject pagedjs polyfill

    While paged.js works well when it's directly included in the head tag of the Site when it's added via script injection ($browser->setOption('addScriptTag', '{"url": "https://unpkg.com/pagedjs/dist/paged.polyfill.js"}')) there need to be done some evaluation a wait for a specific selector is added.

    Im not sure about the option setter, it might be better to support the json syntax from above so one could include a local path version of pagedjs as well. For our case using the remote one is fine, but i could change that if you'd prefer the other variant :)

    opened by mutschler 1
Releases(3.57.5)
  • 3.57.5(Dec 5, 2022)

    What's Changed

    • Add PHP 8.2 Tests Support by @patinthehat in https://github.com/spatie/browsershot/pull/688
    • Add Dependabot Automation by @patinthehat in https://github.com/spatie/browsershot/pull/689
    • Bump actions/checkout from 2 to 3 by @dependabot in https://github.com/spatie/browsershot/pull/690
    • Fixed exception message by @PHLAK in https://github.com/spatie/browsershot/pull/692

    New Contributors

    • @patinthehat made their first contribution in https://github.com/spatie/browsershot/pull/688
    • @dependabot made their first contribution in https://github.com/spatie/browsershot/pull/690
    • @PHLAK made their first contribution in https://github.com/spatie/browsershot/pull/692

    Full Changelog: https://github.com/spatie/browsershot/compare/3.57.4...3.57.5

    Source code(tar.gz)
    Source code(zip)
  • 3.57.4(Nov 21, 2022)

    What's Changed

    • Allow user to explicitly use a local file for html content. by @daum in https://github.com/spatie/browsershot/pull/687

    New Contributors

    • @daum made their first contribution in https://github.com/spatie/browsershot/pull/687

    Full Changelog: https://github.com/spatie/browsershot/compare/3.57.3...3.57.4

    Source code(tar.gz)
    Source code(zip)
  • 3.57.3(Oct 25, 2022)

  • 3.57.2(Aug 19, 2022)

    What's Changed

    • Prevent double request interception on POST by @JeppeKnockaert in https://github.com/spatie/browsershot/pull/664

    New Contributors

    • @JeppeKnockaert made their first contribution in https://github.com/spatie/browsershot/pull/664

    Full Changelog: https://github.com/spatie/browsershot/compare/3.57.1...3.57.2

    Source code(tar.gz)
    Source code(zip)
  • 3.57.1(Aug 3, 2022)

    What's Changed

    • Enable writeOptionsToFile for Windows by @moisish in https://github.com/spatie/browsershot/pull/660

    New Contributors

    • @moisish made their first contribution in https://github.com/spatie/browsershot/pull/660

    Full Changelog: https://github.com/spatie/browsershot/compare/3.57.0...3.57.1

    Source code(tar.gz)
    Source code(zip)
  • 3.57.0(Jun 28, 2022)

    What's Changed

    • Set custom temp path by @mtawil in https://github.com/spatie/browsershot/pull/648

    New Contributors

    • @mtawil made their first contribution in https://github.com/spatie/browsershot/pull/648

    Full Changelog: https://github.com/spatie/browsershot/compare/3.56.0...3.57.0

    Source code(tar.gz)
    Source code(zip)
  • 3.56.0(Jun 21, 2022)

  • 3.55.0(Jun 13, 2022)

    What's Changed

    • Add console messages method by @freekmurze in https://github.com/spatie/browsershot/pull/641

    Full Changelog: https://github.com/spatie/browsershot/compare/3.54.0...3.55.0

    Source code(tar.gz)
    Source code(zip)
  • 3.54.0(May 19, 2022)

    What's Changed

    • Added method setContentUrl to set url when using html method by @vitorsemeano in https://github.com/spatie/browsershot/pull/635

    Full Changelog: https://github.com/spatie/browsershot/compare/3.53.0...3.54.0

    Source code(tar.gz)
    Source code(zip)
  • 3.53.0(May 9, 2022)

    What's Changed

    • Add support for omitBackground by @Ugoku in https://github.com/spatie/browsershot/pull/629
    • Ability to set initial page Number for template Headers by @leonelvsc in https://github.com/spatie/browsershot/pull/632

    New Contributors

    • @Ugoku made their first contribution in https://github.com/spatie/browsershot/pull/629
    • @leonelvsc made their first contribution in https://github.com/spatie/browsershot/pull/632

    Full Changelog: https://github.com/spatie/browsershot/compare/3.52.6...3.53.0

    Source code(tar.gz)
    Source code(zip)
  • 3.52.6(Apr 6, 2022)

    What's Changed

    • Fixed issue Error: Request is already handled! in NodeJs v17.8.0 by @webaddicto in https://github.com/spatie/browsershot/pull/623

    Full Changelog: https://github.com/spatie/browsershot/compare/3.52.5...3.52.6

    Source code(tar.gz)
    Source code(zip)
  • 3.52.5(Apr 4, 2022)

    What's Changed

    • Update savePdf to comply with 50eae92 by @marksalmon in https://github.com/spatie/browsershot/pull/622

    New Contributors

    • @marksalmon made their first contribution in https://github.com/spatie/browsershot/pull/622

    Full Changelog: https://github.com/spatie/browsershot/compare/3.52.4...3.52.5

    Source code(tar.gz)
    Source code(zip)
  • 3.52.4(Apr 1, 2022)

    What's Changed

    • Improve exception output when output file is missing
    • Use function arguments for mobile and touch by @orkhanahmadov in https://github.com/spatie/browsershot/pull/610
    • Update Puppeteer GitHub link by @ioanschmitt in https://github.com/spatie/browsershot/pull/598
    • Add missing 'to' by @ioanschmitt in https://github.com/spatie/browsershot/pull/599
    • Fix typo by @noreason in https://github.com/spatie/browsershot/pull/604
    • PHPUnit to Pest Converter by @freekmurze in https://github.com/spatie/browsershot/pull/611

    New Contributors

    • @ioanschmitt made their first contribution in https://github.com/spatie/browsershot/pull/598
    • @noreason made their first contribution in https://github.com/spatie/browsershot/pull/604
    • @orkhanahmadov made their first contribution in https://github.com/spatie/browsershot/pull/610

    Full Changelog: https://github.com/spatie/browsershot/compare/3.52.3...3.52.4

    Source code(tar.gz)
    Source code(zip)
  • 3.52.3(Dec 17, 2021)

    What's Changed

    • Adding compatibility to Symfony 6 by @spackmat in https://github.com/spatie/browsershot/pull/589

    New Contributors

    • @spackmat made their first contribution in https://github.com/spatie/browsershot/pull/589

    Full Changelog: https://github.com/spatie/browsershot/compare/3.52.2...3.52.3

    Source code(tar.gz)
    Source code(zip)
  • 3.52.2(Dec 14, 2021)

    • Add debug output to vague CouldNotTakeBrowsershot exception

    Full Changelog: https://github.com/spatie/browsershot/compare/3.52.1...3.52.2

    Source code(tar.gz)
    Source code(zip)
  • 3.52.1(Nov 24, 2021)

    What's Changed

    • Fix Apple Silicon Path Issue by @aerni in https://github.com/spatie/browsershot/pull/581

    New Contributors

    • @aerni made their first contribution in https://github.com/spatie/browsershot/pull/581

    Full Changelog: https://github.com/spatie/browsershot/compare/3.52.0...3.52.1

    Source code(tar.gz)
    Source code(zip)
  • 3.52.0(Oct 26, 2021)

    What's Changed

    • Prevent unsuccessful response by @mikaelpopowicz in https://github.com/spatie/browsershot/pull/576

    New Contributors

    • @mikaelpopowicz made their first contribution in https://github.com/spatie/browsershot/pull/576

    Full Changelog: https://github.com/spatie/browsershot/compare/3.51.0...3.52.0

    Source code(tar.gz)
    Source code(zip)
  • 3.51.0(Oct 26, 2021)

    What's Changed

    • 🚀 Support PHP 8.1 by @Nielsvanpach in https://github.com/spatie/browsershot/pull/567
    • Fix incorrect method reference in README by @intrepidws in https://github.com/spatie/browsershot/pull/570

    New Contributors

    • @intrepidws made their first contribution in https://github.com/spatie/browsershot/pull/570

    Full Changelog: https://github.com/spatie/browsershot/compare/3.50.2...3.51.0

    Source code(tar.gz)
    Source code(zip)
  • 3.50.2(Sep 21, 2021)

  • 3.50.1(Aug 27, 2021)

  • 3.50.0(Aug 22, 2021)

  • 3.49.0(Aug 5, 2021)

  • 3.48.0(Jul 28, 2021)

  • 3.47.0(Jun 10, 2021)

  • 3.46.0(May 24, 2021)

  • 3.45.0(Apr 20, 2021)

  • 3.44.1(Apr 9, 2021)

  • 3.44.0(Feb 5, 2021)

  • 3.42.0(Jan 11, 2021)

  • 3.41.2(Dec 23, 2020)

Owner
Spatie
Webdesign agency based in Antwerp, Belgium
Spatie
Convert HTML to PDF using Webkit (QtWebKit)

wkhtmltopdf and wkhtmltoimage wkhtmltopdf and wkhtmltoimage are command line tools to render HTML into PDF and various image formats using the QT Webk

wkhtmltopdf 13k Jan 4, 2023
Laravel package to convert HTML to PDF, supporting multiple drivers.

eve/pdf-converter A Laravel package to help convert HTML to PDF. Supports multiple drivers. Requirements and Installation eve/pdf-converter requires L

eve.io 11 Feb 15, 2022
Convert HTML to PDF using Webkit (QtWebKit)

wkhtmltopdf and wkhtmltoimage wkhtmltopdf and wkhtmltoimage are command line tools to render HTML into PDF and various image formats using the QT Webk

wkhtmltopdf 13k Jan 9, 2023
Gravity PDF is a GPLv2-licensed WordPress plugin that allows you to automatically generate, email and download PDF documents using Gravity Forms.

Gravity PDF Gravity PDF is a GPLv2-licensed WordPress plugin that allows you to automatically generate, email and download PDF documents using the pop

Gravity PDF 90 Nov 14, 2022
Magento 2 Invoice PDF Generator - helps you to customize the pdf templates for Magento 2

Magento 2 Invoice PDF Generator - helps you to customize the pdf templates for Magento 2. If you have an enabled template and a default template for the store you need your template the system will print the pdf template.

EAdesign 64 Oct 18, 2021
A PHP tool that helps you write eBooks in markdown and convert to PDF.

Artwork by Eric L. Barnes and Caneco from Laravel News ❤️ . This PHP tool helps you write eBooks in markdown. Run ibis build and an eBook will be gene

Mohamed Said 1.6k Jan 2, 2023
HTML to PDF converter for PHP

Dompdf Dompdf is an HTML to PDF converter At its heart, dompdf is (mostly) a CSS 2.1 compliant HTML layout and rendering engine written in PHP. It is

null 9.3k Jan 1, 2023
PHP library generating PDF files from UTF-8 encoded HTML

mPDF is a PHP library which generates PDF files from UTF-8 encoded HTML. It is based on FPDF and HTML2FPDF (see CREDITS), with a number of enhancement

null 3.8k Jan 2, 2023
PHP library allowing thumbnail, snapshot or PDF generation from a url or a html page. Wrapper for wkhtmltopdf/wkhtmltoimage

Snappy Snappy is a PHP library allowing thumbnail, snapshot or PDF generation from a url or a html page. It uses the excellent webkit-based wkhtmltopd

KNP Labs 4.1k Dec 30, 2022
PHP library allowing PDF generation or snapshot from an URL or an HTML page. Wrapper for Kozea/WeasyPrint

PhpWeasyPrint PhpWeasyPrint is a PHP library allowing PDF generation from an URL or an HTML page. It's a wrapper for WeasyPrint, a smart solution help

Pontedilana 23 Oct 28, 2022
plugin de criação de PDF através do HTML fácil

pluginmpdf plugin de criação de PDF através do HTML Para inciar nosso pluginmpdf devemos instalar a lib abaixo. mPDF is a PHP library which generates

EAD TUTORIA 2 Mar 24, 2022
PHP library allowing thumbnail, snapshot or PDF generation from a url or a html page.

Snappy Snappy is a PHP library allowing thumbnail, snapshot or PDF generation from a url or a html page. It uses the excellent webkit-based wkhtmltopd

KNP Labs 4.1k Dec 30, 2022
Official clone of PHP library to generate PDF documents and barcodes

TCPDF PHP PDF Library Please consider supporting this project by making a donation via PayPal category Library author Nicola Asuni [email protected] co

Tecnick.com LTD 3.6k Jan 6, 2023
TCPDF - PHP PDF Library - https://tcpdf.org

tc-lib-pdf PHP PDF Library UNDER DEVELOPMENT (NOT READY) UPDATE: CURRENTLY ALL THE DEPENDENCY LIBRARIES ARE ALMOST COMPLETE BUT THE CORE LIBRARY STILL

Tecnick.com LTD 1.3k Dec 30, 2022
Pdf and graphic files generator library written in php

Information Examples Sample documents are in the "examples" directory. "index.php" file is the web interface to browse examples, "cli.php" is a consol

Piotr Śliwa 335 Nov 26, 2022
PdfParser, a standalone PHP library, provides various tools to extract data from a PDF file.

PdfParser Pdf Parser, a standalone PHP library, provides various tools to extract data from a PDF file. Website : https://www.pdfparser.org Test the A

Sebastien MALOT 1.9k Jan 2, 2023
Laravel Snappy PDF

Snappy PDF/Image Wrapper for Laravel 5 and Lumen 5.1 This package is a ServiceProvider for Snappy: https://github.com/KnpLabs/snappy. Wkhtmltopdf Inst

Barry vd. Heuvel 2.3k Jan 2, 2023
Sign PDF files with valid x509 certificate

Sign PDF files with valid x509 certificate Require this package in your composer.json and update composer. This will download the package and the depe

Lucas Nepomuceno 175 Jan 2, 2023
Generate simple PDF invoices with PHP

InvoiScript Generate simple PDF invoices with PHP. Installation Run: composer require mzur/invoiscript Usage Example use Mzur\InvoiScript\Invoice; re

Martin Zurowietz 16 Aug 24, 2022