From 02db388d6d395e9cef6e9f5497d7aadfbed5ab33 Mon Sep 17 00:00:00 2001 From: Taylor Smith Date: Tue, 3 Nov 2026 14:38:11 -0600 Subject: [PATCH 1/4] client: Add TDM reservation policy support - Add synchronous and asynchronous helpers for uploaded PDF resources. - Validate HTTP and HTTPS policy URLs without changing valid values. - Cover serialization, customization, validation, and response mapping. Assisted-by: Codex --- src/pdfrest/client.py | 94 ++++++ src/pdfrest/models/_internal.py | 47 +++ tests/test_apply_tdm_reservation.py | 468 ++++++++++++++++++++++++++++ 3 files changed, 609 insertions(+) create mode 100644 tests/test_apply_tdm_reservation.py diff --git a/src/pdfrest/client.py b/src/pdfrest/client.py index 9e8ef03..d6e9385 100644 --- a/src/pdfrest/client.py +++ b/src/pdfrest/client.py @@ -123,6 +123,7 @@ PdfRestrictPayload, PdfSignPayload, PdfSplitPayload, + PdfTdmReservationPayload, PdfTextWatermarkPayload, PdfToExcelPayload, PdfToPdfaPayload, @@ -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], @@ -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], diff --git a/src/pdfrest/models/_internal.py b/src/pdfrest/models/_internal.py index c140a27..a3b2857 100644 --- a/src/pdfrest/models/_internal.py +++ b/src/pdfrest/models/_internal.py @@ -16,6 +16,7 @@ HttpUrl, PlainSerializer, StringConstraints, + TypeAdapter, ValidatorFunctionWrapHandler, WrapValidator, model_serializer, @@ -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: @@ -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) + except ValueError: + raise ValueError(message) from None + return value + + def _split_comma_list(value: Any) -> Any: if isinstance(value, str): return value.split(",") @@ -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.""" diff --git a/tests/test_apply_tdm_reservation.py b/tests/test_apply_tdm_reservation.py new file mode 100644 index 0000000..cbf03b6 --- /dev/null +++ b/tests/test_apply_tdm_reservation.py @@ -0,0 +1,468 @@ +from __future__ import annotations + +import json + +import httpx +import pytest +from pydantic import ValidationError + +from pdfrest import AsyncPdfRestClient, PdfRestClient +from pdfrest.models import PdfRestFile, PdfRestFileBasedResponse, PdfRestFileID +from pdfrest.models._internal import PdfTdmReservationPayload + +from .graphics_test_helpers import ( + ASYNC_API_KEY, + VALID_API_KEY, + build_file_info_payload, + make_pdf_file, +) + +POLICY_URL = "https://rights.example/tdm-policy?version=2#terms" + + +@pytest.mark.parametrize( + "policy", + [ + pytest.param("https://example.com", id="origin"), + pytest.param( + "https://example.com/terms%20and%20conditions", + id="percent-encoded-path", + ), + ], +) +def test_tdm_reservation_payload_preserves_policy_url(policy: str) -> None: + input_file = make_pdf_file(PdfRestFileID.generate(1)) + + payload = PdfTdmReservationPayload.model_validate( + { + "file": input_file, + "policy": policy, + "output": "tdm-reserved", + } + ) + + assert payload.model_dump( + mode="json", + by_alias=True, + exclude_none=True, + exclude_unset=True, + ) == { + "id": str(input_file.id), + "policy": policy, + "output": "tdm-reserved", + } + + +def test_tdm_reservation_payload_requires_policy() -> None: + input_file = make_pdf_file(PdfRestFileID.generate(1)) + + with pytest.raises(ValidationError, match=r"policy\s+Field required"): + PdfTdmReservationPayload.model_validate({"file": input_file}) + + +def test_apply_tdm_reservation_success(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.delenv("PDFREST_API_KEY", raising=False) + input_file = make_pdf_file(PdfRestFileID.generate(1)) + output_id = str(PdfRestFileID.generate()) + payload_dump = PdfTdmReservationPayload.model_validate( + {"file": input_file, "policy": POLICY_URL} + ).model_dump(mode="json", by_alias=True, exclude_none=True, exclude_unset=True) + seen = {"post": 0, "get": 0} + + def handler(request: httpx.Request) -> httpx.Response: + if request.method == "POST" and request.url.path == "/tdm-reserved-pdf": + seen["post"] += 1 + assert json.loads(request.content) == payload_dump + return httpx.Response( + 200, + json={"inputId": [input_file.id], "outputId": [output_id]}, + ) + if request.method == "GET" and request.url.path == f"/resource/{output_id}": + seen["get"] += 1 + assert request.url.params["format"] == "info" + return httpx.Response( + 200, + json=build_file_info_payload( + output_id, + "report_pdfrest_tdm_reserved_pdf.pdf", + "application/pdf", + ), + ) + message = f"Unexpected request {request.method} {request.url}" + raise AssertionError(message) + + with PdfRestClient( + api_key=VALID_API_KEY, + transport=httpx.MockTransport(handler), + ) as client: + response = client.apply_tdm_reservation(input_file, policy=POLICY_URL) + + assert seen == {"post": 1, "get": 1} + assert isinstance(response, PdfRestFileBasedResponse) + assert str(response.input_id) == str(input_file.id) + assert response.output_file.name == "report_pdfrest_tdm_reserved_pdf.pdf" + assert response.output_file.type == "application/pdf" + assert response.output_file.size > 0 + assert response.warning is None + + +def test_apply_tdm_reservation_request_customization( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.delenv("PDFREST_API_KEY", raising=False) + input_file = make_pdf_file(PdfRestFileID.generate(1)) + output_id = str(PdfRestFileID.generate()) + captured_timeout: dict[str, float | dict[str, float] | None] = {} + + def handler(request: httpx.Request) -> httpx.Response: + assert request.url.params["trace"] == "sync" + assert request.headers["X-Debug"] == "sync" + if request.method == "POST" and request.url.path == "/tdm-reserved-pdf": + captured_timeout["value"] = request.extensions.get("timeout") + assert json.loads(request.content) == { + "id": str(input_file.id), + "policy": POLICY_URL, + "output": "reserved-sync", + "debug": "yes", + } + return httpx.Response( + 200, + json={"inputId": [input_file.id], "outputId": [output_id]}, + ) + if request.method == "GET" and request.url.path == f"/resource/{output_id}": + assert request.url.params["format"] == "info" + return httpx.Response( + 200, + json=build_file_info_payload( + output_id, + "reserved-sync.pdf", + "application/pdf", + ), + ) + message = f"Unexpected request {request.method} {request.url}" + raise AssertionError(message) + + with PdfRestClient( + api_key=VALID_API_KEY, + transport=httpx.MockTransport(handler), + ) as client: + response = client.apply_tdm_reservation( + input_file, + policy=POLICY_URL, + output="reserved-sync", + extra_query={"trace": "sync"}, + extra_headers={"X-Debug": "sync"}, + extra_body={"debug": "yes"}, + timeout=0.61, + ) + + assert response.output_file.name == "reserved-sync.pdf" + timeout_value = captured_timeout["value"] + assert timeout_value is not None + if isinstance(timeout_value, dict): + assert all( + component == pytest.approx(0.61) for component in timeout_value.values() + ) + else: + assert timeout_value == pytest.approx(0.61) + + +@pytest.mark.asyncio +async def test_async_apply_tdm_reservation_success( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.delenv("PDFREST_API_KEY", raising=False) + input_file = make_pdf_file(PdfRestFileID.generate(2)) + output_id = str(PdfRestFileID.generate()) + payload_dump = PdfTdmReservationPayload.model_validate( + {"file": input_file, "policy": POLICY_URL} + ).model_dump(mode="json", by_alias=True, exclude_none=True, exclude_unset=True) + seen = {"post": 0, "get": 0} + + def handler(request: httpx.Request) -> httpx.Response: + if request.method == "POST" and request.url.path == "/tdm-reserved-pdf": + seen["post"] += 1 + assert json.loads(request.content) == payload_dump + return httpx.Response( + 200, + json={"inputId": [input_file.id], "outputId": [output_id]}, + ) + if request.method == "GET" and request.url.path == f"/resource/{output_id}": + seen["get"] += 1 + assert request.url.params["format"] == "info" + return httpx.Response( + 200, + json=build_file_info_payload( + output_id, + "async-report_pdfrest_tdm_reserved_pdf.pdf", + "application/pdf", + ), + ) + message = f"Unexpected request {request.method} {request.url}" + raise AssertionError(message) + + async with AsyncPdfRestClient( + api_key=ASYNC_API_KEY, + transport=httpx.MockTransport(handler), + ) as client: + response = await client.apply_tdm_reservation(input_file, policy=POLICY_URL) + + assert seen == {"post": 1, "get": 1} + assert isinstance(response, PdfRestFileBasedResponse) + assert str(response.input_id) == str(input_file.id) + assert response.output_file.name == "async-report_pdfrest_tdm_reserved_pdf.pdf" + assert response.output_file.type == "application/pdf" + assert response.output_file.size > 0 + assert response.warning is None + + +@pytest.mark.asyncio +async def test_async_apply_tdm_reservation_request_customization( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.delenv("PDFREST_API_KEY", raising=False) + input_file = make_pdf_file(PdfRestFileID.generate(2)) + output_id = str(PdfRestFileID.generate()) + captured_timeout: dict[str, float | dict[str, float] | None] = {} + + def handler(request: httpx.Request) -> httpx.Response: + assert request.url.params["trace"] == "async" + assert request.headers["X-Debug"] == "async" + if request.method == "POST" and request.url.path == "/tdm-reserved-pdf": + captured_timeout["value"] = request.extensions.get("timeout") + assert json.loads(request.content) == { + "id": str(input_file.id), + "policy": POLICY_URL, + "output": "reserved-async", + "flags": ["a", "b"], + } + return httpx.Response( + 200, + json={"inputId": [input_file.id], "outputId": [output_id]}, + ) + if request.method == "GET" and request.url.path == f"/resource/{output_id}": + assert request.url.params["format"] == "info" + return httpx.Response( + 200, + json=build_file_info_payload( + output_id, + "reserved-async.pdf", + "application/pdf", + ), + ) + message = f"Unexpected request {request.method} {request.url}" + raise AssertionError(message) + + async with AsyncPdfRestClient( + api_key=ASYNC_API_KEY, + transport=httpx.MockTransport(handler), + ) as client: + response = await client.apply_tdm_reservation( + input_file, + policy=POLICY_URL, + output="reserved-async", + extra_query={"trace": "async"}, + extra_headers={"X-Debug": "async"}, + extra_body={"flags": ["a", "b"]}, + timeout=0.83, + ) + + assert response.output_file.name == "reserved-async.pdf" + timeout_value = captured_timeout["value"] + assert timeout_value is not None + if isinstance(timeout_value, dict): + assert all( + component == pytest.approx(0.83) for component in timeout_value.values() + ) + else: + assert timeout_value == pytest.approx(0.83) + + +@pytest.mark.parametrize( + ("policy", "match"), + [ + pytest.param("", "String should have at least 1 character", id="empty"), + pytest.param("my-policy", "Must be a valid HTTP or HTTPS URL", id="bare-name"), + pytest.param( + "No AI training allowed", + "Must be a valid HTTP or HTTPS URL", + id="policy-text", + ), + pytest.param( + "example.com/tdm-policy", + "Must be a valid HTTP or HTTPS URL", + id="missing-scheme", + ), + pytest.param( + "ftp://example.com/tdm-policy", + "Must be a valid HTTP or HTTPS URL", + id="unsupported-scheme", + ), + pytest.param( + " https://example.com/tdm-policy ", + "Must be a valid HTTP or HTTPS URL", + id="surrounding-whitespace", + ), + pytest.param( + "https://example.com/%ZZ", + "Must be a valid HTTP or HTTPS URL", + id="invalid-percent-escape", + ), + pytest.param( + "https://example.com\\tdm-policy", + "Must be a valid HTTP or HTTPS URL", + id="backslash", + ), + ], +) +def test_apply_tdm_reservation_rejects_invalid_policy( + monkeypatch: pytest.MonkeyPatch, + policy: str, + match: str, +) -> None: + monkeypatch.delenv("PDFREST_API_KEY", raising=False) + input_file = make_pdf_file(PdfRestFileID.generate(1)) + transport = httpx.MockTransport(lambda request: pytest.fail("request was sent")) + + with ( + PdfRestClient(api_key=VALID_API_KEY, transport=transport) as client, + pytest.raises(ValidationError, match=match), + ): + client.apply_tdm_reservation(input_file, policy=policy) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("policy", "match"), + [ + pytest.param("", "String should have at least 1 character", id="empty"), + pytest.param("my-policy", "Must be a valid HTTP or HTTPS URL", id="bare-name"), + pytest.param( + "No AI training allowed", + "Must be a valid HTTP or HTTPS URL", + id="policy-text", + ), + pytest.param( + "example.com/tdm-policy", + "Must be a valid HTTP or HTTPS URL", + id="missing-scheme", + ), + pytest.param( + "ftp://example.com/tdm-policy", + "Must be a valid HTTP or HTTPS URL", + id="unsupported-scheme", + ), + pytest.param( + "https://example.com/tdm policy", + "Must be a valid HTTP or HTTPS URL", + id="embedded-whitespace", + ), + pytest.param( + "https://example.com/%ZZ", + "Must be a valid HTTP or HTTPS URL", + id="invalid-percent-escape", + ), + pytest.param( + "https://example.com\\tdm-policy", + "Must be a valid HTTP or HTTPS URL", + id="backslash", + ), + ], +) +async def test_async_apply_tdm_reservation_rejects_invalid_policy( + monkeypatch: pytest.MonkeyPatch, + policy: str, + match: str, +) -> None: + monkeypatch.delenv("PDFREST_API_KEY", raising=False) + input_file = make_pdf_file(PdfRestFileID.generate(2)) + transport = httpx.MockTransport(lambda request: pytest.fail("request was sent")) + + async with AsyncPdfRestClient( + api_key=ASYNC_API_KEY, + transport=transport, + ) as client: + with pytest.raises(ValidationError, match=match): + await client.apply_tdm_reservation(input_file, policy=policy) + + +@pytest.mark.parametrize( + ("files", "match"), + [ + pytest.param("empty", "at least 1 item", id="empty"), + pytest.param("png", "Must be a PDF file", id="non-pdf-file"), + pytest.param( + "multiple", + "List should have at most 1 item after validation", + id="multiple-files", + ), + ], +) +def test_apply_tdm_reservation_rejects_incompatible_resources( + monkeypatch: pytest.MonkeyPatch, + files: str, + match: str, +) -> None: + monkeypatch.delenv("PDFREST_API_KEY", raising=False) + pdf_file = make_pdf_file(PdfRestFileID.generate(1)) + png_file = PdfRestFile.model_validate( + build_file_info_payload( + PdfRestFileID.generate(), + "example.png", + "image/png", + ) + ) + files_argument = { + "empty": [], + "png": png_file, + "multiple": [pdf_file, make_pdf_file(PdfRestFileID.generate())], + }[files] + transport = httpx.MockTransport(lambda request: pytest.fail("request was sent")) + + with ( + PdfRestClient(api_key=VALID_API_KEY, transport=transport) as client, + pytest.raises(ValidationError, match=match), + ): + client.apply_tdm_reservation(files_argument, policy=POLICY_URL) + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + ("files", "match"), + [ + pytest.param("empty", "at least 1 item", id="empty"), + pytest.param("png", "Must be a PDF file", id="non-pdf-file"), + pytest.param( + "multiple", + "List should have at most 1 item after validation", + id="multiple-files", + ), + ], +) +async def test_async_apply_tdm_reservation_rejects_incompatible_resources( + monkeypatch: pytest.MonkeyPatch, + files: str, + match: str, +) -> None: + monkeypatch.delenv("PDFREST_API_KEY", raising=False) + pdf_file = make_pdf_file(PdfRestFileID.generate(2)) + png_file = PdfRestFile.model_validate( + build_file_info_payload( + PdfRestFileID.generate(), + "example.png", + "image/png", + ) + ) + files_argument = { + "empty": [], + "png": png_file, + "multiple": [pdf_file, make_pdf_file(PdfRestFileID.generate())], + }[files] + transport = httpx.MockTransport(lambda request: pytest.fail("request was sent")) + + async with AsyncPdfRestClient( + api_key=ASYNC_API_KEY, + transport=transport, + ) as client: + with pytest.raises(ValidationError, match=match): + await client.apply_tdm_reservation(files_argument, policy=POLICY_URL) From 1006dfbdadd1918b3cd30ddba559bb0babc0c3da Mon Sep 17 00:00:00 2001 From: Taylor Smith Date: Tue, 3 Nov 2026 14:38:47 -0600 Subject: [PATCH 2/4] tests: Verify TDM reservation live - Exercise default and custom output names through both client transports. - Inspect generated PDF metadata and server-side policy rejection. Assisted-by: Codex --- tests/live/test_live_apply_tdm_reservation.py | 150 ++++++++++++++++++ 1 file changed, 150 insertions(+) create mode 100644 tests/live/test_live_apply_tdm_reservation.py diff --git a/tests/live/test_live_apply_tdm_reservation.py b/tests/live/test_live_apply_tdm_reservation.py new file mode 100644 index 0000000..106a229 --- /dev/null +++ b/tests/live/test_live_apply_tdm_reservation.py @@ -0,0 +1,150 @@ +from __future__ import annotations + +import pytest + +from pdfrest import AsyncPdfRestClient, PdfRestApiError, PdfRestClient +from pdfrest.models import PdfRestFile + +from ..resources import get_test_resource_path + +POLICY_URL = "https://example.com/terms/tdm-policy" + + +@pytest.fixture(scope="module") +def uploaded_pdf_for_tdm_reservation( + pdfrest_api_key: str, + pdfrest_live_base_url: str, +) -> PdfRestFile: + resource = get_test_resource_path("report.pdf") + with PdfRestClient( + api_key=pdfrest_api_key, + base_url=pdfrest_live_base_url, + ) as client: + return client.files.create_from_paths([resource])[0] + + +@pytest.mark.parametrize( + "output_name", + [ + pytest.param(None, id="default-output"), + pytest.param("tdm-reserved-live", id="custom-output"), + ], +) +def test_live_apply_tdm_reservation( + pdfrest_api_key: str, + pdfrest_live_base_url: str, + uploaded_pdf_for_tdm_reservation: PdfRestFile, + output_name: str | None, +) -> None: + kwargs: dict[str, str] = {} + if output_name is not None: + kwargs["output"] = output_name + + with PdfRestClient( + api_key=pdfrest_api_key, + base_url=pdfrest_live_base_url, + ) as client: + response = client.apply_tdm_reservation( + uploaded_pdf_for_tdm_reservation, + policy=POLICY_URL, + **kwargs, + ) + output_bytes = client.files.read_bytes(response.output_file) + + assert response.output_files + output_file = response.output_file + assert output_file.type == "application/pdf" + assert output_file.size > 0 + assert output_file.url is not None + assert response.warning is None + assert str(response.input_id) == str(uploaded_pdf_for_tdm_reservation.id) + assert POLICY_URL.encode() in output_bytes + assert b"tdm:policy" in output_bytes + if output_name is not None: + assert output_file.name.startswith(output_name) + else: + assert output_file.name.endswith(".pdf") + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "output_name", + [ + pytest.param(None, id="default-output"), + pytest.param("tdm-reserved-live-async", id="custom-output"), + ], +) +async def test_live_async_apply_tdm_reservation( + pdfrest_api_key: str, + pdfrest_live_base_url: str, + uploaded_pdf_for_tdm_reservation: PdfRestFile, + output_name: str | None, +) -> None: + kwargs: dict[str, str] = {} + if output_name is not None: + kwargs["output"] = output_name + + async with AsyncPdfRestClient( + api_key=pdfrest_api_key, + base_url=pdfrest_live_base_url, + ) as client: + response = await client.apply_tdm_reservation( + uploaded_pdf_for_tdm_reservation, + policy=POLICY_URL, + **kwargs, + ) + output_bytes = await client.files.read_bytes(response.output_file) + + assert response.output_files + output_file = response.output_file + assert output_file.type == "application/pdf" + assert output_file.size > 0 + assert output_file.url is not None + assert response.warning is None + assert str(response.input_id) == str(uploaded_pdf_for_tdm_reservation.id) + assert POLICY_URL.encode() in output_bytes + assert b"tdm:policy" in output_bytes + if output_name is not None: + assert output_file.name.startswith(output_name) + else: + assert output_file.name.endswith(".pdf") + + +def test_live_apply_tdm_reservation_rejects_missing_policy( + pdfrest_api_key: str, + pdfrest_live_base_url: str, + uploaded_pdf_for_tdm_reservation: PdfRestFile, +) -> None: + with ( + PdfRestClient( + api_key=pdfrest_api_key, + base_url=pdfrest_live_base_url, + ) as client, + pytest.raises(PdfRestApiError, match=r"(?i)TDM policy setting is required"), + ): + client.apply_tdm_reservation( + uploaded_pdf_for_tdm_reservation, + policy=POLICY_URL, + extra_body={"policy": ""}, + ) + + +@pytest.mark.asyncio +async def test_live_async_apply_tdm_reservation_rejects_missing_policy( + pdfrest_api_key: str, + pdfrest_live_base_url: str, + uploaded_pdf_for_tdm_reservation: PdfRestFile, +) -> None: + async with AsyncPdfRestClient( + api_key=pdfrest_api_key, + base_url=pdfrest_live_base_url, + ) as client: + with pytest.raises( + PdfRestApiError, + match=r"(?i)TDM policy setting is required", + ): + await client.apply_tdm_reservation( + uploaded_pdf_for_tdm_reservation, + policy=POLICY_URL, + extra_body={"policy": ""}, + ) From 77186bec75fb5b699cedb9ed32f042c3e9a90ed9 Mon Sep 17 00:00:00 2001 From: Taylor Smith Date: Tue, 3 Nov 2026 14:39:16 -0600 Subject: [PATCH 3/4] docs: Document TDM reservation workflow - Link the helper and explain URL-based reservation metadata behavior. - Add a runnable upload example and list it in the example inventory. Assisted-by: Codex --- docs/api-guide.md | 3 ++ docs/llms-full.txt | 1 + examples/README.md | 2 + .../apply_tdm_reservation_example.py | 54 +++++++++++++++++++ 4 files changed, 60 insertions(+) create mode 100644 examples/apply_tdm_reservation/apply_tdm_reservation_example.py diff --git a/docs/api-guide.md b/docs/api-guide.md index 8ad4823..f8b5d8a 100644 --- a/docs/api-guide.md +++ b/docs/api-guide.md @@ -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] diff --git a/docs/llms-full.txt b/docs/llms-full.txt index 86484f1..aeefd34 100644 --- a/docs/llms-full.txt +++ b/docs/llms-full.txt @@ -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 diff --git a/examples/README.md b/examples/README.md index 97ba697..bbcabe3 100644 --- a/examples/README.md +++ b/examples/README.md @@ -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` diff --git a/examples/apply_tdm_reservation/apply_tdm_reservation_example.py b/examples/apply_tdm_reservation/apply_tdm_reservation_example.py new file mode 100644 index 0000000..1a7de82 --- /dev/null +++ b/examples/apply_tdm_reservation/apply_tdm_reservation_example.py @@ -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() From f6d9d717eeabd1eea1535087322593133b2ae19f Mon Sep 17 00:00:00 2001 From: Taylor Smith Date: Fri, 13 Nov 2026 15:16:29 -0600 Subject: [PATCH 4/4] pyproject: Bump package version to 1.7.0 - Mark the additive TDM helper for the next minor feature release. - Keep the project lock metadata synchronized. Assisted-by: Codex --- pyproject.toml | 2 +- uv.lock | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index f70e8aa..5e4565f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -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" diff --git a/uv.lock b/uv.lock index 926ab8d..8ed5ed1 100644 --- a/uv.lock +++ b/uv.lock @@ -964,7 +964,7 @@ wheels = [ [[package]] name = "pdfrest" -version = "1.6.0" +version = "1.7.0" source = { editable = "." } dependencies = [ { name = "exceptiongroup" },