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
feat(tools): print page metadata in save_as_pdf header/footer
Saurav Pandaad8f3a4dd776
diff --git a/browser_use/tools/service.py b/browser_use/tools/service.pyindex 445de2cb6..a41083e61 100644--- a/browser_use/tools/service.py+++ b/browser_use/tools/service.py@@ -75,6 +75,24 @@ Context = TypeVar('Context')T = TypeVar('T', bound=BaseModel)+# Default header/footer templates for save_as_pdf, mirroring the metadata that+# Chrome's own Print dialog renders by default: the date in the header and the+# page URL + page numbers in the footer. Chrome injects values into elements+# bearing the magic classes `date`, `title`, `url`, `pageNumber` and `totalPages`.+# A font-size MUST be set explicitly — Chrome defaults header/footer text to 0px,+# so omitting it renders an invisible (blank) header/footer.+_DEFAULT_PDF_HEADER_TEMPLATE = (+ '<div style="font-size:9px; color:#666; width:100%; padding:0 0.4in; '+ 'box-sizing:border-box; text-align:right;"><span class="date"></span></div>'+)+_DEFAULT_PDF_FOOTER_TEMPLATE = (+ '<div style="font-size:9px; color:#666; width:100%; padding:0 0.4in; '+ 'box-sizing:border-box; display:flex; justify-content:space-between;">'+ '<span class="url"></span>'+ '<span><span class="pageNumber"></span> / <span class="totalPages"></span></span></div>'+)++# Global per-action timeout: last-resort guard against hung event handlers.# Individual CDP calls (Page.navigate etc.) have their own shorter timeouts,# but event-bus `await event` and `event_result()` calls have none — if a@@ -1558,16 +1576,41 @@ You will be given a query and the markdown of a webpage that has been filtered tcdp_session = await browser_session.get_or_create_cdp_session(focus=True)+ from cdp_use.cdp.page import PrintToPDFParameters++ pdf_params: PrintToPDFParameters = {+ 'printBackground': params.print_background,+ 'landscape': params.landscape,+ 'scale': params.scale,+ 'paperWidth': paper_width,+ 'paperHeight': paper_height,+ 'preferCSSPageSize': True,+ }++ if params.display_header_footer:+ # Chrome clips the header/footer unless the page leaves vertical room for+ # them, so set explicit margins. preferCSSPageSize only governs page size,+ # not margins, so these still apply. The horizontal margins keep the body+ # aligned with the header/footer content (which is padded to match).+ pdf_params.update(+ {+ 'displayHeaderFooter': True,+ 'headerTemplate': params.header_template+ if params.header_template is not None+ else _DEFAULT_PDF_HEADER_TEMPLATE,+ 'footerTemplate': params.footer_template+ if params.footer_template is not None+ else _DEFAULT_PDF_FOOTER_TEMPLATE,+ 'marginTop': 0.5,+ 'marginBottom': 0.5,+ 'marginLeft': 0.4,+ 'marginRight': 0.4,+ }+ )+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,- },+ params=pdf_params,session_id=cdp_session.session_id,),timeout=30.0,diff --git a/browser_use/tools/views.py b/browser_use/tools/views.pyindex 02b274ed9..65f41a129 100644--- a/browser_use/tools/views.py+++ b/browser_use/tools/views.py@@ -170,6 +170,30 @@ class SaveAsPdfAction(BaseModel):default='Letter',description='Paper size: Letter, Legal, A4, A3, or Tabloid',)+ display_header_footer: bool = Field(+ default=True,+ description=(+ 'Print page metadata into the margins, matching the browser Print dialog default: '+ 'the date in the header and the page URL plus page numbers in the footer. '+ 'Set to False for a clean PDF with no header/footer.'+ ),+ )+ header_template: str | None = Field(+ default=None,+ description=(+ 'Custom HTML for the page header. Inject values with spans using the classes '+ 'date, title, url, pageNumber, totalPages (e.g. \'<span class="title"></span>\'). '+ 'Set an explicit font-size or the text renders invisibly. Only used when '+ 'display_header_footer is True; defaults to showing the date.'+ ),+ )+ footer_template: str | None = Field(+ default=None,+ description=(+ 'Custom HTML for the page footer, same format as header_template. Only used when '+ 'display_header_footer is True; defaults to showing the page URL and page numbers.'+ ),+ )class GetDropdownOptionsAction(BaseModel):diff --git a/examples/features/save_as_pdf.py b/examples/features/save_as_pdf.pyindex 5b453e0d9..fd5f71658 100644--- a/examples/features/save_as_pdf.py+++ b/examples/features/save_as_pdf.py@@ -5,6 +5,11 @@ 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.+By default the PDF includes page metadata in the margins (just like Chrome's+Print dialog): the date in the header and the page URL plus page numbers in the+footer. Pass display_header_footer=False for a clean PDF, or supply custom+header_template / footer_template HTML to control exactly what's printed.+Setup:1. Get your API key from https://cloud.browser-use.com/new-api-key2. Set environment variable: export BROWSER_USE_API_KEY="your-key"diff --git a/tests/ci/test_action_save_as_pdf.py b/tests/ci/test_action_save_as_pdf.pyindex 05b3be969..5d20d8367 100644--- a/tests/ci/test_action_save_as_pdf.py+++ b/tests/ci/test_action_save_as_pdf.py@@ -256,6 +256,82 @@ class TestSaveAsPdf: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_header_footer_renders_url(self, tools, browser_session, http_server, base_url):+ """display_header_footer=True (the default) prints the page URL into the footer."""+ import pypdf++ page_url = f'{base_url}/pdf-test'+ await tools.navigate(url=page_url, 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='with-metadata',+ browser_session=browser_session,+ file_system=file_system,+ )++ pdf_path = _get_attachments(result)[0]+ assert await anyio.Path(pdf_path).exists()++ reader = pypdf.PdfReader(pdf_path)+ text_no_ws = ''.join(reader.pages[0].extract_text().split())++ # The footer metadata (page URL) should be embedded in the rendered PDF.+ expected = f'{http_server.host}:{http_server.port}/pdf-test'+ assert expected in text_no_ws, f'URL footer metadata not found in PDF text: {text_no_ws!r}'++ async def test_save_as_pdf_without_header_footer(self, tools, browser_session, http_server, base_url):+ """display_header_footer=False omits the URL/date metadata from the PDF."""+ import pypdf++ page_url = f'{base_url}/pdf-test'+ await tools.navigate(url=page_url, 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='no-metadata',+ display_header_footer=False,+ browser_session=browser_session,+ file_system=file_system,+ )++ pdf_path = _get_attachments(result)[0]+ assert await anyio.Path(pdf_path).exists()++ reader = pypdf.PdfReader(pdf_path)+ text_no_ws = ''.join(reader.pages[0].extract_text().split())++ # Page body never contains the URL, so it must not appear without the footer.+ netloc = f'{http_server.host}:{http_server.port}'+ assert netloc not in text_no_ws, f'URL leaked into PDF without header/footer: {text_no_ws!r}'++ async def test_save_as_pdf_custom_templates(self, tools, browser_session, base_url):+ """Custom header/footer templates are honored over the defaults."""+ import pypdf++ 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='custom-templates',+ header_template='<div style="font-size:12px;">CONFIDENTIAL DRAFT</div>',+ footer_template='<div style="font-size:12px;"><span class="title"></span></div>',+ browser_session=browser_session,+ file_system=file_system,+ )++ pdf_path = _get_attachments(result)[0]+ reader = pypdf.PdfReader(pdf_path)+ text_no_ws = ''.join(reader.pages[0].extract_text().split())++ assert 'CONFIDENTIALDRAFT' in text_no_ws, f'Custom header not found in PDF text: {text_no_ws!r}'+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@@ -268,9 +344,14 @@ class TestSaveAsPdf:assert 'landscape' in propsassert 'scale' in propsassert 'paper_format' in props+ assert 'display_header_footer' in props+ assert 'header_template' in props+ assert 'footer_template' in props# Check defaultsassert props['print_background']['default'] is Trueassert props['landscape']['default'] is Falseassert props['scale']['default'] == 1.0assert props['paper_format']['default'] == 'Letter'+ # Header/footer metadata is on by default, matching the browser Print dialog+ assert props['display_header_footer']['default'] is True