Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

pdf file creation supported.

mertunsall709569e3ab73
diff --git a/browser_use/controller/service.py b/browser_use/controller/service.py
index d493dcbba..69be01a65 100644
--- a/browser_use/controller/service.py
+++ b/browser_use/controller/service.py
@@ -743,7 +743,9 @@ Explain the content of the page and that the requested information is not availa
raise BrowserError(msg)
# File System Actions
- @self.registry.action('Write content to file_name in file system. Allowed extensions are .md, .txt, .json, .csv.')
+ @self.registry.action(
+ 'Write content to file_name in file system. Allowed extensions are .md, .txt, .json, .csv, .pdf. For .pdf files, write the content in markdown format and it will automatically be converted to a properly formatted PDF document.'
+ )
async def write_file(file_name: str, content: str, file_system: FileSystem):
result = await file_system.write_file(file_name, content)
logger.info(f'💾 {result}')
diff --git a/browser_use/filesystem/file_system.py b/browser_use/filesystem/file_system.py
index d3f513d5d..9e6777cb0 100644
--- a/browser_use/filesystem/file_system.py
+++ b/browser_use/filesystem/file_system.py
@@ -1,12 +1,12 @@
import asyncio
import re
import shutil
-import tempfile
from abc import ABC, abstractmethod
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from typing import Any
+from markdown_pdf import MarkdownPdf, Section
from pydantic import BaseModel, Field
INVALID_FILENAME_ERROR_MESSAGE = 'Error: Invalid filename format. Must be alphanumeric with supported extension.'
@@ -110,6 +110,27 @@ class CsvFile(BaseFile):
return 'csv'
+class PdfFile(BaseFile):
+ """PDF file implementation"""
+
+ @property
+ def extension(self) -> str:
+ return 'pdf'
+
+ def sync_to_disk_sync(self, path: Path) -> None:
+ file_path = path / self.full_name
+ try:
+ md_pdf = MarkdownPdf()
+ md_pdf.add_section(Section(self.content))
+ md_pdf.save(file_path)
+ except Exception as e:
+ raise FileSystemError(f"Error: Could not write to file '{self.full_name}'. {str(e)}")
+
+ async def sync_to_disk(self, path: Path) -> None:
+ with ThreadPoolExecutor() as executor:
+ await asyncio.get_event_loop().run_in_executor(executor, lambda: self.sync_to_disk_sync(path))
+
+
class FileSystemState(BaseModel):
"""Serializable state of the file system"""
@@ -138,6 +159,7 @@ class FileSystem:
'txt': TxtFile,
'json': JsonFile,
'csv': CsvFile,
+ 'pdf': PdfFile,
}
self.files = {}
@@ -422,6 +444,8 @@ class FileSystem:
file_obj = JsonFile(**file_info)
elif file_type == 'CsvFile':
file_obj = CsvFile(**file_info)
+ elif file_type == 'PdfFile':
+ file_obj = PdfFile(**file_info)
else:
# Skip unknown file types
continue
@@ -431,24 +455,3 @@ class FileSystem:
file_obj.sync_to_disk_sync(fs.data_dir)
return fs
-
-
-if __name__ == '__main__':
- # test to understand what model_dump() does
- md_file = MarkdownFile(name='test.md')
- md_file.update_content('Hello, world!')
- print(md_file.model_dump())
-
- # test to understand how state looks like
- tempdir = tempfile.gettempdir()
- fs = FileSystem(base_dir=Path(tempdir) / 'browseruse_test_data')
- print(fs.get_state())
- fs.nuke()
-
- # test to understand creating a filesystem, getting its state, and restoring it
- fs = FileSystem(base_dir=Path(tempdir) / 'browseruse_test_data')
- state = fs.get_state()
- print(state)
- fs2 = FileSystem.from_state(state)
- print(fs2.get_state())
- fs2.nuke()
diff --git a/pyproject.toml b/pyproject.toml
index 0cf222fda..86ba28ee9 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -41,6 +41,7 @@ dependencies = [
"google-auth-oauthlib>=1.2.2",
"mcp>=1.10.1",
"pypdf>=5.7.0",
+ "markdown-pdf>=1.7",
]
# google-api-core: only used for Google LLM APIs
# pyperclip: only used for examples that use copy/paste