Skip to content

API reference

Generated from the source. Everything listed here is public and covered by semantic versioning; modules whose names start with _ are not.

Clients

website2pdf.Client

Client(
    *,
    pdf_options: PdfOptions | None = None,
    browser_options: BrowserOptions | None = None,
    render_options: RenderOptions | None = None,
)

Convert web pages and local HTML files to PDF with headless Chromium.

The browser is started once and reused across conversions; each conversion runs in its own browser context, so cookies and storage never leak between pages.

Use it as a context manager so the browser is always torn down:

with Client() as client:
    pdf = client.convert("https://example.com")

Calling convert() on a client that has not been started will start it implicitly, in which case close() is the caller's responsibility.

Note

Playwright's synchronous driver runs an event loop on the calling thread, so asyncio.run() will fail on that thread while a client is open. In an asyncio program use AsyncClient instead. Several Client instances on one thread are fine: they share one reference-counted driver.

Configure the defaults applied to every conversion.

Parameters:

Name Type Description Default
pdf_options PdfOptions | None

Default PDF rendering options.

None
browser_options BrowserOptions | None

Browser launch and context options.

None
render_options RenderOptions | None

Default navigation and waiting options.

None

is_running property

is_running: bool

Whether the browser is currently started.

start

start() -> None

Start the browser if it is not already running.

Calling this on a running client is a no-op rather than an error, so a client can be started and stopped repeatedly.

Raises:

Type Description
BrowserNotInstalledError

If the Chromium binary is missing.

BrowserLaunchError

If Chromium is present but will not start.

close

close() -> None

Shut the browser down. Safe to call more than once.

convert

convert(
    target: str | Path,
    dest: None = None,
    *,
    pdf_options: PdfOptions | None = None,
    render_options: RenderOptions | None = None,
) -> bytes
convert(
    target: str | Path,
    dest: str | Path,
    *,
    pdf_options: PdfOptions | None = None,
    render_options: RenderOptions | None = None,
) -> Path
convert(
    target: str | Path,
    dest: str | Path | None = None,
    *,
    pdf_options: PdfOptions | None = None,
    render_options: RenderOptions | None = None,
) -> bytes | Path

Render a single page to PDF.

Parameters:

Name Type Description Default
target str | Path

URL, file:// URL, or path to a local HTML file.

required
dest str | Path | None

Where to write the PDF. When omitted the PDF is returned as bytes. May be a file name, a name containing {title}, or an existing directory.

None
pdf_options PdfOptions | None

Overrides this client's PDF options for this call.

None
render_options RenderOptions | None

Overrides this client's render options for this call.

None

Returns:

Type Description
bytes | Path

The PDF bytes when dest is omitted, otherwise the path written.

Raises:

Type Description
InvalidTargetError

If target is not a usable URL or file.

NavigationError

If the page could not be loaded.

RenderError

If the page could not be printed.

convert_many

convert_many(
    targets: Iterable[str | Path],
    dest_dir: None = None,
    *,
    filename_template: str = DEFAULT_TEMPLATE,
    pdf_options: PdfOptions | None = None,
    render_options: RenderOptions | None = None,
) -> list[bytes]
convert_many(
    targets: Iterable[str | Path],
    dest_dir: str | Path,
    *,
    filename_template: str = DEFAULT_TEMPLATE,
    pdf_options: PdfOptions | None = None,
    render_options: RenderOptions | None = None,
) -> list[Path]
convert_many(
    targets: Iterable[str | Path],
    dest_dir: str | Path | None = None,
    *,
    filename_template: str = DEFAULT_TEMPLATE,
    pdf_options: PdfOptions | None = None,
    render_options: RenderOptions | None = None,
) -> list[bytes] | list[Path]

Render several pages to PDF, one after another.

Pages that share a title do not overwrite each other; the second and later files gain a " (2)" suffix.

Parameters:

Name Type Description Default
targets Iterable[str | Path]

URLs or local HTML files.

required
dest_dir str | Path | None

Directory to write into. Created if missing. When omitted the PDFs are returned as bytes.

None
filename_template str

Name template for each file. {title} is the only supported placeholder.

DEFAULT_TEMPLATE
pdf_options PdfOptions | None

Overrides this client's PDF options for this call.

None
render_options RenderOptions | None

Overrides this client's render options for this call.

None

Returns:

Type Description
list[bytes] | list[Path]

A list of PDF bytes when dest_dir is omitted, otherwise the list

list[bytes] | list[Path]

of paths written, in input order.

website2pdf.AsyncClient

AsyncClient(
    *,
    pdf_options: PdfOptions | None = None,
    browser_options: BrowserOptions | None = None,
    render_options: RenderOptions | None = None,
    concurrency: int = DEFAULT_CONCURRENCY,
)

Convert web pages and local HTML files to PDF, concurrently.

Use it as an async context manager so the browser is always torn down:

async with AsyncClient() as client:
    pdfs = await client.convert_many(urls)

Concurrency is a property of the client rather than of a single call, because it caps how many browser contexts exist at once.

Configure the defaults applied to every conversion.

Parameters:

Name Type Description Default
pdf_options PdfOptions | None

Default PDF rendering options.

None
browser_options BrowserOptions | None

Browser launch and context options.

None
render_options RenderOptions | None

Default navigation and waiting options.

None
concurrency int

Maximum number of pages rendered at the same time.

DEFAULT_CONCURRENCY

Raises:

Type Description
OptionsError

If concurrency is below one.

is_running property

is_running: bool

Whether the browser is currently started.

start async

start() -> None

Start the browser if it is not already running.

Calling this on a running client is a no-op rather than an error.

Raises:

Type Description
BrowserNotInstalledError

If the Chromium binary is missing.

BrowserLaunchError

If Chromium is present but will not start.

close async

close() -> None

Shut the browser down. Safe to call more than once.

convert async

convert(
    target: str | Path,
    dest: None = None,
    *,
    pdf_options: PdfOptions | None = None,
    render_options: RenderOptions | None = None,
) -> bytes
convert(
    target: str | Path,
    dest: str | Path,
    *,
    pdf_options: PdfOptions | None = None,
    render_options: RenderOptions | None = None,
) -> Path
convert(
    target: str | Path,
    dest: str | Path | None = None,
    *,
    pdf_options: PdfOptions | None = None,
    render_options: RenderOptions | None = None,
) -> bytes | Path

Render a single page to PDF.

Parameters:

Name Type Description Default
target str | Path

URL, file:// URL, or path to a local HTML file.

required
dest str | Path | None

Where to write the PDF. When omitted the PDF is returned as bytes. May be a file name, a name containing {title}, or an existing directory.

None
pdf_options PdfOptions | None

Overrides this client's PDF options for this call.

None
render_options RenderOptions | None

Overrides this client's render options for this call.

None

Returns:

Type Description
bytes | Path

The PDF bytes when dest is omitted, otherwise the path written.

Raises:

Type Description
InvalidTargetError

If target is not a usable URL or file.

NavigationError

If the page could not be loaded.

RenderError

If the page could not be printed.

convert_many async

convert_many(
    targets: Iterable[str | Path],
    dest_dir: None = None,
    *,
    filename_template: str = DEFAULT_TEMPLATE,
    pdf_options: PdfOptions | None = None,
    render_options: RenderOptions | None = None,
) -> list[bytes]
convert_many(
    targets: Iterable[str | Path],
    dest_dir: str | Path,
    *,
    filename_template: str = DEFAULT_TEMPLATE,
    pdf_options: PdfOptions | None = None,
    render_options: RenderOptions | None = None,
) -> list[Path]
convert_many(
    targets: Iterable[str | Path],
    dest_dir: str | Path | None = None,
    *,
    filename_template: str = DEFAULT_TEMPLATE,
    pdf_options: PdfOptions | None = None,
    render_options: RenderOptions | None = None,
) -> list[bytes] | list[Path]

Render several pages to PDF, up to concurrency at a time.

All pages are rendered before any file is written, so file names are assigned in input order and stay reproducible across runs. Pages that share a title do not overwrite each other; the second and later files gain a " (2)" suffix.

Parameters:

Name Type Description Default
targets Iterable[str | Path]

URLs or local HTML files.

required
dest_dir str | Path | None

Directory to write into. Created if missing. When omitted the PDFs are returned as bytes.

None
filename_template str

Name template for each file. {title} is the only supported placeholder.

DEFAULT_TEMPLATE
pdf_options PdfOptions | None

Overrides this client's PDF options for this call.

None
render_options RenderOptions | None

Overrides this client's render options for this call.

None

Returns:

Type Description
list[bytes] | list[Path]

A list of PDF bytes when dest_dir is omitted, otherwise the list

list[bytes] | list[Path]

of paths written, in input order.

Options

website2pdf.PdfOptions dataclass

PdfOptions(
    paper_format: PaperFormat | None = "A4",
    width: str | None = None,
    height: str | None = None,
    scale: float = 1.0,
    landscape: bool = False,
    margin: Margin | None = None,
    print_background: bool = True,
    prefer_css_page_size: bool = False,
    page_ranges: str | None = None,
    display_header_footer: bool = False,
    header_template: str | None = None,
    footer_template: str | None = None,
    outline: bool = False,
    tagged: bool = False,
)

How the loaded page is painted into a PDF.

Attributes:

Name Type Description
paper_format PaperFormat | None

Named paper size. Ignored when width or height is set.

width str | None

Explicit page width as a CSS length. Overrides paper_format.

height str | None

Explicit page height as a CSS length. Overrides paper_format.

scale float

Rendering scale between 0.1 and 2.0.

landscape bool

Whether to use landscape orientation.

margin Margin | None

Page margins. None leaves Chromium's default.

print_background bool

Whether to paint background graphics. Defaults to True because a page converted without its backgrounds rarely matches what the user saw.

prefer_css_page_size bool

Whether an @page size in the document's CSS wins over paper_format.

page_ranges str | None

Pages to emit, for example "1-3, 8". None emits all.

display_header_footer bool

Whether to render the header and footer templates.

header_template str | None

HTML for the page header.

footer_template str | None

HTML for the page footer.

outline bool

Whether to embed a document outline.

tagged bool

Whether to emit a tagged (accessible) PDF.

to_playwright

to_playwright() -> dict[str, Any]

Convert to keyword arguments for Playwright's page.pdf().

Returns:

Type Description
dict[str, Any]

Only the keys this object actually constrains, so Chromium's own

dict[str, Any]

defaults apply to everything else.

website2pdf.Margin dataclass

Margin(
    top: str = "0",
    right: str = "0",
    bottom: str = "0",
    left: str = "0",
)

Page margins, expressed in CSS units (px, in, cm, mm).

uniform classmethod

uniform(value: str) -> Margin

Build a margin with the same value on all four sides.

Parameters:

Name Type Description Default
value str

CSS length, for example "1cm".

required

Returns:

Type Description
Margin

A margin applying value to every side.

to_playwright

to_playwright() -> dict[str, str]

Convert to the mapping Playwright's page.pdf() expects.

Returns:

Type Description
dict[str, str]

A dict with top, right, bottom and left keys.

website2pdf.RenderOptions dataclass

RenderOptions(
    wait_until: WaitUntil = "load",
    timeout: float = DEFAULT_TIMEOUT_MS,
    emulate_media: MediaType | None = None,
    wait_for_selector: str | None = None,
    extra_wait: float = 0.0,
)

How navigation waits for the page to become ready.

Attributes:

Name Type Description
wait_until WaitUntil

Navigation milestone to wait for. "networkidle" is the safest choice for pages that fetch content after load.

timeout float

Navigation timeout in milliseconds. 0 disables it.

emulate_media MediaType | None

CSS media type to emulate. Chromium renders PDFs with print media by default; pass "screen" to reproduce the on-screen appearance instead.

wait_for_selector str | None

CSS selector to wait for before rendering.

extra_wait float

Additional idle time in milliseconds after the page is ready. A last resort for animations that cannot be observed.

website2pdf.BrowserOptions dataclass

BrowserOptions(
    headless: bool = True,
    args: tuple[str, ...] = (),
    executable_path: str | None = None,
    channel: str | None = None,
    launch_timeout: float = DEFAULT_TIMEOUT_MS,
    user_agent: str | None = None,
    viewport: tuple[int, int] | None = (1280, 720),
    device_scale_factor: float = 1.0,
    locale: str | None = None,
    timezone_id: str | None = None,
    ignore_https_errors: bool = False,
    extra_http_headers: Mapping[str, str] | None = None,
    http_credentials: tuple[str, str] | None = None,
    cookies: tuple[Mapping[str, Any], ...] = (),
)

How the browser process and its context are created.

Attributes:

Name Type Description
headless bool

Whether to run without a visible window.

args tuple[str, ...]

Extra Chromium command-line switches.

executable_path str | None

Path to a specific Chromium build.

channel str | None

Branded channel such as "chrome" or "msedge".

launch_timeout float

Milliseconds to wait for the browser to start.

user_agent str | None

Override for the User-Agent header.

viewport tuple[int, int] | None

Viewport size as (width, height). None disables the fixed viewport.

device_scale_factor float

Device pixel ratio.

locale str | None

BCP 47 locale, for example "it-IT".

timezone_id str | None

IANA timezone, for example "Europe/Rome".

ignore_https_errors bool

Whether to accept invalid TLS certificates.

extra_http_headers Mapping[str, str] | None

Headers added to every request.

http_credentials tuple[str, str] | None

(username, password) for HTTP basic auth.

cookies tuple[Mapping[str, Any], ...]

Cookies installed on the context before navigation, in Playwright's cookie format.

to_launch_kwargs

to_launch_kwargs() -> dict[str, Any]

Convert to keyword arguments for playwright.chromium.launch().

Returns:

Type Description
dict[str, Any]

Only the keys this object constrains.

to_context_kwargs

to_context_kwargs() -> dict[str, Any]

Convert to keyword arguments for browser.new_context().

Returns:

Type Description
dict[str, Any]

Only the keys this object constrains.

Type aliases

website2pdf.options.PaperFormat module-attribute

PaperFormat = Literal[
    "Letter",
    "Legal",
    "Tabloid",
    "Ledger",
    "A0",
    "A1",
    "A2",
    "A3",
    "A4",
    "A5",
    "A6",
]

Paper sizes Chromium understands by name.

website2pdf.options.WaitUntil module-attribute

WaitUntil = Literal[
    "commit", "domcontentloaded", "load", "networkidle"
]

Navigation milestone to wait for before rendering.

website2pdf.options.MediaType module-attribute

MediaType = Literal['print', 'screen']

CSS media type to emulate.

Exceptions

website2pdf.WebSite2PDFError

Bases: Exception

Base class for every error raised by this library.

website2pdf.BrowserNotInstalledError

BrowserNotInstalledError(browser: str = 'chromium')

Bases: WebSite2PDFError

The Playwright browser binary has not been downloaded yet.

Build the error with an actionable install hint.

Parameters:

Name Type Description Default
browser str

Name of the missing Playwright browser.

'chromium'

website2pdf.BrowserLaunchError

Bases: WebSite2PDFError

The browser is installed but could not be started.

website2pdf.InvalidTargetError

Bases: WebSite2PDFError

The target is neither a supported URL nor an existing local file.

website2pdf.NavigationError

Bases: WebSite2PDFError

The page could not be loaded within the configured timeout.

website2pdf.RenderError

Bases: WebSite2PDFError

The page loaded but could not be painted into a PDF.

website2pdf.OptionsError

Bases: WebSite2PDFError, ValueError

An option value, or a combination of options, is invalid.