pdfops 0.1.0__tar.gz → 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: pdfops
3
- Version: 0.1.0
4
- Summary: Python client for the PDFops API: fill AcroForm PDFs, merge PDFs, inspect form fields, generate invoices. One HTTP call, no native deps, no headless browser.
3
+ Version: 0.2.0
4
+ Summary: Python client for the PDFops API: fill AcroForm PDFs, merge and split PDFs, page operations (extract, delete, rotate, watermark, page numbers), protect and unlock, edit metadata, inspect form fields, generate invoices. One HTTP call, no native deps, no headless browser.
5
5
  Project-URL: Homepage, https://pdfops.dev
6
6
  Project-URL: Documentation, https://pdfops.dev/docs
7
7
  Project-URL: Fill a PDF in Python, https://pdfops.dev/fill-pdf-in-python
@@ -10,7 +10,7 @@ Project-URL: Issues, https://github.com/pdfops/pdfops-python/issues
10
10
  Author-email: PDFops <hello@pdfops.dev>
11
11
  License-Expression: MIT
12
12
  License-File: LICENSE
13
- Keywords: acroform,fill-pdf,invoice,merge-pdf,pdf,pdf-api,pdf-forms,pypdf
13
+ Keywords: acroform,fill-pdf,invoice,merge-pdf,pdf,pdf-api,pdf-forms,pdf-metadata,protect-pdf,pypdf,rotate-pdf,split-pdf,watermark-pdf
14
14
  Classifier: Development Status :: 4 - Beta
15
15
  Classifier: Intended Audience :: Developers
16
16
  Classifier: License :: OSI Approved :: MIT License
@@ -30,7 +30,7 @@ Description-Content-Type: text/markdown
30
30
 
31
31
  # pdfops
32
32
 
33
- Python client for the [PDFops API](https://pdfops.dev): **fill** AcroForm PDFs, **merge** PDFs, **inspect** form fields, and **generate invoices** with one HTTP call. No native dependencies, no headless browser, nothing to install but this package.
33
+ Python client for the [PDFops API](https://pdfops.dev): **fill** AcroForm PDFs, **merge** and **split** PDFs, run **page operations** (extract, delete, rotate, watermark, page numbers), **protect / unlock** and edit **metadata**, **inspect** form fields, and **generate invoices** with one HTTP call. No native dependencies, no headless browser, nothing to install but this package.
34
34
 
35
35
  Built for the moment `pypdf` / `PyPDFForm` stop cooperating — appearance streams that never render, `NeedAppearances` flags, encrypted government blanks, checkboxes that will not tick — and for runtimes where a PDF toolchain does not fit: Lambda, Cloud Functions, Airflow tasks, notebooks.
36
36
 
@@ -72,6 +72,21 @@ invoice = client.invoice({
72
72
  })
73
73
  ```
74
74
 
75
+ Page operations, one line each (all keyword-only options are optional and omitted when unset):
76
+
77
+ ```python
78
+ first_two = client.extract_pages("in.pdf", "1-2")
79
+ trimmed = client.delete_pages("in.pdf", "2,4-6")
80
+ turned = client.rotate("in.pdf", 90, pages="1")
81
+ res = client.split("in.pdf", ranges="1-2,3-") # or every=5; res.parts[0].pdf is bytes
82
+ marked = client.watermark("in.pdf", "DRAFT", opacity=0.2)
83
+ numbered = client.page_numbers("in.pdf", format="Page {n} of {total}", position="bottom-right")
84
+ opened = client.unlock("locked.pdf") # opened.pdf, opened.note ("not-encrypted" or None)
85
+ sealed = client.protect("in.pdf", user_password="s3cret", permissions=["print"]) # [] allows none
86
+ info = client.metadata("in.pdf") # info["page_count"], info["title"], ...
87
+ titled = client.set_metadata("in.pdf", title="Q3 report", keywords=["finance", "q3"])
88
+ ```
89
+
75
90
  PDF inputs may be `bytes`, a path (`str` / `pathlib.Path`), or a binary file object. Every PDF-producing call returns `bytes`.
76
91
 
77
92
  ## API
@@ -82,6 +97,16 @@ PDF inputs may be `bytes`, a path (`str` / `pathlib.Path`), or a binary file obj
82
97
  | `fill_form(pdf, fields, *, flatten=False)` | `POST /api/fill-form` | filled PDF `bytes` |
83
98
  | `merge([pdf, pdf, ...])` | `POST /api/merge` | merged PDF `bytes` |
84
99
  | `invoice(request)` | `POST /api/invoice` | invoice PDF `bytes` |
100
+ | `extract_pages(pdf, pages, *, password=None)` | `POST /api/extract-pages` | PDF `bytes` with only those pages, in that order |
101
+ | `delete_pages(pdf, pages, *, password=None)` | `POST /api/delete-pages` | PDF `bytes` without those pages |
102
+ | `rotate(pdf, degrees, *, pages=None, password=None)` | `POST /api/rotate` | rotated PDF `bytes` (90, 180, 270, -90) |
103
+ | `split(pdf, *, ranges=None, every=None, password=None)` | `POST /api/split` | `SplitResult` — `count`, `parts[]` of `pages`, `page_count`, `pdf` bytes |
104
+ | `watermark(pdf, text, *, opacity, size, color, rotation, position, pages, password)` | `POST /api/watermark` | watermarked PDF `bytes` |
105
+ | `page_numbers(pdf, *, format, position, size, start, margin, pages, password)` | `POST /api/page-numbers` | numbered PDF `bytes` |
106
+ | `unlock(pdf, password=None)` | `POST /api/unlock` | `UnlockResult` — `pdf` bytes plus optional `note` |
107
+ | `protect(pdf, *, user_password, owner_password, permissions, password)` | `POST /api/protect` | encrypted PDF `bytes` |
108
+ | `metadata(pdf, *, password=None)` | `POST /api/metadata` | `dict` — page count, page sizes, title, author, dates, form field count |
109
+ | `set_metadata(pdf, *, title, author, subject, creator, keywords, password)` | `POST /api/set-metadata` | PDF `bytes` with the info fields written |
85
110
  | `usage()` | `GET /api/usage` | `dict` — tier, limit, used, remaining, resets_at |
86
111
  | `signup(email)` | `POST /api/signup` | `None` — the key is emailed |
87
112
 
@@ -1,6 +1,6 @@
1
1
  # pdfops
2
2
 
3
- Python client for the [PDFops API](https://pdfops.dev): **fill** AcroForm PDFs, **merge** PDFs, **inspect** form fields, and **generate invoices** with one HTTP call. No native dependencies, no headless browser, nothing to install but this package.
3
+ Python client for the [PDFops API](https://pdfops.dev): **fill** AcroForm PDFs, **merge** and **split** PDFs, run **page operations** (extract, delete, rotate, watermark, page numbers), **protect / unlock** and edit **metadata**, **inspect** form fields, and **generate invoices** with one HTTP call. No native dependencies, no headless browser, nothing to install but this package.
4
4
 
5
5
  Built for the moment `pypdf` / `PyPDFForm` stop cooperating — appearance streams that never render, `NeedAppearances` flags, encrypted government blanks, checkboxes that will not tick — and for runtimes where a PDF toolchain does not fit: Lambda, Cloud Functions, Airflow tasks, notebooks.
6
6
 
@@ -42,6 +42,21 @@ invoice = client.invoice({
42
42
  })
43
43
  ```
44
44
 
45
+ Page operations, one line each (all keyword-only options are optional and omitted when unset):
46
+
47
+ ```python
48
+ first_two = client.extract_pages("in.pdf", "1-2")
49
+ trimmed = client.delete_pages("in.pdf", "2,4-6")
50
+ turned = client.rotate("in.pdf", 90, pages="1")
51
+ res = client.split("in.pdf", ranges="1-2,3-") # or every=5; res.parts[0].pdf is bytes
52
+ marked = client.watermark("in.pdf", "DRAFT", opacity=0.2)
53
+ numbered = client.page_numbers("in.pdf", format="Page {n} of {total}", position="bottom-right")
54
+ opened = client.unlock("locked.pdf") # opened.pdf, opened.note ("not-encrypted" or None)
55
+ sealed = client.protect("in.pdf", user_password="s3cret", permissions=["print"]) # [] allows none
56
+ info = client.metadata("in.pdf") # info["page_count"], info["title"], ...
57
+ titled = client.set_metadata("in.pdf", title="Q3 report", keywords=["finance", "q3"])
58
+ ```
59
+
45
60
  PDF inputs may be `bytes`, a path (`str` / `pathlib.Path`), or a binary file object. Every PDF-producing call returns `bytes`.
46
61
 
47
62
  ## API
@@ -52,6 +67,16 @@ PDF inputs may be `bytes`, a path (`str` / `pathlib.Path`), or a binary file obj
52
67
  | `fill_form(pdf, fields, *, flatten=False)` | `POST /api/fill-form` | filled PDF `bytes` |
53
68
  | `merge([pdf, pdf, ...])` | `POST /api/merge` | merged PDF `bytes` |
54
69
  | `invoice(request)` | `POST /api/invoice` | invoice PDF `bytes` |
70
+ | `extract_pages(pdf, pages, *, password=None)` | `POST /api/extract-pages` | PDF `bytes` with only those pages, in that order |
71
+ | `delete_pages(pdf, pages, *, password=None)` | `POST /api/delete-pages` | PDF `bytes` without those pages |
72
+ | `rotate(pdf, degrees, *, pages=None, password=None)` | `POST /api/rotate` | rotated PDF `bytes` (90, 180, 270, -90) |
73
+ | `split(pdf, *, ranges=None, every=None, password=None)` | `POST /api/split` | `SplitResult` — `count`, `parts[]` of `pages`, `page_count`, `pdf` bytes |
74
+ | `watermark(pdf, text, *, opacity, size, color, rotation, position, pages, password)` | `POST /api/watermark` | watermarked PDF `bytes` |
75
+ | `page_numbers(pdf, *, format, position, size, start, margin, pages, password)` | `POST /api/page-numbers` | numbered PDF `bytes` |
76
+ | `unlock(pdf, password=None)` | `POST /api/unlock` | `UnlockResult` — `pdf` bytes plus optional `note` |
77
+ | `protect(pdf, *, user_password, owner_password, permissions, password)` | `POST /api/protect` | encrypted PDF `bytes` |
78
+ | `metadata(pdf, *, password=None)` | `POST /api/metadata` | `dict` — page count, page sizes, title, author, dates, form field count |
79
+ | `set_metadata(pdf, *, title, author, subject, creator, keywords, password)` | `POST /api/set-metadata` | PDF `bytes` with the info fields written |
55
80
  | `usage()` | `GET /api/usage` | `dict` — tier, limit, used, remaining, resets_at |
56
81
  | `signup(email)` | `POST /api/signup` | `None` — the key is emailed |
57
82
 
@@ -4,13 +4,13 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "pdfops"
7
- version = "0.1.0"
8
- description = "Python client for the PDFops API: fill AcroForm PDFs, merge PDFs, inspect form fields, generate invoices. One HTTP call, no native deps, no headless browser."
7
+ version = "0.2.0"
8
+ description = "Python client for the PDFops API: fill AcroForm PDFs, merge and split PDFs, page operations (extract, delete, rotate, watermark, page numbers), protect and unlock, edit metadata, inspect form fields, generate invoices. One HTTP call, no native deps, no headless browser."
9
9
  readme = "README.md"
10
10
  license = "MIT"
11
11
  requires-python = ">=3.9"
12
12
  authors = [{ name = "PDFops", email = "hello@pdfops.dev" }]
13
- keywords = ["pdf", "acroform", "fill-pdf", "merge-pdf", "pdf-forms", "invoice", "pypdf", "pdf-api"]
13
+ keywords = ["pdf", "acroform", "fill-pdf", "merge-pdf", "pdf-forms", "invoice", "pypdf", "pdf-api", "split-pdf", "rotate-pdf", "watermark-pdf", "pdf-metadata", "protect-pdf"]
14
14
  classifiers = [
15
15
  "Development Status :: 4 - Beta",
16
16
  "Intended Audience :: Developers",
@@ -15,16 +15,18 @@ Errors carry the API's structured ``{"error", "details"}`` body via
15
15
 
16
16
  from __future__ import annotations
17
17
 
18
+ import base64
18
19
  import json
19
20
  import os
20
21
  import uuid
22
+ from dataclasses import dataclass
21
23
  from pathlib import PurePath
22
24
  from typing import IO, Any, Callable, Dict, List, Mapping, Optional, Sequence, Tuple, Union
23
25
  from urllib import error as urlerror
24
26
  from urllib import request as urlrequest
25
27
 
26
- __all__ = ["PdfOps", "PdfOpsError", "PdfInput", "__version__"]
27
- __version__ = "0.1.0"
28
+ __all__ = ["PdfOps", "PdfOpsError", "PdfInput", "SplitPart", "SplitResult", "UnlockResult", "__version__"]
29
+ __version__ = "0.2.0"
28
30
 
29
31
  #: A PDF given as raw bytes, a filesystem path, or a binary file object.
30
32
  PdfInput = Union[bytes, bytearray, memoryview, str, "os.PathLike[str]", IO[bytes]]
@@ -37,6 +39,31 @@ DEFAULT_BASE_URL = "https://pdfops.dev"
37
39
  USER_AGENT = f"pdfops-python/{__version__}"
38
40
 
39
41
 
42
+ @dataclass(frozen=True)
43
+ class SplitPart:
44
+ """One output of :meth:`PdfOps.split`."""
45
+
46
+ #: The 1-based page spec this part covers, e.g. ``"3-5"``.
47
+ pages: str
48
+ page_count: int
49
+ #: The part's PDF bytes (decoded from the API's base64).
50
+ pdf: bytes
51
+
52
+
53
+ @dataclass(frozen=True)
54
+ class SplitResult:
55
+ count: int
56
+ parts: List[SplitPart]
57
+
58
+
59
+ @dataclass(frozen=True)
60
+ class UnlockResult:
61
+ pdf: bytes
62
+ #: The API's ``x-pdfops-note`` header: ``"not-encrypted"`` when the input had
63
+ #: no encryption (it is returned re-saved). ``None`` otherwise.
64
+ note: Optional[str] = None
65
+
66
+
40
67
  class PdfOpsError(Exception):
41
68
  """Structured API error. ``code`` is the API's stable ``error`` slug."""
42
69
 
@@ -130,9 +157,14 @@ class PdfOps:
130
157
  return h
131
158
 
132
159
  def _request(self, method: str, path: str, headers: Mapping[str, str], body: Optional[bytes]) -> bytes:
160
+ return self._request_full(method, path, headers, body)[1]
161
+
162
+ def _request_full(
163
+ self, method: str, path: str, headers: Mapping[str, str], body: Optional[bytes]
164
+ ) -> Tuple[Mapping[str, str], bytes]:
133
165
  status, _res_headers, data = self._send(method, f"{self.base_url}{path}", headers, body)
134
166
  if 200 <= status < 300:
135
- return data
167
+ return _res_headers, data
136
168
  code, details = f"http_{status}", (data.decode("utf-8", "replace") or f"HTTP {status}")
137
169
  try:
138
170
  parsed = json.loads(data.decode("utf-8"))
@@ -147,6 +179,18 @@ class PdfOps:
147
179
  ctype, body = _multipart(parts)
148
180
  return self._request("POST", path, self._headers({"Content-Type": ctype}), body)
149
181
 
182
+ def _post_fields(
183
+ self, path: str, pdf: PdfInput, fields: Mapping[str, Any]
184
+ ) -> Tuple[Mapping[str, str], bytes]:
185
+ """POST a PDF plus text fields; fields whose value is ``None`` are omitted
186
+ (a missing field means "default"; an empty string does not)."""
187
+ parts: List[Tuple[str, Optional[str], bytes, str]] = [("pdf", "input.pdf", _read_pdf(pdf), "application/pdf")]
188
+ for name, value in fields.items():
189
+ if value is not None:
190
+ parts.append((name, None, str(value).encode("utf-8"), "text/plain"))
191
+ ctype, body = _multipart(parts)
192
+ return self._request_full("POST", path, self._headers({"Content-Type": ctype}), body)
193
+
150
194
  # ── API ─────────────────────────────────────────────────────────────────
151
195
 
152
196
  def inspect(self, pdf: PdfInput) -> Dict[str, Any]:
@@ -193,6 +237,176 @@ class PdfOps:
193
237
  body = json.dumps(dict(request)).encode("utf-8")
194
238
  return self._request("POST", "/api/invoice", self._headers({"Content-Type": "application/json"}), body)
195
239
 
240
+ def extract_pages(self, pdf: PdfInput, pages: str, *, password: Optional[str] = None) -> bytes:
241
+ """Keep only the listed pages, in the order given (so it also reorders and
242
+ duplicates). ``pages`` is a 1-based spec such as ``"1-3,5,8-"``.
243
+
244
+ Errors: ``invalid_pages`` (a page out of range), ``encrypted_pdf``.
245
+ """
246
+ return self._post_fields("/api/extract-pages", pdf, {"pages": pages, "password": password})[1]
247
+
248
+ def delete_pages(self, pdf: PdfInput, pages: str, *, password: Optional[str] = None) -> bytes:
249
+ """Remove the listed pages and keep the rest in order. ``pages`` is a
250
+ 1-based spec such as ``"2,4-6,9-"``.
251
+
252
+ Errors: ``invalid_pages``, ``no_pages_left`` (every page deleted).
253
+ """
254
+ return self._post_fields("/api/delete-pages", pdf, {"pages": pages, "password": password})[1]
255
+
256
+ def rotate(
257
+ self, pdf: PdfInput, degrees: int, *, pages: Optional[str] = None, password: Optional[str] = None
258
+ ) -> bytes:
259
+ """Rotate pages clockwise by 90, 180, 270 or -90 degrees, added to each
260
+ page's existing rotation. Omit ``pages`` to rotate every page.
261
+
262
+ Errors: ``invalid_degrees``, ``invalid_pages``.
263
+ """
264
+ return self._post_fields("/api/rotate", pdf, {"degrees": degrees, "pages": pages, "password": password})[1]
265
+
266
+ def split(
267
+ self,
268
+ pdf: PdfInput,
269
+ *,
270
+ ranges: Optional[str] = None,
271
+ every: Optional[int] = None,
272
+ password: Optional[str] = None,
273
+ ) -> SplitResult:
274
+ """Split one PDF into several, by explicit ``ranges`` (``"1-2,3-5"`` gives
275
+ two parts) or fixed-size chunks (``every``). Give exactly one of the two.
276
+
277
+ Errors: ``invalid_split``, ``invalid_every``, ``invalid_pages``,
278
+ ``too_many_parts``, ``output_too_large``.
279
+ """
280
+ _, data = self._post_fields("/api/split", pdf, {"ranges": ranges, "every": every, "password": password})
281
+ body = json.loads(data.decode("utf-8"))
282
+ parts = [
283
+ SplitPart(pages=p["pages"], page_count=p["page_count"], pdf=base64.b64decode(p["pdf"]))
284
+ for p in body["parts"]
285
+ ]
286
+ return SplitResult(count=body["count"], parts=parts)
287
+
288
+ def watermark(
289
+ self,
290
+ pdf: PdfInput,
291
+ text: str,
292
+ *,
293
+ opacity: Optional[float] = None,
294
+ size: Optional[float] = None,
295
+ color: Optional[str] = None,
296
+ rotation: Optional[float] = None,
297
+ position: Optional[str] = None,
298
+ pages: Optional[str] = None,
299
+ password: Optional[str] = None,
300
+ ) -> bytes:
301
+ """Stamp a diagonal text watermark (default: centered, 45 degrees, grey
302
+ ``#808080``, 15% opacity, 48 pt). Standard Helvetica only. ``position`` is
303
+ ``"center"``, ``"top"`` or ``"bottom"``.
304
+
305
+ Errors: ``missing_text``, ``text_too_long``, ``unsupported_characters``,
306
+ ``invalid_parameter``, ``invalid_pages``.
307
+ """
308
+ fields = {
309
+ "text": text, "opacity": opacity, "size": size, "color": color,
310
+ "rotation": rotation, "position": position, "pages": pages, "password": password,
311
+ }
312
+ return self._post_fields("/api/watermark", pdf, fields)[1]
313
+
314
+ def page_numbers(
315
+ self,
316
+ pdf: PdfInput,
317
+ *,
318
+ format: Optional[str] = None,
319
+ position: Optional[str] = None,
320
+ size: Optional[float] = None,
321
+ start: Optional[int] = None,
322
+ margin: Optional[float] = None,
323
+ pages: Optional[str] = None,
324
+ password: Optional[str] = None,
325
+ ) -> bytes:
326
+ """Print page numbers from a template with ``{n}`` and ``{total}`` (default
327
+ ``"{n} / {total}"``, bottom-center, 10 pt). Page i shows ``start + i - 1``.
328
+ ``position`` is one of ``bottom-center|bottom-right|bottom-left|top-center|top-right|top-left``.
329
+
330
+ Errors: ``unsupported_characters``, ``invalid_pages``.
331
+ """
332
+ fields = {
333
+ "format": format, "position": position, "size": size, "start": start,
334
+ "margin": margin, "pages": pages, "password": password,
335
+ }
336
+ return self._post_fields("/api/page-numbers", pdf, fields)[1]
337
+
338
+ def unlock(self, pdf: PdfInput, password: Optional[str] = None) -> UnlockResult:
339
+ """Save a PDF without encryption so print/copy/modify restrictions are gone.
340
+
341
+ Owner-locked files with an empty user password need no ``password``; this
342
+ does not crack unknown passwords (``encrypted_pdf``). ``note`` is
343
+ ``"not-encrypted"`` when the input had no encryption and was only re-saved.
344
+ """
345
+ headers, data = self._post_fields("/api/unlock", pdf, {"password": password})
346
+ note = next((v for k, v in headers.items() if k.lower() == "x-pdfops-note"), None)
347
+ return UnlockResult(pdf=data, note=note or None)
348
+
349
+ def protect(
350
+ self,
351
+ pdf: PdfInput,
352
+ *,
353
+ user_password: Optional[str] = None,
354
+ owner_password: Optional[str] = None,
355
+ permissions: Optional[Sequence[str]] = None,
356
+ password: Optional[str] = None,
357
+ ) -> bytes:
358
+ """Encrypt a PDF. Give at least one of ``user_password`` (needed to open the
359
+ result) and ``owner_password`` (lifts restrictions), each 1-32 Latin-1 chars.
360
+ ``permissions`` lists what stays ALLOWED (``print``, ``copy``, ``modify``,
361
+ ``annotate``, ``fill-forms``); omit for the default, ``[]`` allows none.
362
+ ``password`` opens an encrypted input.
363
+
364
+ Errors: ``missing_password``, ``invalid_password``, ``invalid_permissions``.
365
+ """
366
+ fields = {
367
+ "user_password": user_password,
368
+ "owner_password": owner_password,
369
+ "permissions": None if permissions is None else ",".join(permissions),
370
+ "password": password,
371
+ }
372
+ return self._post_fields("/api/protect", pdf, fields)[1]
373
+
374
+ def metadata(self, pdf: PdfInput, *, password: Optional[str] = None) -> Dict[str, Any]:
375
+ """Read a PDF's page count, per-page size and rotation, document info (title,
376
+ author, dates, ...), encryption flag and form field count.
377
+
378
+ Returns ``{"page_count", "pages": [{"width", "height", "rotation"}], "title",
379
+ "author", "subject", "keywords", "creator", "producer", "creation_date",
380
+ "modification_date", "encrypted", "has_form", "form_field_count",
381
+ "form_field_count_capped"}``; absent text/date values are ``None``.
382
+ """
383
+ _, data = self._post_fields("/api/metadata", pdf, {"password": password})
384
+ return json.loads(data.decode("utf-8"))
385
+
386
+ def set_metadata(
387
+ self,
388
+ pdf: PdfInput,
389
+ *,
390
+ title: Optional[str] = None,
391
+ author: Optional[str] = None,
392
+ subject: Optional[str] = None,
393
+ creator: Optional[str] = None,
394
+ keywords: Optional[Sequence[str]] = None,
395
+ password: Optional[str] = None,
396
+ ) -> bytes:
397
+ """Write document info fields into a PDF; give at least one. An empty string
398
+ sets an empty value. The output is saved unencrypted.
399
+ """
400
+ fields = {
401
+ "title": title,
402
+ "author": author,
403
+ "subject": subject,
404
+ "creator": creator,
405
+ "keywords": None if keywords is None else ",".join(keywords),
406
+ "password": password,
407
+ }
408
+ return self._post_fields("/api/set-metadata", pdf, fields)[1]
409
+
196
410
  def usage(self) -> Dict[str, Any]:
197
411
  """Quota state for the configured key: tier, limit, used, remaining, period, resets_at."""
198
412
  if not self.api_key:
@@ -1,6 +1,6 @@
1
1
  """Offline tests for the pdfops client — a fake transport records every request.
2
2
 
3
- Run: python3 -m unittest discover -s python/tests -t python
3
+ Run: python3 -m unittest discover -s tests -t .
4
4
  """
5
5
 
6
6
  from __future__ import annotations
@@ -151,6 +151,132 @@ class Endpoints(unittest.TestCase):
151
151
  self.assertEqual(json.loads(body), {"email": "dev@example.com"})
152
152
 
153
153
 
154
+ def fields_of(t: "FakeTransport"):
155
+ """Last call -> (url, [(name, filename, value-or-bytes)]) with text parts decoded."""
156
+ _, url, headers, body = t.calls[-1]
157
+ return url, [(n, fn, d) for n, fn, _c, d in parts_of(body, headers["Content-Type"])]
158
+
159
+
160
+ def text_fields(t: "FakeTransport"):
161
+ url, parts = fields_of(t)
162
+ assert parts[0] == ("pdf", "input.pdf", PDF)
163
+ return url, [(n, d.decode()) for n, _fn, d in parts[1:]]
164
+
165
+
166
+ class PageOperations(unittest.TestCase):
167
+ def test_extract_and_delete_pages(self):
168
+ for method, path in (("extract_pages", "extract-pages"), ("delete_pages", "delete-pages")):
169
+ t = FakeTransport(body=PDF)
170
+ self.assertEqual(getattr(PdfOps(transport=t), method)(PDF, "1-3,5"), PDF)
171
+ self.assertEqual(text_fields(t), (f"https://pdfops.dev/api/{path}", [("pages", "1-3,5")]))
172
+ getattr(PdfOps(transport=t), method)(PDF, "2", password="pw")
173
+ self.assertEqual(text_fields(t)[1], [("pages", "2"), ("password", "pw")])
174
+
175
+ def test_rotate_sends_degrees_as_string_and_omits_pages(self):
176
+ t = FakeTransport(body=PDF)
177
+ PdfOps(transport=t).rotate(PDF, -90)
178
+ self.assertEqual(text_fields(t), ("https://pdfops.dev/api/rotate", [("degrees", "-90")]))
179
+ PdfOps(transport=t).rotate(PDF, 180, pages="1,3", password="pw")
180
+ self.assertEqual(text_fields(t)[1], [("degrees", "180"), ("pages", "1,3"), ("password", "pw")])
181
+
182
+ def test_split_decodes_base64_parts(self):
183
+ import base64
184
+ api = {"count": 2, "parts": [
185
+ {"pages": "1-2", "page_count": 2, "pdf": base64.b64encode(b"%PDF-A").decode()},
186
+ {"pages": "3", "page_count": 1, "pdf": base64.b64encode(b"%PDF-B").decode()},
187
+ ]}
188
+ t = FakeTransport(body=json.dumps(api).encode())
189
+ res = PdfOps(transport=t).split(PDF, ranges="1-2,3")
190
+ self.assertEqual(text_fields(t), ("https://pdfops.dev/api/split", [("ranges", "1-2,3")]))
191
+ self.assertEqual(res.count, 2)
192
+ self.assertEqual([(p.pages, p.page_count, p.pdf) for p in res.parts], [("1-2", 2, b"%PDF-A"), ("3", 1, b"%PDF-B")])
193
+ PdfOps(transport=t).split(PDF, every=5, password="pw")
194
+ self.assertEqual(text_fields(t)[1], [("every", "5"), ("password", "pw")])
195
+
196
+ def test_watermark_all_options_and_defaults_omitted(self):
197
+ t = FakeTransport(body=PDF)
198
+ PdfOps(transport=t).watermark(PDF, "DRAFT")
199
+ self.assertEqual(text_fields(t), ("https://pdfops.dev/api/watermark", [("text", "DRAFT")]))
200
+ PdfOps(transport=t).watermark(
201
+ PDF, "DRAFT", opacity=0.25, size=36, color="#ff0000", rotation=30,
202
+ position="top", pages="1-2", password="pw",
203
+ )
204
+ self.assertEqual(text_fields(t)[1], [
205
+ ("text", "DRAFT"), ("opacity", "0.25"), ("size", "36"), ("color", "#ff0000"),
206
+ ("rotation", "30"), ("position", "top"), ("pages", "1-2"), ("password", "pw"),
207
+ ])
208
+
209
+ def test_text_parts_are_utf8_text_plain(self):
210
+ t = FakeTransport(body=PDF)
211
+ PdfOps(transport=t).watermark(PDF, "Entw\u00fcrfe \u2014 \u00e9")
212
+ _, _, headers, body = t.calls[-1]
213
+ name, _fn, ctype, data = parts_of(body, headers["Content-Type"])[1]
214
+ self.assertEqual((name, ctype, data), ("text", "text/plain", "Entw\u00fcrfe \u2014 \u00e9".encode("utf-8")))
215
+
216
+ def test_page_numbers_options(self):
217
+ t = FakeTransport(body=PDF)
218
+ PdfOps(transport=t).page_numbers(PDF)
219
+ self.assertEqual(text_fields(t), ("https://pdfops.dev/api/page-numbers", []))
220
+ PdfOps(transport=t).page_numbers(
221
+ PDF, format="Page {n} of {total}", position="top-left", size=12, start=0, margin=20,
222
+ pages="2-", password="pw",
223
+ )
224
+ self.assertEqual(text_fields(t)[1], [
225
+ ("format", "Page {n} of {total}"), ("position", "top-left"), ("size", "12"),
226
+ ("start", "0"), ("margin", "20"), ("pages", "2-"), ("password", "pw"),
227
+ ])
228
+
229
+ def test_unlock_note_header(self):
230
+ t = FakeTransport(body=PDF, headers={"x-pdfops-note": "not-encrypted"})
231
+ res = PdfOps(transport=t).unlock(PDF)
232
+ self.assertEqual(text_fields(t), ("https://pdfops.dev/api/unlock", []))
233
+ self.assertEqual((res.pdf, res.note), (PDF, "not-encrypted"))
234
+ res = PdfOps(transport=FakeTransport(body=PDF, headers={"X-Pdfops-Note": "not-encrypted"})).unlock(PDF)
235
+ self.assertEqual(res.note, "not-encrypted")
236
+ t = FakeTransport(body=PDF)
237
+ res = PdfOps(transport=t).unlock(PDF, "pw")
238
+ self.assertEqual((res.pdf, res.note), (PDF, None))
239
+ self.assertEqual(text_fields(t)[1], [("password", "pw")])
240
+
241
+ def test_protect_joins_permissions_and_empty_list_allows_none(self):
242
+ t = FakeTransport(body=PDF)
243
+ PdfOps(transport=t).protect(PDF, user_password="u", owner_password="o", permissions=["print", "copy"], password="pw")
244
+ self.assertEqual(text_fields(t), ("https://pdfops.dev/api/protect", [
245
+ ("user_password", "u"), ("owner_password", "o"), ("permissions", "print,copy"), ("password", "pw"),
246
+ ]))
247
+ PdfOps(transport=t).protect(PDF, user_password="u", permissions=[])
248
+ self.assertEqual(text_fields(t)[1], [("user_password", "u"), ("permissions", "")])
249
+ PdfOps(transport=t).protect(PDF, owner_password="o")
250
+ self.assertEqual(text_fields(t)[1], [("owner_password", "o")])
251
+
252
+ def test_metadata_returns_json_dict(self):
253
+ api = {"page_count": 2, "pages": [{"width": 612, "height": 792, "rotation": 0}], "title": None,
254
+ "encrypted": False, "has_form": False, "form_field_count": 0, "form_field_count_capped": False}
255
+ t = FakeTransport(body=json.dumps(api).encode())
256
+ self.assertEqual(PdfOps(transport=t).metadata(PDF), api)
257
+ self.assertEqual(text_fields(t), ("https://pdfops.dev/api/metadata", []))
258
+ PdfOps(transport=t).metadata(PDF, password="pw")
259
+ self.assertEqual(text_fields(t)[1], [("password", "pw")])
260
+
261
+ def test_set_metadata_joins_keywords_and_keeps_empty_strings(self):
262
+ t = FakeTransport(body=PDF)
263
+ PdfOps(transport=t).set_metadata(
264
+ PDF, title="T", author="A", subject="S", creator="C", keywords=["a", "b"], password="pw"
265
+ )
266
+ self.assertEqual(text_fields(t), ("https://pdfops.dev/api/set-metadata", [
267
+ ("title", "T"), ("author", "A"), ("subject", "S"), ("creator", "C"),
268
+ ("keywords", "a,b"), ("password", "pw"),
269
+ ]))
270
+ PdfOps(transport=t).set_metadata(PDF, title="")
271
+ self.assertEqual(text_fields(t)[1], [("title", "")])
272
+
273
+ def test_page_op_errors_surface_slug(self):
274
+ t = FakeTransport(status=400, body=json.dumps({"error": "invalid_pages", "details": "page 9 out of range"}).encode())
275
+ with self.assertRaises(PdfOpsError) as cm:
276
+ PdfOps(transport=t).extract_pages(PDF, "9")
277
+ self.assertEqual(cm.exception.code, "invalid_pages")
278
+
279
+
154
280
  class Errors(unittest.TestCase):
155
281
  def test_structured_api_error(self):
156
282
  t = FakeTransport(status=422, body=json.dumps({"error": "unknown_field", "details": "No field named Nmae"}).encode())
File without changes
File without changes
File without changes
File without changes