Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions docs/api-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,9 @@ Use this group for password protection, permissions, signatures, and standards.
[remove_open_password][pdfrest.PdfRestClient.remove_open_password]
- Digital signatures:
[sign_pdf][pdfrest.PdfRestClient.sign_pdf]
- Text-and-data-mining reservation:
[apply_tdm_reservation][pdfrest.PdfRestClient.apply_tdm_reservation] embeds
the URL of hosted terms or a machine-readable policy without fetching it
- Archival/print conformance:
[convert_to_pdfa][pdfrest.PdfRestClient.convert_to_pdfa],
[convert_to_pdfx][pdfrest.PdfRestClient.convert_to_pdfx]
Expand Down
1 change: 1 addition & 0 deletions docs/llms-full.txt
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,7 @@ to the API guide and API reference for exact method names and options.
- Redaction preview/apply
- Passwords and permissions
- Encryption/decryption/restrictions
- URL-based text-and-data-mining reservation metadata
- Watermarking (text/image)
- Digital signing

Expand Down
2 changes: 2 additions & 0 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ supported interpreter matrix.

## Available Examples

- `examples/apply_tdm_reservation/apply_tdm_reservation_example.py` – embed a
hosted TDM policy URL in an uploaded PDF.
- `examples/add_shapes/add_shapes_to_pdf_example.py` – add a styled rectangle
and divider line to a PDF with accessibility tagging enabled.
- `examples/convert_structured_documents/convert_structured_documents_to_pdf_example.py`
Expand Down
54 changes: 54 additions & 0 deletions examples/apply_tdm_reservation/apply_tdm_reservation_example.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# /// script
# requires-python = ">=3.10"
# dependencies = ["pdfrest", "python-dotenv"]
# ///
"""Apply a text-and-data-mining reservation policy to a PDF.

This sample demonstrates how to:

1. Load ``PDFREST_API_KEY`` from the environment or a local ``.env`` file.
2. Upload the checked-in ``examples/resources/report.pdf`` input.
3. Embed a URL for hosted TDM terms or a machine-readable policy document.
4. Print the generated PDF metadata.

Replace ``POLICY_URL`` with the URL of your hosted policy in a real integration.
Set ``PDFREST_BASE_URL`` only for a self-hosted deployment. pdfRest stores the
URL without fetching or inspecting its destination. Run from the repository root with
``uv run examples/apply_tdm_reservation/apply_tdm_reservation_example.py``.
"""

from __future__ import annotations

import os
from pathlib import Path

from dotenv import load_dotenv

from pdfrest import PdfRestClient

RESOURCE_DIRECTORY = Path(__file__).resolve().parents[1] / "resources"
INPUT_PATH = RESOURCE_DIRECTORY / "report.pdf"
POLICY_URL = "https://example.com/terms/tdm-policy"


def apply_tdm_reservation() -> None:
"""Upload a PDF and add a URL-based TDM reservation policy."""
load_dotenv()
base_url = os.getenv("PDFREST_BASE_URL")

with PdfRestClient(base_url=base_url) as client:
uploaded_pdf = client.files.create_from_paths(INPUT_PATH)[0]
response = client.apply_tdm_reservation(
uploaded_pdf,
policy=POLICY_URL,
output="report-with-tdm-reservation",
)

print(f"Input ID: {response.input_id}")
print(f"Output file: {response.output_file.name}")
print(f"Output MIME type: {response.output_file.type}")
print(f"Output URL: {response.output_file.url}")


if __name__ == "__main__": # pragma: no cover - manual example
apply_tdm_reservation()
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "pdfrest"
version = "1.6.0"
version = "1.7.0"
description = "Python client library for interacting with the pdfRest API"
readme = { file = "README.md", content-type = "text/markdown" }
license = "Apache-2.0"
Expand Down
94 changes: 94 additions & 0 deletions src/pdfrest/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@
PdfRestrictPayload,
PdfSignPayload,
PdfSplitPayload,
PdfTdmReservationPayload,
PdfTextWatermarkPayload,
PdfToExcelPayload,
PdfToPdfaPayload,
Expand Down Expand Up @@ -4620,6 +4621,53 @@ def sign_pdf(
timeout=timeout,
)

def apply_tdm_reservation(
self,
file: PdfRestFile | Sequence[PdfRestFile],
*,
policy: str,
output: str | None = None,
extra_query: Query | None = None,
extra_headers: AnyMapping | None = None,
extra_body: Body | None = None,
timeout: TimeoutTypes | None = None,
) -> PdfRestFileBasedResponse:
"""Apply a text-and-data-mining reservation policy to a PDF.

Embeds a URL that points to hosted terms of use or a machine-readable
TDM policy document. The URL is stored as metadata without fetching or
inspecting its destination.

Args:
file: Uploaded PDF resource to update.
policy: HTTP or HTTPS URL for the hosted TDM policy or terms of use.
output: Generated output filename without its extension.
extra_query: Additional query parameters merged into the request.
extra_headers: Additional HTTP headers merged into the request.
extra_body: Additional request body fields merged into the payload.
timeout: Request timeout override for this call.

Returns:
Validated file-based response containing the TDM-reserved PDF.

Raises:
PdfRestError: If request execution fails at the client or API layer.
ValidationError: If local payload validation fails before sending.
"""
payload: dict[str, Any] = {"files": file, "policy": policy}
if output is not None:
payload["output"] = output

return self._post_file_operation(
endpoint="/tdm-reserved-pdf",
payload=payload,
payload_model=PdfTdmReservationPayload,
extra_query=extra_query,
extra_headers=extra_headers,
extra_body=extra_body,
timeout=timeout,
)

def validate_zugferd_pdf(
self,
file: PdfRestFile | Sequence[PdfRestFile],
Expand Down Expand Up @@ -8315,6 +8363,52 @@ async def sign_pdf(
timeout=timeout,
)

async def apply_tdm_reservation(
self,
file: PdfRestFile | Sequence[PdfRestFile],
*,
policy: str,
output: str | None = None,
extra_query: Query | None = None,
extra_headers: AnyMapping | None = None,
extra_body: Body | None = None,
timeout: TimeoutTypes | None = None,
) -> PdfRestFileBasedResponse:
"""Asynchronously apply a TDM reservation policy to a PDF.

This is the asynchronous variant of
[PdfRestClient.apply_tdm_reservation][pdfrest.PdfRestClient.apply_tdm_reservation].

Args:
file: Uploaded PDF resource to update.
policy: HTTP or HTTPS URL for the hosted TDM policy or terms of use.
output: Generated output filename without its extension.
extra_query: Additional query parameters merged into the request.
extra_headers: Additional HTTP headers merged into the request.
extra_body: Additional request body fields merged into the payload.
timeout: Request timeout override for this call.

Returns:
Validated file-based response containing the TDM-reserved PDF.

Raises:
PdfRestError: If request execution fails at the client or API layer.
ValidationError: If local payload validation fails before sending.
"""
payload: dict[str, Any] = {"files": file, "policy": policy}
if output is not None:
payload["output"] = output

return await self._post_file_operation(
endpoint="/tdm-reserved-pdf",
payload=payload,
payload_model=PdfTdmReservationPayload,
extra_query=extra_query,
extra_headers=extra_headers,
extra_body=extra_body,
timeout=timeout,
)

async def validate_zugferd_pdf(
self,
file: PdfRestFile | Sequence[PdfRestFile],
Expand Down
47 changes: 47 additions & 0 deletions src/pdfrest/models/_internal.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
HttpUrl,
PlainSerializer,
StringConstraints,
TypeAdapter,
ValidatorFunctionWrapHandler,
WrapValidator,
model_serializer,
Expand Down Expand Up @@ -68,6 +69,7 @@
PDFA_OUTPUT_TYPE_MAP: dict[str, PdfAType] = {
output_type.casefold(): output_type for output_type in PDFA_OUTPUT_TYPES
}
_HTTP_URL_ADAPTER = TypeAdapter(HttpUrl)


def _ensure_list(value: Any) -> Any:
Expand Down Expand Up @@ -128,6 +130,22 @@ def _validate_output_prefix(value: str | None) -> str | None:
return value


def _validate_http_url(value: str) -> str:
"""Validate an HTTP(S) URL without normalizing the caller's value."""
message = "Must be a valid HTTP or HTTPS URL."
if (
any(character.isspace() for character in value)
or "\\" in value
or re.search(r"%(?![0-9A-Fa-f]{2})", value)
):
raise ValueError(message)
try:
_ = _HTTP_URL_ADAPTER.validate_python(value)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Reject malformed URLs with strict parsing

validate_python(value) accepts https:/example.com/policy, https:example.com/policy, and https:///example.com/policy by repairing the separators internally. Because the validator returns the original string, those malformed values still reach the API unchanged. Please call validate_python(value, strict=True) and continue returning the original value so valid policy URLs are never rewritten.

Please add parametrized regression tests for all three malformed forms through distinct sync and async client tests, using a fail-if-called transport to prove rejection before any HTTP request. Also test that valid URLs (including a bare origin and an encoded path/query/fragment) serialize exactly as supplied. Retain the existing whitespace, backslash, and malformed-percent checks.

except ValueError:
raise ValueError(message) from None
return value


def _split_comma_list(value: Any) -> Any:
if isinstance(value, str):
return value.split(",")
Expand Down Expand Up @@ -3656,6 +3674,35 @@ class PdfDecryptPayload(BaseModel):
] = None


class PdfTdmReservationPayload(BaseModel):
"""Adapt caller options into a pdfRest-ready TDM reservation payload."""

files: Annotated[
list[PdfRestFile],
Field(
min_length=1,
max_length=1,
validation_alias=AliasChoices("file", "files"),
serialization_alias="id",
),
BeforeValidator(_ensure_list),
AfterValidator(
_allowed_mime_types("application/pdf", error_msg="Must be a PDF file")
),
PlainSerializer(_serialize_as_first_file_id),
]
policy: Annotated[
str,
Field(min_length=1, serialization_alias="policy"),
AfterValidator(_validate_http_url),
]
output: Annotated[
str | None,
Field(serialization_alias="output", min_length=1, default=None),
AfterValidator(_validate_output_prefix),
] = None


class BmpPdfRestPayload(BasePdfRestGraphicPayload[Literal["rgb", "gray"]]):
"""Adapt caller options into a pdfRest-ready BMP request payload."""

Expand Down
Loading
Loading