Capturing Screenshots & PDFs

Browser Swarm enables you to capture high-quality screenshots and generate PDFs of web pages during your automated browser sessions. These features are essential for visual testing, documentation, and archiving purposes.


🖼️ Capturing Screenshots

You can capture screenshots using your preferred automation framework. For optimal performance and flexibility, we recommend using the Chrome DevTools Protocol (CDP).

Example with Playwright

import { chromium } from 'playwright-core';
import { BrowserSwarm } from 'browser-swarm-sdk';
import fs from 'fs';

const bs = new BrowserSwarm({ apiKey: process.env.BROWSER_SWARM_API_KEY });

(async () => {
  const session = await bs.sessions.create({
    projectId: process.env.BROWSER_SWARM_PROJECT_ID,
  });

  const browser = await chromium.connectOverCDP(session.connectUrl);
  const context = browser.contexts()[0];
  const page = context.pages()[0];

  await page.goto('https://example.com');

  const client = await context.newCDPSession(page);
  const { data } = await client.send('Page.captureScreenshot', {
    format: 'jpeg',
    quality: 80,
    fullPage: true,
  });

  const buffer = Buffer.from(data, 'base64');
  fs.writeFileSync('screenshot.jpeg', buffer);

  await browser.close();
})();


📝 Generating PDFs

Generating PDFs of web pages is straightforward with Browser Swarm. This is particularly useful for saving receipts, reports, or any page content in a portable format.

Example with Playwright

import { chromium } from 'playwright-core';
import { BrowserSwarm } from 'browser-swarm-sdk';
import fs from 'fs';

const bs = new BrowserSwarm({ apiKey: process.env.BROWSER_SWARM_API_KEY });

(async () => {
  const session = await bs.sessions.create({
    projectId: process.env.BROWSER_SWARM_PROJECT_ID,
  });

  const browser = await chromium.connectOverCDP(session.connectUrl);
  const context = browser.contexts()[0];
  const page = context.pages()[0];

  await page.goto('https://example.com');

  const pdfBuffer = await page.pdf({
    format: 'A4',
    printBackground: true,
  });

  fs.writeFileSync('page.pdf', pdfBuffer);

  await browser.close();
})();

💡 Best Practices

  • Use CDP for Performance: Leveraging the Chrome DevTools Protocol can result in faster and more reliable screenshot captures.

  • Full-Page Screenshots: Set fullPage: true to capture the entire scrollable area of the page.

  • PDF Formatting: Adjust the format parameter (e.g., 'A4', 'Letter') and set printBackground: true to include background graphics in PDFs.

  • Error Handling: Implement appropriate error handling to manage scenarios where page loading or rendering might fail.


By integrating these capabilities into your automation workflows, Browser Swarm enhances your ability to document and analyze web content effectively.

Last updated