Browser Automation API: Generate PDFs and Screenshots
In this article
Generating PDFs and screenshots with a browser automation API allows you to programmatically capture the visual state of a webpage, converting dynamic HTML, CSS, and JavaScript into static documents or images. This process is essential for creating automated invoices, archiving web content, generating social media preview images, or performing visual regression testing to ensure a website looks consistent across different updates. By using a headless browser—a web browser without a graphical user interface—you can trigger these captures via an API call, ensuring that the final output reflects exactly what a user would see in a standard browser window.
What You'll Need
- A Browser Automation API: This could be a managed cloud service (like Browserless, Puppeteer-as-a-Service) or a self-hosted library (like Puppeteer or Playwright).
- API Key or Endpoint: If using a cloud service, you will need an authentication token to authorize your requests.
- A Target URL: The specific web address you wish to capture.
- An HTTP Client: A tool to send requests to the API, such as cURL, Postman, or a programming language library (e.g., Axios for Node.js or Requests for Python).
- Basic Knowledge of JSON: Most automation APIs communicate using JSON for configuration and request bodies.
Step-by-Step
- Select Your Automation Method: Decide whether you want to manage the browser infrastructure yourself or use a hosted API. Self-hosting requires installing Chromium and managing memory/CPU usage, while a hosted API provides a REST endpoint where you simply send a URL and receive a file. For most production environments, a hosted API is preferred to avoid the overhead of managing "zombie" browser processes.
- Configure the Viewport Dimensions: Before capturing, you must define the screen size. A screenshot of a page at 1920x1080 will look different from one at 375x667 (mobile). In your API request, set the
widthandheightparameters. For "full-page" screenshots, many APIs offer afullPage: trueflag that automatically calculates the total scrollable height of the document. - Handle Authentication and Cookies: If the page you are capturing is behind a login wall, you cannot simply send the URL. You must either provide the API with session cookies, an authorization header, or a script that performs the login sequence (entering username and password) before the capture command is issued.
- Wait for Page Load and Rendering: Modern websites use lazy loading and asynchronous JavaScript. If you capture the page the instant the HTML loads, you may get a blank screen or a loading spinner. Use a "wait" command. Common options include
networkidle0(wait until there are no more than 0 network connections for 500ms) or waiting for a specific CSS selector to appear on the page. - Execute the Screenshot Command: Send the request to the
/screenshotendpoint. Specify the format (PNG or JPEG) and the quality. If you only need a specific part of the page, define a "clip" area using X and Y coordinates and the width and height of the element you want to isolate. - Execute the PDF Generation Command: Send the request to the
/pdfendpoint. Unlike screenshots, PDFs require print-specific settings. You must choose the page format (A4, Letter, etc.), the orientation (portrait or landscape), and whether to include background graphics. Ensure theprintBackgroundproperty is set to true if you want the CSS colors and images to appear in the PDF. - Process the API Response: The API will typically return the file as a binary stream or a Base64 encoded string. You must then save this data to a local file or upload it to a cloud storage bucket (like AWS S3 or Google Cloud Storage) to make it accessible to your users.
Common Mistakes
One of the most frequent errors is failing to account for Lazy Loading. Many modern sites only load images as the user scrolls down. If you request a full-page screenshot without first simulating a scroll to the bottom, the resulting image will have empty gaps where images should be. To fix this, use a custom script to scroll the page incrementally before triggering the capture.
Another common pitfall is ignoring CSS Media Queries. Browsers have different stylesheets for "screen" and "print". When generating a PDF, the browser defaults to the @media print stylesheet. If the website developer has hidden certain elements (like navigation bars or sidebars) for printing, those elements will be missing from your PDF. To bypass this, you can use the API to emulate the "screen" media type during PDF generation.
Memory Leaks are a significant issue for those self-hosting. Every browser instance consumes a large amount of RAM. If you do not explicitly close the browser context after the PDF is generated, the server will eventually run out of memory and crash. Always ensure your code includes a browser.close() or equivalent command in a finally block.
Tips
To get the highest quality screenshots, set the Device Scale Factor to 2 or 3. This emulates a Retina or High-DPI display, resulting in much sharper images that don't look pixelated when zoomed in. This is particularly useful for professional portfolios or product catalogs.
If you need to capture a page that requires a specific user interaction—such as clicking a "Show More" button or closing a popup—use Custom JS Injection. Most APIs allow you to send a snippet of JavaScript to be executed on the page before the capture. You can use this to remove annoying cookie banners or trigger specific UI states that are necessary for the final document.
For PDFs, utilize Page Margins. Default browser PDF generation often leaves awkward white borders. By setting the margins to 0 in your API configuration, you can create "edge-to-edge" PDFs that look like professionally designed documents rather than printed web pages.
Troubleshooting
The output is blank or shows a loading screen: This usually means the API captured the page before the JavaScript finished rendering the content. Increase your wait time or change your wait condition to networkidle2. If the page uses a heavy framework like React or Angular, you may need to wait for a specific element to be visible using a waitForSelector command.
Images are missing from the PDF: Check if the images are being loaded via a protocol that the browser doesn't support or if they are blocked by a Content Security Policy (CSP). Additionally, ensure printBackground: true is enabled, as many browsers disable background images by default to save ink during printing.
The screenshot is cut off or the wrong size: Verify that you aren't using a fixed height for a page with dynamic content. Instead of guessing the height, use the fullPage option. If the page uses a non-standard scrolling container (like a div with overflow: scroll), the fullPage flag may not work; in this case, you must manually calculate the height of that specific element and set the viewport accordingly.
API requests are timing out: Browser automation is resource-intensive. If the page is extremely large or has many external scripts, the default timeout (usually 30 seconds) may not be enough. Increase the timeout limit in your request headers or optimize the page by blocking unnecessary resources like ads and tracking scripts using a request interceptor.
Frequently Asked Questions
Can I capture a page that requires a login?
Yes, but you cannot simply provide the URL. You must either use the API to automate the login process (typing credentials and clicking submit) or pass existing session cookies/local storage tokens in the request header to mimic an authenticated session.
What is the difference between a screenshot and a PDF in this context?
A screenshot is a raster image (pixels) of exactly what is visible on the screen. A PDF is a document format that can preserve text as selectable vectors and can span multiple pages, though it is subject to the website's print CSS rules.
How do I remove a cookie banner before taking a screenshot?
The best method is to inject a small piece of JavaScript via the API that finds the cookie banner's CSS selector and sets its display property to none. This ensures the banner doesn't obstruct the content of your capture.
Which image format is better: PNG or JPEG?
PNG is generally better for browser captures because it is lossless and supports transparency, making text look crisp. JPEG is better if you are capturing high-resolution photographs and need a smaller file size, though text may appear slightly blurred.
Can I schedule these captures to happen automatically?
Yes, the API itself does not usually handle scheduling, but you can trigger the API call using a cron job, a GitHub Action, or a serverless function (like AWS Lambda) to capture pages at specific intervals.
Does the API handle mobile responsiveness?
Yes, by changing the viewport width and height to match a mobile device (e.g., 375x812 for iPhone X) and setting the isMobile flag to true, the browser will trigger the mobile version of the website's layout.