Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.
Python ai-agentsai-toolsbrowser-agentbrowser-automationbrowser-usecdpcloud-browsercomputer-useheadless-browserllmmcpplaywrightpythonremote-browserstealth-browserweb-automationweb-scraping
Add save_as_pdf agent action for CDP-based page-to-PDF export
Saurav Panda95215d621129
diff --git a/browser_use/tools/service.py b/browser_use/tools/service.pyindex 2b730a733..b20a49af4 100644--- a/browser_use/tools/service.py+++ b/browser_use/tools/service.py@@ -48,6 +48,7 @@ from browser_use.tools.views import (NavigateAction,NoParamsAction,ReadContentAction,+ SaveAsPdfAction,ScreenshotAction,ScrollAction,SearchAction,@@ -1417,6 +1418,96 @@ You will be given a query and the markdown of a webpage that has been filtered tmetadata={'include_screenshot': True},)+ # PDF Actions++ @self.registry.action(+ 'Save the current page as a PDF file. Returns the file path of the saved PDF. '+ 'Use this to capture the full page content (including content below the fold) as a printable document.',+ param_model=SaveAsPdfAction,+ )+ async def save_as_pdf(+ params: SaveAsPdfAction,+ browser_session: BrowserSession,+ file_system: FileSystem,+ ):+ """Save the current page as a PDF using CDP Page.printToPDF."""+ import base64+ import re++ # Paper format dimensions in inches (width, height)+ paper_sizes: dict[str, tuple[float, float]] = {+ 'letter': (8.5, 11),+ 'legal': (8.5, 14),+ 'a4': (8.27, 11.69),+ 'a3': (11.69, 16.54),+ 'tabloid': (11, 17),+ }++ paper_key = params.paper_format.lower()+ if paper_key not in paper_sizes:+ paper_key = 'letter'+ paper_width, paper_height = paper_sizes[paper_key]++ cdp_session = await browser_session.get_or_create_cdp_session(focus=True)++ result = await asyncio.wait_for(+ cdp_session.cdp_client.send.Page.printToPDF(+ params={+ 'printBackground': params.print_background,+ 'landscape': params.landscape,+ 'scale': params.scale,+ 'paperWidth': paper_width,+ 'paperHeight': paper_height,+ 'preferCSSPageSize': True,+ },+ session_id=cdp_session.session_id,+ ),+ timeout=30.0,+ )++ pdf_data = result.get('data')+ assert pdf_data, 'CDP Page.printToPDF returned no data'++ pdf_bytes = base64.b64decode(pdf_data)++ # Determine filename+ if params.file_name:+ file_name = params.file_name+ else:+ try:+ page_title = await asyncio.wait_for(browser_session.get_current_page_title(), timeout=2.0)+ safe_title = re.sub(r'[^\w\s-]', '', page_title).strip()[:50]+ file_name = safe_title if safe_title else 'page'+ except Exception:+ file_name = 'page'++ if not file_name.lower().endswith('.pdf'):+ file_name = f'{file_name}.pdf'+ file_name = FileSystem.sanitize_filename(file_name)++ file_path = file_system.get_dir() / file_name+ # Handle duplicate filenames+ if file_path.exists():+ base, ext = os.path.splitext(file_name)+ counter = 1+ while (file_system.get_dir() / f'{base} ({counter}){ext}').exists():+ counter += 1+ file_name = f'{base} ({counter}){ext}'+ file_path = file_system.get_dir() / file_name++ async with await anyio.open_file(file_path, 'wb') as f:+ await f.write(pdf_bytes)++ file_size = file_path.stat().st_size+ msg = f'Saved page as PDF: {file_name} ({file_size:,} bytes)'+ logger.info(f'📄 {msg}. Full path: {file_path}')++ return ActionResult(+ extracted_content=msg,+ long_term_memory=f'{msg}. Full path: {file_path}',+ attachments=[str(file_path)],+ )+# Dropdown Actions@self.registry.action(diff --git a/browser_use/tools/views.py b/browser_use/tools/views.pyindex 50275a421..9aec8fc0f 100644--- a/browser_use/tools/views.py+++ b/browser_use/tools/views.py@@ -141,6 +141,20 @@ class ScreenshotAction(BaseModel):)+class SaveAsPdfAction(BaseModel):+ file_name: str | None = Field(+ default=None,+ description='Output PDF filename (without path). Defaults to page title. Extension .pdf is added automatically if missing.',+ )+ print_background: bool = Field(default=True, description='Include background graphics and colors')+ landscape: bool = Field(default=False, description='Use landscape orientation')+ scale: float = Field(default=1.0, ge=0.1, le=2.0, description='Scale of the webpage rendering (0.1 to 2.0)')+ paper_format: str = Field(+ default='Letter',+ description='Paper size: Letter, Legal, A4, A3, or Tabloid',+ )++class ReadContentAction(BaseModel):"""Action for intelligent reading of long content."""diff --git a/examples/features/save_as_pdf.py b/examples/features/save_as_pdf.pynew file mode 100644index 000000000..5b453e0d9--- /dev/null+++ b/examples/features/save_as_pdf.py@@ -0,0 +1,46 @@+"""+Save any webpage as a PDF using the save_as_pdf action.++The agent can save the current page as a PDF at any point during a task.+Supports custom filenames, paper sizes (Letter, A4, Legal, A3, Tabloid),+landscape orientation, and background printing.++Setup:+1. Get your API key from https://cloud.browser-use.com/new-api-key+2. Set environment variable: export BROWSER_USE_API_KEY="your-key"+"""++import asyncio+import os+import sys++sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))++from dotenv import load_dotenv++load_dotenv()++from browser_use import Agent, ChatBrowserUse+++async def main():+ agent = Agent(+ task=(+ 'Go to https://news.ycombinator.com and save the front page as a PDF named "hackernews". '+ 'Then go to https://en.wikipedia.org/wiki/Web_browser and save just that article as a PDF in A4 format.'+ ),+ llm=ChatBrowserUse(model='bu-2-0'),+ )++ history = await agent.run()++ # Print paths of any PDF files the agent saved+ print('\nSaved files:')+ for result in history.action_results():+ if result.attachments:+ for path in result.attachments:+ print(f' {path}')+++if __name__ == '__main__':+ asyncio.run(main())diff --git a/tests/ci/test_action_save_as_pdf.py b/tests/ci/test_action_save_as_pdf.pynew file mode 100644index 000000000..05b3be969--- /dev/null+++ b/tests/ci/test_action_save_as_pdf.py@@ -0,0 +1,276 @@+import asyncio+import tempfile++import anyio+import pytest+from pytest_httpserver import HTTPServer++from browser_use.agent.views import ActionResult+from browser_use.browser import BrowserSession+from browser_use.browser.profile import BrowserProfile+from browser_use.filesystem.file_system import FileSystem+from browser_use.tools.service import Tools++[email protected](scope='session')+def http_server():+ server = HTTPServer()+ server.start()++ server.expect_request('/pdf-test').respond_with_data(+ """+ <!DOCTYPE html>+ <html>+ <head><title>PDF Test Page</title></head>+ <body>+ <h1>Hello PDF</h1>+ <p>This page should be saved as a PDF document.</p>+ <ul>+ <li>Item 1</li>+ <li>Item 2</li>+ <li>Item 3</li>+ </ul>+ </body>+ </html>+ """,+ content_type='text/html',+ )++ server.expect_request('/pdf-styled').respond_with_data(+ """+ <!DOCTYPE html>+ <html>+ <head>+ <title>Styled PDF Page</title>+ <style>+ body { background-color: #f0f0f0; font-family: sans-serif; }+ h1 { color: navy; }+ .highlight { background-color: yellow; padding: 10px; }+ </style>+ </head>+ <body>+ <h1>Styled Content</h1>+ <div class="highlight">This has a background color that should appear when print_background=True.</div>+ </body>+ </html>+ """,+ content_type='text/html',+ )++ yield server+ server.stop()++[email protected](scope='session')+def base_url(http_server):+ return f'http://{http_server.host}:{http_server.port}'++[email protected](scope='module')+async def browser_session():+ browser_session = BrowserSession(+ browser_profile=BrowserProfile(+ headless=True,+ user_data_dir=None,+ keep_alive=True,+ )+ )+ await browser_session.start()+ yield browser_session+ await browser_session.kill()++[email protected](scope='function')+def tools():+ return Tools()+++def _get_attachments(result: ActionResult) -> list[str]:+ """Helper to extract attachments with pyright-safe narrowing."""+ assert result.attachments is not None+ return result.attachments+++class TestSaveAsPdf:+ """Tests for the save_as_pdf action."""++ async def test_save_as_pdf_registered(self, tools):+ """save_as_pdf action is in the default action registry."""+ assert 'save_as_pdf' in tools.registry.registry.actions+ action = tools.registry.registry.actions['save_as_pdf']+ assert action.function is not None+ assert 'PDF' in action.description++ async def test_save_as_pdf_default_filename(self, tools, browser_session, base_url):+ """save_as_pdf with no filename uses the page title."""+ await tools.navigate(url=f'{base_url}/pdf-test', new_tab=False, browser_session=browser_session)+ await asyncio.sleep(0.5)++ with tempfile.TemporaryDirectory() as temp_dir:+ file_system = FileSystem(temp_dir)+ result = await tools.save_as_pdf(browser_session=browser_session, file_system=file_system)++ assert isinstance(result, ActionResult)+ assert result.extracted_content is not None+ assert 'Saved page as PDF' in result.extracted_content++ attachments = _get_attachments(result)+ assert len(attachments) == 1++ pdf_path = attachments[0]+ assert pdf_path.endswith('.pdf')+ assert await anyio.Path(pdf_path).exists()++ # Verify it's actually a PDF (starts with %PDF magic bytes)+ header = await anyio.Path(pdf_path).read_bytes()+ assert header[:5] == b'%PDF-', f'File does not start with PDF magic bytes: {header[:5]!r}'++ async def test_save_as_pdf_custom_filename(self, tools, browser_session, base_url):+ """save_as_pdf with a custom filename uses that name."""+ await tools.navigate(url=f'{base_url}/pdf-test', new_tab=False, browser_session=browser_session)+ await asyncio.sleep(0.5)++ with tempfile.TemporaryDirectory() as temp_dir:+ file_system = FileSystem(temp_dir)+ result = await tools.save_as_pdf(+ file_name='my-report',+ browser_session=browser_session,+ file_system=file_system,+ )++ assert isinstance(result, ActionResult)+ attachments = _get_attachments(result)+ assert len(attachments) == 1++ pdf_path = attachments[0]+ assert 'my-report.pdf' in pdf_path+ assert await anyio.Path(pdf_path).exists()++ async def test_save_as_pdf_custom_filename_with_extension(self, tools, browser_session, base_url):+ """save_as_pdf doesn't double the .pdf extension."""+ await tools.navigate(url=f'{base_url}/pdf-test', new_tab=False, browser_session=browser_session)+ await asyncio.sleep(0.5)++ with tempfile.TemporaryDirectory() as temp_dir:+ file_system = FileSystem(temp_dir)+ result = await tools.save_as_pdf(+ file_name='already.pdf',+ browser_session=browser_session,+ file_system=file_system,+ )++ assert isinstance(result, ActionResult)+ attachments = _get_attachments(result)+ pdf_path = attachments[0]+ # Should not be "already.pdf.pdf"+ assert pdf_path.endswith('already.pdf')+ assert not pdf_path.endswith('.pdf.pdf')++ async def test_save_as_pdf_duplicate_filename(self, tools, browser_session, base_url):+ """save_as_pdf increments filename when a duplicate exists."""+ await tools.navigate(url=f'{base_url}/pdf-test', new_tab=False, browser_session=browser_session)+ await asyncio.sleep(0.5)++ with tempfile.TemporaryDirectory() as temp_dir:+ file_system = FileSystem(temp_dir)++ # Save first PDF+ result1 = await tools.save_as_pdf(+ file_name='duplicate',+ browser_session=browser_session,+ file_system=file_system,+ )+ attachments1 = _get_attachments(result1)+ assert await anyio.Path(attachments1[0]).exists()+ assert attachments1[0].endswith('duplicate.pdf')++ # Save second PDF with same name+ result2 = await tools.save_as_pdf(+ file_name='duplicate',+ browser_session=browser_session,+ file_system=file_system,+ )+ attachments2 = _get_attachments(result2)+ assert await anyio.Path(attachments2[0]).exists()+ assert 'duplicate (1).pdf' in attachments2[0]++ async def test_save_as_pdf_landscape(self, tools, browser_session, base_url):+ """save_as_pdf with landscape=True produces a valid PDF."""+ await tools.navigate(url=f'{base_url}/pdf-test', new_tab=False, browser_session=browser_session)+ await asyncio.sleep(0.5)++ with tempfile.TemporaryDirectory() as temp_dir:+ file_system = FileSystem(temp_dir)+ result = await tools.save_as_pdf(+ file_name='landscape-test',+ landscape=True,+ browser_session=browser_session,+ file_system=file_system,+ )++ assert isinstance(result, ActionResult)+ attachments = _get_attachments(result)+ assert await anyio.Path(attachments[0]).exists()++ header = await anyio.Path(attachments[0]).read_bytes()+ assert header[:5] == b'%PDF-'++ async def test_save_as_pdf_a4_format(self, tools, browser_session, base_url):+ """save_as_pdf with paper_format='A4' produces a valid PDF."""+ await tools.navigate(url=f'{base_url}/pdf-test', new_tab=False, browser_session=browser_session)+ await asyncio.sleep(0.5)++ with tempfile.TemporaryDirectory() as temp_dir:+ file_system = FileSystem(temp_dir)+ result = await tools.save_as_pdf(+ file_name='a4-test',+ paper_format='A4',+ browser_session=browser_session,+ file_system=file_system,+ )++ assert isinstance(result, ActionResult)+ attachments = _get_attachments(result)+ assert await anyio.Path(attachments[0]).exists()++ async def test_save_as_pdf_with_background(self, tools, browser_session, base_url):+ """save_as_pdf with print_background=True on a styled page produces a valid PDF."""+ await tools.navigate(url=f'{base_url}/pdf-styled', new_tab=False, browser_session=browser_session)+ await asyncio.sleep(0.5)++ with tempfile.TemporaryDirectory() as temp_dir:+ file_system = FileSystem(temp_dir)+ result = await tools.save_as_pdf(+ file_name='styled-with-bg',+ print_background=True,+ browser_session=browser_session,+ file_system=file_system,+ )++ assert isinstance(result, ActionResult)+ attachments = _get_attachments(result)+ pdf_path = attachments[0]+ assert await anyio.Path(pdf_path).exists()++ # Verify file size is non-trivial (has actual rendered content)+ stat = await anyio.Path(pdf_path).stat()+ assert stat.st_size > 1000, f'PDF seems too small ({stat.st_size} bytes), may be empty'++ async def test_save_as_pdf_param_model_schema(self):+ """SaveAsPdfAction schema exposes the right fields with defaults."""+ from browser_use.tools.views import SaveAsPdfAction++ schema = SaveAsPdfAction.model_json_schema()+ props = schema['properties']++ assert 'file_name' in props+ assert 'print_background' in props+ assert 'landscape' in props+ assert 'scale' in props+ assert 'paper_format' in props++ # Check defaults+ assert props['print_background']['default'] is True+ assert props['landscape']['default'] is False+ assert props['scale']['default'] == 1.0+ assert props['paper_format']['default'] == 'Letter'