### Set Up Pre-commit Hooks Source: https://stumpylog.github.io/gotenberg-client/latest/contributing Initializes pre-commit hooks using the 'prek install' command. This ensures code quality and consistency before committing changes. ```bash prek install ``` -------------------------------- ### AsyncMarkdownToPdfRoute Initialization and Context Management (Python) Source: https://stumpylog.github.io/gotenberg-client/0.12.0/ref_routes Demonstrates how to initialize the AsyncMarkdownToPdfRoute and use it within an asynchronous context manager. This setup is crucial for managing resources and ensuring proper cleanup. ```python from gotenberg_client._chromium.routes import AsyncMarkdownToPdfRoute from gotenberg_client.client import Client import logging async def example_usage(client: Client, log: logging.Logger): route = AsyncMarkdownToPdfRoute(client=client, route_url="/forms/chromium/convert/pdf", log=log) async with route: # Use route methods here pass ``` -------------------------------- ### Install Project Tools with uv Source: https://stumpylog.github.io/gotenberg-client/0.11.0/contributing Installs the 'hatch' and 'pre-commit' tools using the 'uv' package manager. These tools are essential for project management, testing, formatting, and maintaining code quality. ```shell uv tool install hatch pre-commit ``` -------------------------------- ### Set Up Pre-commit Hooks Source: https://stumpylog.github.io/gotenberg-client/0.11.0/contributing Initializes the pre-commit framework by installing the necessary Git hooks. These hooks run checks on code before each commit, ensuring code style and quality standards are met. ```shell pre-commit install ``` -------------------------------- ### Install Gotenberg Client with pip Source: https://stumpylog.github.io/gotenberg-client/0.10.0/usage This command installs the Gotenberg client library using pip. It's a prerequisite for using the library in your Python projects. ```bash pip install gotenberg-client ``` -------------------------------- ### Initialize Gotenberg Sync Screenshot Route Source: https://stumpylog.github.io/gotenberg-client/0.13.0/ref_routes Initializes the synchronous screenshot route for Gotenberg. It requires an HTTP client instance, the specific route URL, and a logger for recording operations. This setup is necessary before using the route. ```python def __init__(self, client: ClientT, route_url: str, log: logging.Logger) -> None: """Initialize a new BaseRoute instance. Parameters: ---------- client : ClientT The HTTP client used to connect to Gotenberg. route_url : str The URL of the specific Gotenberg route. log : Logger Logger for recording operations. """ pass ``` -------------------------------- ### Configure and Run Markdown to PDF Conversion Source: https://stumpylog.github.io/gotenberg-client/0.7.0/usage Provides an example of converting a Markdown file to a PDF with specific formatting options. It demonstrates chaining configuration methods like setting page size and including resources, followed by calling the .run() method. ```python from gotenberg_client import GotenbergClient from gotenberg_client.options import A4 with GotenbergClient("http://localhost:3000") as client: with client.chromium.markdown_to_pdf() as route: response = ( route.index("main.html") .markdown_file("readme.md") .size(A4) .resource("styles.css") .fail_on_exceptions() .run() ) # The 'response' variable will contain the httpx.Response object, # with the PDF content available in response.content ``` -------------------------------- ### Initialize GotenbergClient (Python) Source: https://stumpylog.github.io/gotenberg-client/0.5.0/usage Demonstrates the initialization of the GotenbergClient. It requires the host address of the Gotenberg server and accepts optional parameters for timeouts, logging level, and HTTP/2 usage. ```python class GotenbergClient: def __init__( self, host: str, *, timeout: float = 30.0, log_level: int = logging.ERROR, http2: bool = True, ): .... ``` -------------------------------- ### Configure and Run Markdown to PDF Route in Python Source: https://stumpylog.github.io/gotenberg-client/0.10.0/usage An example showcasing how to configure and run a markdown to PDF conversion route using the Gotenberg client. It demonstrates chaining multiple options like specifying input files, page size, and resource files before executing the route. ```python from gotenberg_client import GotenbergClient from gotenberg_client.options import A4 with GotenbergClient("http://localhost:3000") as client: with client.chromium.markdown_to_pdf() as route: response = ( route.index("main.html") .markdown_file("readme.md") .size(A4) .resource("styles.css") .fail_on_exceptions() .run() ) ``` -------------------------------- ### Install uv for Independent Tool Installations Source: https://stumpylog.github.io/gotenberg-client/0.13.1/contributing Installs the 'uv' tool, a fast Python package and environment manager, using a curl script. This is a prerequisite for managing project dependencies independently. ```shell curl -LsSf https://astral.sh/uv/install.sh | sh # Install uv ``` -------------------------------- ### Initialize Async HTML to PDF Route Source: https://stumpylog.github.io/gotenberg-client/0.11.0/ref_routes Initializes the `AsyncHtmlToPdfRoute` with necessary components for interacting with the Gotenberg API. It requires an HTTP client, the specific route URL, and a logger instance for tracking operations. This setup is fundamental for any route operation. ```python def __init__(self, client: ClientT, route_url: str, log: logging.Logger) -> None: """Initialize a new BaseRoute instance. Parameters: client: The HTTP client used to connect to Gotenberg. route_url: The URL of the specific Gotenberg route. log: Logger for recording operations. """ self.client = client self.route_url = route_url self.log = log ``` -------------------------------- ### Set up pre-commit hooks Source: https://stumpylog.github.io/gotenberg-client/0.9.0/contributing Installs the pre-commit git hooks for the project. These hooks run checks automatically before each commit, ensuring code style and quality standards are met. ```shell pre-commit install ``` -------------------------------- ### Install uv package manager Source: https://stumpylog.github.io/gotenberg-client/0.9.0/contributing Installs the 'uv' package manager using a curl script. 'uv' is used for independent tool installations within the project. This is a prerequisite for setting up the development environment. ```shell curl -LsSf https://astral.sh/uv/install.sh | sh # Install uv ``` -------------------------------- ### HTML to PDF Conversion Source: https://stumpylog.github.io/gotenberg-client/0.8.2/usage Shows an example of converting an HTML file to a PDF using the chromium module, including route configuration and execution. ```APIDOC ## HTML to PDF Conversion ### Description This example demonstrates converting an HTML file to a PDF using the `chromium.html_to_pdf` route. It shows how to select the module, the operation, configure route-specific options, and execute the conversion. ### Method POST ### Endpoint `/forms/chromium/convert/html ` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **files** (file) - The HTML file(s) to convert. - **inline_styles** (boolean) - Optional. Whether to inline CSS styles. - **markdown** (boolean) - Optional. Whether to treat HTML as markdown. - **base_url** (string) - Optional. The base URL for resolving relative paths in the HTML. - **extra_http_headers** (object) - Optional. Additional HTTP headers to send. - **wait_delay** (integer) - Optional. Delay in milliseconds before conversion. - **fail_on_exceptions** (boolean) - Optional. Whether to fail on rendering exceptions. - **emulated_device** (string) - Optional. Emulated device name for rendering. - **media_print** (boolean) - Optional. Whether to use print media type. - **prefer_css_page_size** (boolean) - Optional. Whether to prefer CSS page size. - **paper_width** (float) - Optional. Page width in centimeters. - **paper_height** (float) - Optional. Page height in centimeters. - **margin_top** (float) - Optional. Top margin in centimeters. - **margin_bottom** (float) - Optional. Bottom margin in centimeters. - **margin_left** (float) - Optional. Left margin in centimeters. - **margin_right** (float) - Optional. Right margin in centimeters. - **pdfa** (boolean) - Optional. Whether to output PDF/A format. - **pdfa_version** (string) - Optional. Version of PDF/A to output (e.g., "1b", "2b"). ### Request Example ```python from gotenberg_client import GotenbergClient from gotenberg_client.options import A4 with GotenbergClient("http://localhost:3000") as client: with client.chromium.html_to_pdf() as route: response = ( route.index("index.html") # Provide the HTML file .run() ) # For more complex options: with GotenbergClient("http://localhost:3000") as client: with client.chromium.html_to_pdf() as route: response = ( route.index("main.html") .fail_on_exceptions() .size(A4) .run() ) ``` ### Response #### Success Response (200) - **content** (bytes) - The resulting PDF file content. #### Response Example (Binary PDF content) ``` -------------------------------- ### Manage Route Context (Python) Source: https://stumpylog.github.io/gotenberg-client/0.11.0/ref_routes Implements context management for routes, allowing for proper setup and cleanup of resources. The `__enter__` method prepares the route for use, often resetting its state, while `__exit__` handles resource deallocation, ensuring cleanup even if exceptions occur. It requires `Optional` types for exception handling. ```python def __enter__(self) -> Self: """ Enter the context manager scope. Resets the route state and returns the route instance. """ pass ``` ```python def __exit__(self, exc_type: Optional[type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]) -> None: """ Exit the context manager scope. Performs cleanup by calling close() to release resources. """ pass ``` -------------------------------- ### Asynchronous Screenshot Route Initialization Source: https://stumpylog.github.io/gotenberg-client/0.11.0/ref_routes Initializes the asynchronous screenshot route for capturing web page screenshots. It requires an HTTP client, the specific route URL, and a logger instance. This setup is part of the asynchronous context management for screenshot operations. ```python def __init__(client: ClientT, route_url: str, log: logging.Logger) -> None: """ Initialize a new BaseRoute instance. Parameters: client (ClientT): The HTTP client used to connect to Gotenberg. route_url (str): The URL of the specific Gotenberg route. log (Logger): Logger for recording operations. """ # Implementation details would go here pass ``` -------------------------------- ### Use GotenbergClient as a Context Manager in Python Source: https://stumpylog.github.io/gotenberg-client/0.10.0/usage Illustrates the recommended way to use the GotenbergClient by leveraging a context manager. This ensures proper connection management and cleanup. The example shows accessing the chromium module to initiate an HTML to PDF conversion route. ```python from gotenberg_client import GotenbergClient with GotenbergClient("http://localhost:3000") as client: with client.chromium.html_to_pdf() as route: .... ``` -------------------------------- ### Convert HTML with Resources to PDF using Python Source: https://stumpylog.github.io/gotenberg-client/0.10 This example shows how to convert an HTML file to PDF while including additional resources like images and CSS. The `resource()` method is used to attach these files before running the conversion. The output is saved to a PDF file. Proper client and route management is crucial. ```python from gotenberg_client import GotenbergClient with GotenbergClient("http://localhost:3000") as client: with client.chromium.html_to_pdf() as route: response = route.index("my-index.html").resource("image.png").resource("style.css").run() response.to_file(Path("my-index.pdf")) ``` -------------------------------- ### Convert Markdown to PDF using GotenbergClient in Python Source: https://stumpylog.github.io/gotenberg-client/0.13.1/usage Provides an example of converting a Markdown file to a PDF using the Gotenberg client library. This snippet showcases route configuration chaining, including specifying input files, page size, and resources, before executing the conversion via the `.run()` method. The response is an `httpx.Response` object. ```python from gotenberg_client import GotenbergClient from gotenberg_client.constants import A4 with GotenbergClient("http://localhost:3000") as client: with client.chromium.markdown_to_pdf() as route: response = ( route.index("main.html") .markdown_file("readme.md") .size(A4) .resource("styles.css") .fail_on_exceptions() .run() ) ``` -------------------------------- ### Install uv Package Manager Source: https://stumpylog.github.io/gotenberg-client/0.11.0/contributing Installs the 'uv' package manager, a fast Python package installer and compiler. This is a prerequisite for managing project dependencies and tools independently. ```shell curl -LsSf https://astral.sh/uv/install.sh | sh ``` -------------------------------- ### AsyncMarkdownToPdfRoute - Setting Index File and Hiding Background (Python) Source: https://stumpylog.github.io/gotenberg-client/0.12.0/ref_routes Demonstrates setting the main HTML file for conversion and configuring the route to omit background graphics. This is fundamental for specifying the content to be converted and controlling visual elements. ```python from pathlib import Path from gotenberg_client._chromium.routes import AsyncMarkdownToPdfRoute from gotenberg_client.client import Client import logging async def set_index_and_hide_background(client: Client, log: logging.Logger): route = AsyncMarkdownToPdfRoute(client=client, route_url="/forms/chromium/convert/pdf", log=log) index_html_path = Path("/path/to/your/index.html") route.index(index=index_html_path) route.hide_background() # Further operations with the route... ``` -------------------------------- ### AsyncScreenshotFromUrlRoute - Initialization Source: https://stumpylog.github.io/gotenberg-client/0.11.0/ref_routes Initializes the Asynchronous ScreenshotFromUrlRoute with necessary client and logging configurations. ```APIDOC ## AsyncScreenshotFromUrlRoute Initialization ### Description Initializes a new instance of the `AsyncScreenshotFromUrlRoute`. This requires the HTTP client, the specific route URL, and a logger instance. ### Method `client.screenshot_from_url(url: str)` (Constructor wrapper) ### Endpoint (Specific to the screenshot route) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Assumes 'client' is an initialized Gotenberg client instance route = client.screenshot_from_url("https://example.com") ``` ### Response #### Success Response - **__init__** (None) - Initializes the route instance. ### Parameters during Initialization - **client** (ClientT) - The HTTP client for Gotenberg communication. - **route_url** (str) - The URL endpoint for the screenshot route. - **log** (logging.Logger) - Logger for recording route operations. ``` -------------------------------- ### Route Initialization and Cleanup Source: https://stumpylog.github.io/gotenberg-client/0.13.0/ref_routes Details on initializing and closing route instances, including asynchronous context management. ```APIDOC ## Route Initialization and Cleanup ### `__init__(client: ClientT, route_url: str, log: logging.Logger)` Initialize a new BaseRoute instance. #### Parameters - **client** (`ClientT`) - Required - The HTTP client used to connect to Gotenberg. - **route_url** (`str`) - Required - The URL of the specific Gotenberg route. - **log** (`logging.Logger`) - Required - Logger for recording operations. ### `__aexit__(exc_type: Optional[type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]) -> None` Exit the async context manager scope. Performs cleanup by calling close() to release resources. #### Parameters - **exc_type** (`Optional[type[BaseException]]`) - Required - The exception type, if an exception was raised. - **exc_val** (`Optional[BaseException]`) - Required - The exception instance, if an exception was raised. - **exc_tb** (`Optional[TracebackType]`) - Required - The traceback, if an exception was raised. ### `close() -> None` Close and clean up resources used by this route. This is an alias for reset(). ``` -------------------------------- ### Configure Split Span Source: https://stumpylog.github.io/gotenberg-client/0.12.0/ref_routes Sets the specific range or span for the document splitting operation, for example, defining page numbers like '1-3'. ```APIDOC ## POST /set/split_span ### Description Configures the splitting span for the route options, specifying the range of pages or intervals to split. ### Method POST ### Endpoint /set/split_span ### Parameters #### Query Parameters - **span** (str) - Required - The splitting span, e.g., '1-3' or '5,7'. ### Request Body *(No request body is typically sent for this configuration endpoint.)* ### Request Example ```json { "message": "Setting split span to 1-5." } ``` ### Response #### Success Response (200) - **self** (Self) - Returns the instance with the updated form data, enabling method chaining. #### Response Example ```json { "status": "Split span set to 1-5." } ``` ``` -------------------------------- ### Render Expression Configuration Source: https://stumpylog.github.io/gotenberg-client/0.13.0/ref_routes Specifies an expression that must be evaluated as true before the rendering process begins. This allows for dynamic control over when rendering starts. ```APIDOC ## POST /render_expression ### Description Specifies an expression to wait for before rendering begins. The format and behavior depend on the underlying rendering engine. ### Method POST ### Endpoint /render_expression ### Parameters #### Request Body - **expr** (str) - Required - The expression to wait for. Consult the Gotenberg documentation for details on the expression format. ### Request Example ```json { "expr": "document.readyState === 'complete'" } ``` ### Response #### Success Response (200) - **self** (Self) - The current instance of the class, allowing for method chaining. #### Response Example ```json { "message": "Render expression set successfully" } ``` ``` -------------------------------- ### Gotenberg Client Initialization Source: https://stumpylog.github.io/gotenberg-client/0.13.1/usage Demonstrates how to instantiate the GotenbergClient, including required and optional parameters for host, timeouts, log level, and HTTP/2 usage. ```APIDOC ## GotenbergClient Initialization ### Description Instantiates the GotenbergClient to communicate with a Gotenberg instance. The client should be long-lived for efficient connection management. It can be used as a context manager or closed manually. ### Class `GotenbergClient` ### Parameters - **host** (str) - Required - The base URL of the Gotenberg instance. - **timeout** (float) - Optional - Default: 30.0 - Global timeout for requests. - **log_level** (int) - Optional - Default: logging.ERROR - Log level for the library and its dependencies. - **http2** (bool) - Optional - Default: True - Controls the usage of HTTP/2. ### Usage Example (Context Manager) ```python from gotenberg_client import GotenbergClient with GotenbergClient("http://localhost:3000") as client: # Use the client here pass ``` ### Usage Example (Manual Close) ```python import logging client = GotenbergClient("http://localhost:3000", timeout=60.0, log_level=logging.INFO, http2=False) try: # Use the client here pass finally: client.close() ``` ``` -------------------------------- ### Render Wait Configuration Source: https://stumpylog.github.io/gotenberg-client/0.10.0/ref_routes Sets a delay before the rendering process starts. This can be specified in seconds or as a timedelta object. ```APIDOC ## POST /render_wait ### Description Specifies the delay before rendering begins. ### Method POST ### Endpoint /render_wait ### Parameters #### Request Body - **wait** (Union[float, int, timedelta]) - Required - The delay in seconds or a timedelta object before rendering begins. ### Request Example ```json { "wait": 5.0 } ``` ### Response #### Success Response (200) - **self** (Self) - The current instance of the class, allowing for method chaining. #### Response Example ```json { "message": "Render wait time set successfully" } ``` #### Error Response - **NegativeWaitDurationError** - If the wait duration is negative. ``` -------------------------------- ### render_wait(wait: Union[float, int, timedelta]) -> Self Source: https://stumpylog.github.io/gotenberg-client/0.13.0/ref_routes Specifies the delay before rendering begins. This method allows for a controlled pause before the rendering process starts. ```APIDOC ## POST /websites/stumpylog_github_io_gotenberg-client/render_wait ### Description Specifies the delay before rendering begins. ### Method POST ### Endpoint /websites/stumpylog_github_io_gotenberg-client/render_wait ### Parameters #### Query Parameters - **wait** (Union[float, int, timedelta]) - Required - The delay before rendering begins. This can be a float or integer representing seconds, or a timedelta object. ### Request Example ```json { "wait": 5.5 } ``` ### Response #### Success Response (200) - **self** (Self) - The current instance of the class, allowing for method chaining. #### Response Example ```json { "message": "Render wait time set." } ``` ### Error Handling - **NegativeWaitDurationError**: If the wait duration is negative. ``` -------------------------------- ### Render Wait Source: https://stumpylog.github.io/gotenberg-client/0.13.1/ref_routes Specifies the delay before rendering begins. Allows for controlled pauses before the PDF generation process starts. ```APIDOC ## POST /render_wait ### Description Specifies the delay before rendering begins. ### Method POST ### Endpoint /render_wait ### Parameters #### Request Body - **wait** (Union[float, int, timedelta]) - Required - The delay before rendering begins. This can be a float or integer representing seconds, or a timedelta object. ### Response #### Success Response (200) - **self** (Self) - The current instance of the class, allowing for method chaining. ### Request Example ```json { "wait": 5.5 } ``` ### Response Example ```json { "message": "Render wait time set successfully" } ``` ### Errors - **NegativeWaitDurationError**: If the wait duration is negative. ``` -------------------------------- ### Synchronous Screenshot Route Initialization (Python) Source: https://stumpylog.github.io/gotenberg-client/0.13.0/ref_routes Initializes a synchronous route for capturing screenshots from HTML. This constructor sets up the route with the necessary HTTP client, route URL, and a logger instance. It requires these parameters to be provided. ```python def __init__(client: ClientT, route_url: str, log: logging.Logger) -> None: """ Initialize a new BaseRoute instance. """ # ... implementation details ... pass ``` -------------------------------- ### render_wait Source: https://stumpylog.github.io/gotenberg-client/0.10.0/ref_routes Specifies the delay before rendering begins. This method allows you to introduce a pause before the PDF generation process starts. ```APIDOC ## render_wait ### Description Specifies the delay before rendering begins. ### Method POST (Assumed, as it modifies state) ### Endpoint /render_wait ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **wait** (Union[float, int, timedelta]) - Required - The delay before rendering begins. This can be a float or integer representing seconds, or a timedelta object. ### Request Example ```json { "wait": 5.5 } ``` ### Response #### Success Response (200) - **self** (Self) - The current instance of the class, allowing for method chaining. #### Response Example ```json { "message": "Render wait time set successfully." } ``` ### Errors - **NegativeWaitDurationError** - If the wait duration is negative. ``` -------------------------------- ### Route Configuration and Reset Source: https://stumpylog.github.io/gotenberg-client/0.11.0/ref_routes Configure output filename, emulate media types, omit backgrounds, and reset the route. ```APIDOC ## Route Configuration and Reset ### `output_filename(filename: str)` Set the desired output filename for the generated file. Sets the Gotenberg-Output-Filename header to control the output filename. **Parameters:** - `filename` (str) - Required - The desired filename for the output file. **Note:** This setting will only be applied for the current route instantiation. ### `media_type(media_type: Literal['print', 'screen'])` Specifies the emulated media type. **Parameters:** - `media_type` (Literal['print', 'screen']) - Required - The media type to emulate. Must be either "print" or "screen". ### `omit_background(*, omit_background: bool)` Enables or disables the omission of the page background. **Parameters:** - `omit_background` (bool) - Required - True to omit the background, False to include it. ### `reset()` Reset the route to its initial state. Closes all context managers via the ExitStack and clears all set files, form data options, and route-specific headers. ``` -------------------------------- ### Markdown to PDF Conversion Source: https://stumpylog.github.io/gotenberg-client/0.13.1/usage Example of converting a Markdown file to a PDF using the Gotenberg client library's Chromium module. ```APIDOC ## Chromium: Markdown to PDF ### Description Converts a Markdown file to a PDF document using the Chromium engine provided by Gotenberg. This route also supports including external resources like CSS. ### Method `client.chromium.markdown_to_pdf()` ### Endpoint `/forms/chromium/convert/markdown ` ### Parameters #### Request Body - **files** (file) - Required - The Markdown file(s) to convert. - **header_html_file** (file) - Optional - An HTML file for the header. - **footer_html_file** (file) - Optional - An HTML file for the footer. - **pdfa** (bool) - Optional - Convert the PDF/A format. - **fail_on_exceptions** (bool) - Optional - Throw an exception if Gotenberg encounters an error. - **page_size** (str) - Optional - Example: `A4`, `Letter`. - **margin_top** (float) - Optional - Margin in cm. - **margin_bottom** (float) - Optional - Margin in cm. - **margin_left** (float) - Optional - Margin in cm. - **margin_right** (float) - Optional - Margin in cm. - **orientation** (str) - Optional - `portrait` or `landscape`. - **delay** (float) - Optional - Delay in seconds before conversion. - **skip_network_idle_event** (bool) - Optional - Skip network idle event. - **scale** (float) - Optional - Scale the page. - **display_header_footer** (bool) - Optional - Display header and footer. - **print_background** (bool) - Optional - Print background graphics. - **width** (int) - Optional - Page width in pixels. - **height** (int) - Optional - Page height in pixels. - **prefer_css_page_size** (bool) - Optional - Prefer CSS page size. - **css_units** (str) - Optional - CSS units, e.g., `cm`. - **emulated_viewport** (bool) - Optional - Emulate viewport. - **viewport_width** (int) - Optional - Viewport width in pixels. - **viewport_height** (int) - Optional - Viewport height in pixels. - **viewport_device_scale_factor** (float) - Optional - Device scale factor. - **viewport_is_mobile** (bool) - Optional - Whether the viewport is mobile. - **viewport_has_navigation_bar** (bool) - Optional - Whether the viewport has a navigation bar. - **viewport_is_vertical_unified_consent** (bool) - Optional - Whether the viewport has a vertical unified consent. - **viewport_viewports** (list) - Optional - List of viewports. - **resource** (file or str) - Optional - Additional resources like CSS files. ### Request Example ```python from gotenberg_client import GotenbergClient from gotenberg_client.constants import A4 with GotenbergClient("http://localhost:3000") as client: with client.chromium.markdown_to_pdf() as route: response = ( route.markdown_file(open("readme.md")) .size(A4) .resource("styles.css") .fail_on_exceptions() .run() ) ``` ### Response #### Success Response (200) - **content** (bytes) - The generated PDF file content. ``` -------------------------------- ### Initialize GotenbergClient in Python Source: https://stumpylog.github.io/gotenberg-client/0.10.0/usage Demonstrates how to initialize the GotenbergClient. It requires the host URL of the Gotenberg server and allows optional configuration for timeouts, logging level, and HTTP/2 usage. The client should be managed for connection longevity and proper cleanup. ```python import logging class GotenbergClient: def __init__( self, host: str, *, timeout: float = 30.0, log_level: int = logging.ERROR, http2: bool = True, ): .... ``` -------------------------------- ### Set Main HTML Entry Point Source: https://stumpylog.github.io/gotenberg-client/0.13.0/ref_routes Specifies the primary HTML file to be used as the entry point for PDF conversion. The file name will be normalized to 'index.html'. ```python def index(index: Path) -> Self: """Sets the main HTML file for conversion. Parameters: ---------- index : Path Path to the HTML file to use as the main entry point. Returns: ------- Self This object for method chaining. Note ---- The file name will be normalized to "index.html" regardless of original name. """ pass ``` -------------------------------- ### HTML to PDF Conversion Source: https://stumpylog.github.io/gotenberg-client/0.13.1/usage Example of converting an HTML file to a PDF using the Gotenberg client library's Chromium module. ```APIDOC ## Chromium: HTML to PDF ### Description Converts an HTML file to a PDF document using the Chromium engine provided by Gotenberg. This route allows for detailed configuration of the conversion process. ### Method `client.chromium.html_to_pdf()` ### Endpoint `/forms/chromium/convert/html ` ### Parameters #### Request Body - **files** (file) - Required - The HTML file(s) to convert. - **header_html_file** (file) - Optional - An HTML file for the header. - **footer_html_file** (file) - Optional - An HTML file for the footer. - **markdown_file** (file) - Optional - A Markdown file to convert to PDF. - **pdfa** (bool) - Optional - Convert the PDF/A format. - **fail_on_exceptions** (bool) - Optional - Throw an exception if Gotenberg encounters an error. - **page_size** (str) - Optional - Example: `A4`, `Letter`. - **margin_top** (float) - Optional - Margin in cm. - **margin_bottom** (float) - Optional - Margin in cm. - **margin_left** (float) - Optional - Margin in cm. - **margin_right** (float) - Optional - Margin in cm. - **orientation** (str) - Optional - `portrait` or `landscape`. - **delay** (float) - Optional - Delay in seconds before conversion. - **skip_network_idle_event** (bool) - Optional - Skip network idle event. - **scale** (float) - Optional - Scale the page. - **display_header_footer** (bool) - Optional - Display header and footer. - **print_background** (bool) - Optional - Print background graphics. - **width** (int) - Optional - Page width in pixels. - **height** (int) - Optional - Page height in pixels. - **prefer_css_page_size** (bool) - Optional - Prefer CSS page size. - **css_units** (str) - Optional - CSS units, e.g., `cm`. - **emulated_viewport** (bool) - Optional - Emulate viewport. - **viewport_width** (int) - Optional - Viewport width in pixels. - **viewport_height** (int) - Optional - Viewport height in pixels. - **viewport_device_scale_factor** (float) - Optional - Device scale factor. - **viewport_is_mobile** (bool) - Optional - Whether the viewport is mobile. - **viewport_has_navigation_bar** (bool) - Optional - Whether the viewport has a navigation bar. - **viewport_is_vertical_unified_consent** (bool) - Optional - Whether the viewport has a vertical unified consent. - **viewport_viewports** (list) - Optional - List of viewports. ### Request Example ```python from gotenberg_client import GotenbergClient from gotenberg_client.constants import A4 with GotenbergClient("http://localhost:3000") as client: with client.chromium.html_to_pdf() as route: response = ( route.index(open("main.html")) .size(A4) .fail_on_exceptions() .run() ) ``` ### Response #### Success Response (200) - **content** (bytes) - The generated PDF file content. ``` -------------------------------- ### Initialize AsyncChromiumApi Source: https://stumpylog.github.io/gotenberg-client/0.10.0/ref_modules Initializes the AsyncChromiumApi with an asynchronous HTTP client and a logger. This setup is necessary for performing asynchronous Chromium-based conversions and screenshots. ```python AsyncChromiumApi(client: ClientT, log: logging.Logger) -> None ``` -------------------------------- ### Initialize SyncMarkdownToPdfRoute in Python Source: https://stumpylog.github.io/gotenberg-client/0.11.0/ref_routes Initializes the asynchronous route for converting Markdown files to PDFs using Chromium. This class requires an HTTP client, the route URL, and a logger instance for its operation. ```python from gotenberg.client import Client from gotenberg.logger import Logger from gotenberg.routes.chromium import SyncMarkdownToPdfRoute # Assuming 'client' and 'log' are initialized elsewhere # client: Client # log: Logger # route_url = "/forms/chromium/convert/markdown" # markdown_route = SyncMarkdownToPdfRoute(client=client, route_url=route_url, log=log) ``` -------------------------------- ### SyncScreenshotFromHtmlRoute - Initialization Source: https://stumpylog.github.io/gotenberg-client/0.11.0/ref_routes Initializes a new instance of the SyncScreenshotFromHtmlRoute. ```APIDOC ## SyncScreenshotFromHtmlRoute Initialization ### Description Initialize a new BaseRoute instance. ### Parameters - **client** (ClientT) - Required - The HTTP client used to connect to Gotenberg. - **route_url** (str) - Required - The URL of the specific Gotenberg route. - **log** (logging.Logger) - Required - Logger for recording operations. ``` -------------------------------- ### Render Expression - Python Source: https://stumpylog.github.io/gotenberg-client/0.13.0/ref_routes Specifies an expression that the rendering engine should wait for before starting the rendering process. The exact format of the expression depends on the Gotenberg documentation. Supports method chaining. ```python from gotenberg import Client client = Client() # Example: Wait for a specific JavaScript expression route = client.pdf_engines.chromium("https://example.com") route.render_expression("document.fonts.ready") ``` -------------------------------- ### AsyncMarkdownToPdfRoute - Setting Header and Footer (Python) Source: https://stumpylog.github.io/gotenberg-client/0.12.0/ref_routes Illustrates how to attach custom HTML files for headers and footers to the PDF output. This functionality allows for consistent branding or additional information across generated documents. ```python from pathlib import Path from gotenberg_client._chromium.routes import AsyncMarkdownToPdfRoute from gotenberg_client.client import Client import logging async def set_header_footer(client: Client, log: logging.Logger): route = AsyncMarkdownToPdfRoute(client=client, route_url="/forms/chromium/convert/pdf", log=log) header_path = Path("/path/to/your/header.html") footer_path = Path("/path/to/your/footer.html") route.header(header=header_path) route.footer(footer=footer_path) # Further operations with the route... ``` -------------------------------- ### Configure PDF Splitting Span Source: https://stumpylog.github.io/gotenberg-client/latest/ref_routes Sets the specific span for the splitting operation. The 'span' parameter is a string representing the range of pages or intervals to split, for example, '1-3'. This is a required parameter. ```python def split_span(span: str) -> Self: """Configures the splitting span for the route options.""" pass ``` -------------------------------- ### Render Wait Delay (Python) Source: https://stumpylog.github.io/gotenberg-client/0.11.0/ref_routes Sets a delay in seconds before the rendering process starts. This can be a float, integer, or a timedelta object. It's useful for ensuring all page elements have loaded before conversion. ```python client.render_wait(wait=5.5) ``` ```python from datetime import timedelta client.render_wait(wait=timedelta(seconds=5)) ``` -------------------------------- ### Initialize SyncLibreOfficeApi Source: https://stumpylog.github.io/gotenberg-client/0.10.0/ref_modules Initializes the SyncLibreOfficeApi, which is used for synchronous document conversions powered by LibreOffice. This API does not explicitly show an __init__ signature in the provided text but is implied by its existence. -------------------------------- ### ScreenshotFromUrlRoute - Async Context Management Source: https://stumpylog.github.io/gotenberg-client/0.13.0/ref_routes Demonstrates the asynchronous context management for the ScreenshotFromUrlRoute, including entering and exiting the context. ```APIDOC ## AsyncScreenshotFromUrlRoute Asynchronous route for capturing screenshots from URLs. ### Functions ##### `__aenter__() -> Self` `async` Enter the async context manager scope. Resets the route state and returns the route instance. Returns: - **Self** (`Self`) - The route instance. ##### `__aexit__(exc_type: Optional[type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]) -> None` `async` Exit the async context manager scope. Performs cleanup by calling close() to release resources. Parameters: - **exc_type** (`Optional[type[BaseException]]`) - The exception type, if an exception was raised. - **exc_val** (`Optional[BaseException]`) - The exception instance, if an exception was raised. - **exc_tb** (`Optional[TracebackType]`) - The traceback, if an exception was raised. ``` -------------------------------- ### Async Health Check API Source: https://stumpylog.github.io/gotenberg-client/0.13.1/ref_modules Provides an asynchronous interface for performing health checks on the Gotenberg service. It allows for making asynchronous GET requests to the health check endpoint and parsing the response. ```APIDOC ## AsyncHealthCheckApi Asynchronous implementation of the Gotenberg health check API. This class provides an asynchronous interface for performing health checks on the Gotenberg service. For more information on Gotenberg's health check endpoint, see: https://gotenberg.dev/docs/routes#health ### Functions #### `__init__(client: ClientT, log: logging.Logger)` Initialize a new BaseApi instance. **Parameters**: - `client` (ClientT) - Required - The HTTP client (sync or async) to use for requests. - `log` (Logger) - Required - Logger for recording operations. #### `health() -> HealthStatus` `async` Perform an asynchronous health check on the Gotenberg service. This method sends an asynchronous GET request to the Gotenberg health check endpoint and returns the parsed health status. For more details on the health check API, see: https://gotenberg.dev/docs/routes#health **Returns**: - `HealthStatus` (HealthStatus) - An object representing the current health status of the Gotenberg service. **Raises**: - `HTTPStatusError` - If the request to the health check endpoint fails. ``` -------------------------------- ### AsyncMarkdownToPdfRoute Initialization and Context Management Source: https://stumpylog.github.io/gotenberg-client/0.13.0/ref_routes This snippet covers the initialization of the AsyncMarkdownToPdfRoute and its usage within an asynchronous context manager. ```APIDOC ## AsyncMarkdownToPdfRoute ### Description Represents a route for converting Markdown (or HTML) to PDF using Gotenberg's Chromium engine. This class implements an asynchronous context manager for convenient setup and cleanup. ### Initialization ```python __init__(client: ClientT, route_url: str, log: logging.Logger) -> None ``` Initializes the route with an HTTP client, the specific route URL, and a logger. ### Async Context Management ```python __aenter__() -> Self ``` Enter the async context manager scope. Resets the route state and returns the route instance. ```python __aexit__(exc_type: Optional[type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]) -> None ``` Exit the async context manager scope. Performs cleanup by calling `close()` to release resources. ``` -------------------------------- ### Main HTML Index Configuration Source: https://stumpylog.github.io/gotenberg-client/0.13.0/ref_routes Sets the main HTML file that will be used as the entry point for the PDF conversion. Any relative paths within this HTML will be resolved relative to its location. ```APIDOC ## POST /index ### Description Sets the main HTML file for conversion. The file name will be normalized to "index.html". ### Method POST ### Endpoint /index ### Parameters #### Request Body - **index** (Path) - Required - Path to the HTML file to use as the main entry point. ### Response #### Success Response (200) - **self** (Self) - This object for method chaining. ### Response Example { "message": "Main HTML index set successfully" } ``` -------------------------------- ### PDF Metadata Support Source: https://stumpylog.github.io/gotenberg-client/0.10.0/routes This section details how to add metadata to generated PDFs using the Gotenberg client. It lists supported metadata fields and provides a Python code example. ```APIDOC ## PDF Metadata Support ### Description Add metadata to your PDFs using the `metadata()` method. ### Method This documentation applies to routes that accept metadata, such as `html_to_pdf`. ### Endpoint N/A (Method applied within a route context) ### Parameters #### Request Body (Implicitly within route methods) - **title** (str) - Optional - Document title - **author** (str) - Optional - Document author - **subject** (str) - Optional - Document subject - **keywords** (list[str]) - Optional - List of keywords - **creator** (str) - Optional - Creating application - **creation_date** (datetime) - Optional - Creation datetime - **modification_date** (datetime) - Optional - Last modification datetime - **producer** (str) - Optional - PDF producer - **trapped** (str) - Optional - Trapping status ('True', 'False', 'Unknown') - **copyright** (str) - Optional - Copyright information - **marked** (bool) - Optional - PDF marked status - **pdf_version** (str) - Optional - PDF version number ### Request Example ```python from gotenberg_client import GotenbergClient from datetime import datetime with GotenbergClient("http://localhost:3000") as client: with client.chromium.html_to_pdf() as route: response = ( route .index("my-index.html") .metadata( title="My Document", author="John Doe", creation_date=datetime.now(), keywords=["sample", "document"], subject="Sample PDF Generation", trapped="Unknown" ) .run() ) ``` ### Response #### Success Response (200) - **file** (bytes) - The generated PDF file with metadata. #### Response Example (Binary PDF content) ``` -------------------------------- ### BaseRoute Initialization Source: https://stumpylog.github.io/gotenberg-client/0.12.0/ref_routes Initializes a new BaseRoute instance with the provided client, route URL, and logger. ```APIDOC ## `__init__(client: ClientT, route_url: str, log: logging.Logger) -> None` ### Description Initialize a new BaseRoute instance. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Chromium HTML to PDF Route Context Management Source: https://stumpylog.github.io/gotenberg-client/0.11.0/ref_routes Provides context management for the synchronous HTML to PDF route using Chromium. Includes methods to enter and exit the context, handling resource cleanup. Initialization requires a client, route URL, and logger. ```python class SyncHtmlToPdfRoute: def __init__(self, client: ClientT, route_url: str, log: logging.Logger) -> None: pass def __enter__(self) -> Self: """Enter the context manager scope. Resets the route state and returns the route instance. Returns: Self: The route instance. """ pass def __exit__(self, exc_type: Optional[type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]) -> None: """Exit the context manager scope. Performs cleanup by calling close() to release resources. Parameters: exc_type (Optional[type[BaseException]]): The exception type, if an exception was raised. exc_val (Optional[BaseException]): The exception instance, if an exception was raised. exc_tb (Optional[TracebackType]): The traceback, if an exception was raised. """ pass def close(self) -> None: """Close and clean up resources used by this route. This is an alias for reset(). """ pass def background_graphics(self) -> Self: """Enables printing of the page background. Equivalent to print_background(print_background=True). Returns: Self: The current instance of the class, allowing for method chaining. """ pass ``` -------------------------------- ### Specify Screenshot Render Delay (Python) Source: https://stumpylog.github.io/gotenberg-client/0.10.0/ref_routes Sets a delay in seconds before the screenshot rendering process starts. Accepts float, int, or timedelta objects. Negative values will raise an error. ```python from gotenberg import ScreenshotRoute from datetime import timedelta route = ScreenshotRoute() # Wait for 2 seconds route.render_wait(2) # Wait for 1.5 seconds route.render_wait(1.5) # Wait for 3 seconds using timedelta route.render_wait(timedelta(seconds=3)) ``` -------------------------------- ### Set Render Wait Time Source: https://stumpylog.github.io/gotenberg-client/0.13.1/ref_routes Defines a delay in seconds before the rendering process begins. This can be a float, integer, or timedelta object. It's useful for ensuring resources are loaded before rendering starts. ```python client.render_wait(wait=5.0) ``` -------------------------------- ### Initialize AsyncHtmlToPdfRoute Source: https://stumpylog.github.io/gotenberg-client/0.10.0/ref_routes This snippet illustrates the initialization of the AsyncHtmlToPdfRoute. It requires an HTTP client instance, the specific route URL for the HTML to PDF conversion, and a logger object. These parameters are essential for establishing communication with the Gotenberg server and recording operational logs. ```python from gotenberg_client._chromium.routes import AsyncHtmlToPdfRoute from gotenberg_client.client import Client import logging client: Client = ... # Your initialized Gotenberg client route_url: str = "/forms/chromium/convert/pdf" # Example route URL log: logging.Logger = logging.getLogger(__name__) route = AsyncHtmlToPdfRoute(client=client, route_url=route_url, log=log) ``` -------------------------------- ### Set Main HTML File for Conversion Source: https://stumpylog.github.io/gotenberg-client/0.11.0/ref_routes Specifies the main HTML file to be used as the entry point for conversion. The filename will be normalized to 'index.html' regardless of its original name. ```python def index(self, index: Path) -> Self: """Sets the main HTML file for conversion.""" # Implementation to set the index file return self ``` -------------------------------- ### Set PDF Scale Factor (Python) Source: https://stumpylog.github.io/gotenberg-client/0.11.0/ref_routes Sets the scale factor for the generated PDF. This allows you to resize the PDF content. For example, a scale of 2.0 will double the size, while a scale of 0.5 will halve the size. The method returns the current instance for method chaining. ```python def scale(self, scale: Union[float, int]) -> Self: """ Sets the scale factor for the generated PDF. Parameters: scale (Union[float, int]): The scale factor. A float or integer representing the desired scale. For example, a scale of 2.0 will double the size, while a scale of 0.5 will halve the size. Returns: Self: The current instance of the class, allowing for method chaining. """ pass ```