Skip to content

Commit c9e07b6

Browse files
committed
Add Tab.print_to_pdf
1 parent 275f285 commit c9e07b6

File tree

2 files changed

+24
-3
lines changed

2 files changed

+24
-3
lines changed

CHANGELOG.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1111

1212
### Added
1313

14-
- Added `tab.screenshot_b64` and `element.screenshot_b64` methods to return screenshot as base64 string @falmar
14+
- Added `Tab.screenshot_b64` and `Element.screenshot_b64` methods to return screenshot as base64 string @falmar
15+
- Added `Tab.print_to_pdf` to print the current page to a PDF file @stephanlensky
1516

1617
### Changed
1718

zendriver/core/tab.py

Lines changed: 22 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from __future__ import annotations
22

33
import asyncio
4+
import base64
45
import datetime
56
import logging
67
import pathlib
@@ -1381,14 +1382,33 @@ async def save_screenshot(
13811382

13821383
data = await self.screenshot_b64(format=format, full_page=full_page)
13831384

1384-
import base64
1385-
13861385
data_bytes = base64.b64decode(data)
13871386
if not path:
13881387
raise RuntimeError("invalid filename or path: '%s'" % filename)
13891388
path.write_bytes(data_bytes)
13901389
return str(path)
13911390

1391+
async def print_to_pdf(self, filename: PathLike, **kwargs: Any) -> pathlib.Path:
1392+
"""
1393+
Prints the current page to a PDF file and saves it to the specified path.
1394+
1395+
:param filename: The path where the PDF will be saved.
1396+
:param kwargs: Additional options for printing to be passed to :py:obj:`cdp.page.print_to_pdf`.
1397+
:return: The path to the saved PDF file.
1398+
:rtype: pathlib.Path
1399+
"""
1400+
filename = pathlib.Path(filename)
1401+
if filename.is_dir():
1402+
raise ValueError(
1403+
f"filename {filename} must be a file path, not a directory"
1404+
)
1405+
1406+
data, _ = await self.send(cdp.page.print_to_pdf(**kwargs))
1407+
1408+
data_bytes = base64.b64decode(data)
1409+
filename.write_bytes(data_bytes)
1410+
return filename
1411+
13921412
async def set_download_path(self, path: PathLike):
13931413
"""
13941414
sets the download path and allows downloads

0 commit comments

Comments
 (0)