Can I generate PDFs of webpages using Playwright?

Yes, you can generate PDFs of webpages using Playwright. Playwright is a Node.js library that allows developers to automate browser tasks. It supports multiple browsers including Chrome, Firefox, and WebKit. One of the features provided by Playwright is the ability to generate a PDF of a webpage.

In the following example, I will illustrate how to generate a PDF of a webpage using Playwright in both Python and JavaScript.

Python

First, make sure to install the Playwright Python library using pip if you haven't already:

pip install playwright

Then you will need to run the playwright install command to download the browser binaries:

playwright install

Here's an example of how to generate a PDF using Playwright in Python:

from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()
    page.goto('http://example.com')
    page.pdf(path='example.pdf')
    browser.close()

In this script, we first launch a new browser instance. Then we create a new page in that browser and navigate to 'http://example.com'. Finally, we generate a PDF of the current page and save it to 'example.pdf'.

JavaScript

First, make sure to install the Playwright Node.js library using npm if you haven't already:

npm i playwright

Here's an example of how to generate a PDF using Playwright in JavaScript:

const playwright = require('playwright');

(async () => {
  const browser = await playwright.chromium.launch();
  const context = await browser.newContext();
  const page = await context.newPage();
  await page.goto('http://example.com');
  await page.pdf({ path: 'example.pdf', format: 'A4' });
  await browser.close();
})();

In this script, we first launch a new browser instance, then we create a new context, which is an isolated environment within the browser. Then we create a new page in that context and navigate to 'http://example.com'. Finally, we generate a PDF of the current page with an A4 format and save it to 'example.pdf'.

Related Questions

Get Started Now

WebScraping.AI provides rotating proxies, Chromium rendering and built-in HTML parser for web scraping
Icon