Creating images | browsershot-rust | Spatie       

 SPATIE  

browsershot-rust
================

spatie.be/open-source

  [Docs](https://spatie.be/docs)  [Browsershot-rust](https://spatie.be/docs/browsershot-rust/v1)  Usage  Creating images

 Version   v1      

 Other versions for crawler [v1](https://spatie.be/docs/browsershot-rust/v1) 

  Creating images    
- [ Introduction ](https://spatie.be/docs/browsershot-rust/v1/introduction)
- [ Support us ](https://spatie.be/docs/browsershot-rust/v1/support-us)
- [ Requirements ](https://spatie.be/docs/browsershot-rust/v1/requirements)
- [ Installation &amp; setup ](https://spatie.be/docs/browsershot-rust/v1/installation-setup)
- [ Questions and issues ](https://spatie.be/docs/browsershot-rust/v1/questions-issues)
- [ Testing ](https://spatie.be/docs/browsershot-rust/v1/testing)
- [ Changelog ](https://spatie.be/docs/browsershot-rust/v1/changelog)
- [ About us ](https://spatie.be/docs/browsershot-rust/v1/about-us)

Usage
-----

- [ Introduction ](https://spatie.be/docs/browsershot-rust/v1/usage/introduction)
- [ Creating images ](https://spatie.be/docs/browsershot-rust/v1/usage/creating-images)
- [ Creating PDFs ](https://spatie.be/docs/browsershot-rust/v1/usage/creating-pdfs)
- [ Creating HTML ](https://spatie.be/docs/browsershot-rust/v1/usage/creating-html)

Miscellaneous options
---------------------

- [ Adding extra headers to every request ](https://spatie.be/docs/browsershot-rust/v1/miscellaneous-options/adding-extra-headers-to-every-request)
- [ Adding extra headers to the navigational request ](https://spatie.be/docs/browsershot-rust/v1/miscellaneous-options/adding-extra-headers-to-the-navigational-request)
- [ Changing the language of the browser ](https://spatie.be/docs/browsershot-rust/v1/miscellaneous-options/changing-the-language-of-the-browser)
- [ Changing the value of a dropdown ](https://spatie.be/docs/browsershot-rust/v1/miscellaneous-options/changing-the-value-of-a-dropdown)
- [ Clicking on the page ](https://spatie.be/docs/browsershot-rust/v1/miscellaneous-options/clicking-on-the-page)
- [ Connection to a remote chromium/chrome instance ](https://spatie.be/docs/browsershot-rust/v1/miscellaneous-options/connection-to-a-remote-chrome-instance)
- [ Disable sandboxing ](https://spatie.be/docs/browsershot-rust/v1/miscellaneous-options/disable-sandboxing)
- [ Fixing cors issues ](https://spatie.be/docs/browsershot-rust/v1/miscellaneous-options/fixing-cors-options)
- [ Getting console output ](https://spatie.be/docs/browsershot-rust/v1/miscellaneous-options/getting-console-ouput)
- [ Getting failed requests ](https://spatie.be/docs/browsershot-rust/v1/miscellaneous-options/getting-failed-requests)
- [ Ignore HTTPS errors ](https://spatie.be/docs/browsershot-rust/v1/miscellaneous-options/ignore-https-errors)
- [ Passing environment variables to the browser ](https://spatie.be/docs/browsershot-rust/v1/miscellaneous-options/passing-environment-variables-to-the-browser)
- [ Performance ](https://spatie.be/docs/browsershot-rust/v1/miscellaneous-options/performance)
- [ Prevent unsuccessful responses ](https://spatie.be/docs/browsershot-rust/v1/miscellaneous-options/prevent-unsuccessful-responses)
- [ Sending POST requests ](https://spatie.be/docs/browsershot-rust/v1/miscellaneous-options/sending-post-requests)
- [ Setting an arbitrary option ](https://spatie.be/docs/browsershot-rust/v1/miscellaneous-options/setting-an-arbirary-option)
- [ Setting the CSS media type of the page ](https://spatie.be/docs/browsershot-rust/v1/miscellaneous-options/setting-the-css-media-type-of-the-page)
- [ Setting the timeout ](https://spatie.be/docs/browsershot-rust/v1/miscellaneous-options/setting-the-timeout)
- [ Setting the user agent ](https://spatie.be/docs/browsershot-rust/v1/miscellaneous-options/setting-the-user-agent)
- [ Specifying-a-proxy-server ](https://spatie.be/docs/browsershot-rust/v1/miscellaneous-options/specifying-a-proxy-server)
- [ Typing on the page ](https://spatie.be/docs/browsershot-rust/v1/miscellaneous-options/typing-on-the-page)
- [ Using a pipe instead of a WebSocket ](https://spatie.be/docs/browsershot-rust/v1/miscellaneous-options/using-a-pipe-instead-of-a-websocket)
- [ Using cookies ](https://spatie.be/docs/browsershot-rust/v1/miscellaneous-options/using-cookies)
- [ Using HTTP Authentication ](https://spatie.be/docs/browsershot-rust/v1/miscellaneous-options/using-http-authentication)
- [ Using url for html content ](https://spatie.be/docs/browsershot-rust/v1/miscellaneous-options/using-url-for-html-content)
- [ Writing options to a file ](https://spatie.be/docs/browsershot-rust/v1/miscellaneous-options/writing-options-to-a-file)
- [ Disabling redirects ](https://spatie.be/docs/browsershot-rust/v1/miscellaneous-options/disabling-redirects)
- [ Read redirect history ](https://spatie.be/docs/browsershot-rust/v1/miscellaneous-options/read-redirect-history)
- [ Evaluating a script before page load ](https://spatie.be/docs/browsershot-rust/v1/miscellaneous-options/evaluating-a-script-before-page-load)

 Creating images
===============

###  On this page 

1. [ Formatting the image ](#content-formatting-the-image)
2. [ Sizing the image ](#content-sizing-the-image)
3. [ Manipulating the image ](#content-manipulating-the-image)
4. [ Taking a full page screenshot ](#content-taking-a-full-page-screenshot)
5. [ Setting the device scale ](#content-setting-the-device-scale)
6. [ Mobile emulation ](#content-mobile-emulation)
7. [ Device emulation ](#content-device-emulation)
8. [ Backgrounds ](#content-backgrounds)
9. [ Dismiss dialogs ](#content-dismiss-dialogs)
10. [ Disable Javascript ](#content-disable-javascript)
11. [ Disable Images ](#content-disable-images)
12. [ Block Urls ](#content-block-urls)
13. [ Block Domains ](#content-block-domains)
14. [ Waiting for lazy-loaded resources ](#content-waiting-for-lazy-loaded-resources)
15. [ Delayed screenshots ](#content-delayed-screenshots)
16. [ Waiting for javascript function ](#content-waiting-for-javascript-function)
17. [ Waiting for a selector ](#content-waiting-for-a-selector)
18. [ Adding JS ](#content-adding-js)
19. [ Adding CSS ](#content-adding-css)
20. [ Output directly to the browser ](#content-output-directly-to-the-browser)
21. [ Setting the user data directory ](#content-setting-the-user-data-directory)

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

```
Browsershot::url("https://example.com").save(path_to_image)?;
```

Formatting the image
--------------------------------------------------------------------------------------------------------------------

By default, the screenshot's type will be a `png`. But you can change it to `jpeg` with quality option.

```
Browsershot::url("https://example.com")
    .set_screenshot_type("jpeg", Some(100))
    .save(path_to_image)?;
```

Sizing the image
--------------------------------------------------------------------------------------------------------

By default the screenshot's size is 800 by 600 pixels. Want another size of screenshot? No problem!

```
Browsershot::url("https://example.com")
    .window_size(640, 480)
    .save(path_to_image)?;
```

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

```
Browsershot::url("https://example.com")
    .clip(x, y, width, height)
    .save(path_to_image)?;
```

You can take a screenshot of an element matching a selector using `select` and a `selector_index` which is used to select the nth element (e.g. use `selector_index = 3` to get the fourth element like `div:eq(3)`). Pass `0` for the first matching element.

```
Browsershot::url("https://example.com")
    .select(".some-selector", selector_index)
    .save(path_to_image)?;
```

### Getting a screenshot as base64

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

```
let base64_data = Browsershot::url("https://example.com")
    .base64_screenshot()?;
```

Manipulating the image
--------------------------------------------------------------------------------------------------------------------------

Image manipulation uses Rust's [image](https://docs.rs/image) crate. Here's an example where we create a greyscale image:

```
Browsershot::url("https://example.com")
    .window_size(640, 480)
    .greyscale()
    .save(path_to_image)?;
```

For other transformations, pass an image transformation function to `manipulate`. It receives and returns an `image::DynamicImage`. Transformations run in order and apply to both file and in-memory screenshots.

Taking a full page screenshot
-----------------------------------------------------------------------------------------------------------------------------------------------

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

```
Browsershot::url("https://example.com")
    .full_page()
    .save(path_to_image)?;
```

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")
    .device_scale_factor(2)
    .save(path_to_image)?;
```

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 `user_agent` method, these can be used to effectively take a mobile screenshot of the page.

```
Browsershot::url("https://example.com")
    .user_agent("My Mobile Browser 1.0")
    .mobile()
    .touch()
    .save(path_to_image)?;
```

Device emulation
--------------------------------------------------------------------------------------------------------

You can emulate a device view with the `device` method. The devices' names can be found [Here](https://github.com/puppeteer/puppeteer/blob/main/docs/api/puppeteer.knowndevices.md).

```
let browsershot = Browsershot::url("https://example.com");
browsershot
        .device("iPhone X")
        .save(path_to_image)?;
```

is the same as

```
Browsershot::url("https://example.com")
    .user_agent("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")
    .window_size(375, 812)
    .device_scale_factor(3)
    .mobile()
    .touch()
    .landscape(false)
    .save(path_to_image)?;
```

Backgrounds
-----------------------------------------------------------------------------------------

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

```
Browsershot::url("https://example.com")
    .hide_background()
    .save(path_to_image)?;
```

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 `dismiss_dialogs()` method automatically closes such popups allowing the screenshot to be taken.

```
Browsershot::url("https://example.com")
    .dismiss_dialogs()
    .save(path_to_image)?;
```

Disable Javascript
--------------------------------------------------------------------------------------------------------------

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

```
Browsershot::url("https://example.com")
    .disable_javascript()
    .save(path_to_image)?;
```

Disable Images
--------------------------------------------------------------------------------------------------

You can completely remove all images and ![]() elements when capturing a page using the `disable_images()` method.

```
Browsershot::url("https://example.com")
    .disable_images()
    .save(path_to_image)?;
```

Block Urls
--------------------------------------------------------------------------------------

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

```
let urls_list = ["example.com/cm-notify?pi=outbrain", "sync.outbrain.com/cookie-sync?p=bidswitch"];
Browsershot::url("https://example.com")
    .block_urls(urls_list)
    .save(path_to_image)?;
```

Block Domains
-----------------------------------------------------------------------------------------------

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

```
let domains_list = ["googletagmanager.com", "googlesyndication.com", "doubleclick.net", "google-analytics.com"];
Browsershot::url("https://example.com")
    .block_domains(domains_list)
    .save(path_to_image)?;
```

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 `wait_until_network_idle(true)` 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")
    .wait_until_network_idle(true)
    .save(path_to_image)?;
```

Alternatively you can use less strict `wait_until_network_idle(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 `set_delay()`. 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")
    .set_delay(delay_in_milliseconds)
    .save(path_to_image)?;
```

Waiting for javascript function
-----------------------------------------------------------------------------------------------------------------------------------------------------

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

```
Browsershot::url("https://example.com")
    .wait_for_function("window.innerWidth < 100", Polling::Interval(Duration::from_millis(polling_in_milliseconds)), Duration::from_millis(timeout_in_milliseconds))
    .save(path_to_image)?;
```

Waiting for a selector
--------------------------------------------------------------------------------------------------------------------------

You can also wait for a selector by using `wait_for_selector()`. This is useful if you need to wait for the selector to appear in page.

```
Browsershot::url("https://example.com")
    .wait_for_selector("#my_selector")
    .save(path_to_image)?;
```

Adding JS
-----------------------------------------------------------------------------------

You can add javascript prior to your screenshot or output using the syntax for [Puppeteer's addScriptTag](https://github.com/puppeteer/puppeteer/blob/v1.9.0/docs/api.md#pageaddscripttagoptions).

```
Browsershot::url("https://example.com")
    .set_option("addScriptTag", json!({"content" : "alert(\"Hello World\")"}))
    .save(path_to_image)?;
```

Adding CSS
--------------------------------------------------------------------------------------

You can add CSS styles prior to your screenshot or output using the syntax for [Puppeteer's addStyleTag](https://github.com/puppeteer/puppeteer/blob/v1.9.0/docs/api.md#pageaddstyletagoptions).

```
Browsershot::url("https://example.com")
    .set_option("addStyleTag", json!({"content" : "body{ font-size: 14px; }"}))
    .save(path_to_image)?;
```

Output directly to the browser
--------------------------------------------------------------------------------------------------------------------------------------------------

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

```
let image = Browsershot::url("https://example.com").screenshot()?;
```

Setting the user data directory
-----------------------------------------------------------------------------------------------------------------------------------------------------

You can set the [user data directory](https://chromium.googlesource.com/chromium/src/+/refs/heads/main/docs/user_data_dir.md) that is used to store the browser session and additional data. Setting this to a static value may introduce cache problems, could also increase performance. It needs to be an absolute path.

```
let image = Browsershot::url("https://example.com")
    .user_data_dir("/tmp/session-1")
    .screenshot()?;
```

 A good
match?
-------------

### What we do best

- All things Laravel
- Custom frontend components
- Building APIs
- AI-powered features
- Simplifying things
- Clean solutions
- Integrating services

### Not our cup of tea

- WordPress themes
- Cutting corners
- Free mockups to win a job
- "Just execute the briefing"

 In short: we'd like to be a **substantial part** of your project.

 [ Get in touch via email ](mailto:info@spatie.be?subject=A%20good%20match%21&body=Tell%20us%20as%20much%20as%20you%20can%20about%0A-%20your%20online%20project%0A-%20your%20planning%0A-%20your%20budget%0A-%20%E2%80%A6%0A%0AAnything%20that%20helps%20us%20to%20start%20straightforward%21)
