formfeed 0.3.24__tar.gz → 0.3.26__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,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: formfeed
3
- Version: 0.3.24
3
+ Version: 0.3.26
4
4
  Summary: Formfeed API client: template-based PDF and image generation (sync and async, httpx).
5
5
  Project-URL: Homepage, https://formfeed.dev
6
6
  Project-URL: Documentation, https://docs.formfeed.dev/api/sdks/python
@@ -72,6 +72,13 @@ docx = client.templates.version_file("offer", "latest") # the document's bytes
72
72
  # any office document to PDF (Word, Excel, PowerPoint, OpenDocument, RTF)
73
73
  with open("report.xlsx", "rb") as f:
74
74
  pdf = client.pdf.convert(file=f, single_page_sheets=True)
75
+
76
+ # fill a PDF form by the field names info lists, and redact a name wherever it stands
77
+ form = client.pdf.info("antrag.pdf").form
78
+ filled = client.pdf.fill("antrag.pdf", fields={"customer.name": "Erika Mustermann"}, flatten=True)
79
+ with open("invoice.pdf", "rb") as f:
80
+ redacted = client.pdf.redact(file=f, text=["Max Mustermann"])
81
+ # and split, compress or draw pages: client.pdf.split, .compress, .to_image
75
82
  ```
76
83
 
77
84
  Webhooks:
@@ -42,6 +42,13 @@ docx = client.templates.version_file("offer", "latest") # the document's bytes
42
42
  # any office document to PDF (Word, Excel, PowerPoint, OpenDocument, RTF)
43
43
  with open("report.xlsx", "rb") as f:
44
44
  pdf = client.pdf.convert(file=f, single_page_sheets=True)
45
+
46
+ # fill a PDF form by the field names info lists, and redact a name wherever it stands
47
+ form = client.pdf.info("antrag.pdf").form
48
+ filled = client.pdf.fill("antrag.pdf", fields={"customer.name": "Erika Mustermann"}, flatten=True)
49
+ with open("invoice.pdf", "rb") as f:
50
+ redacted = client.pdf.redact(file=f, text=["Max Mustermann"])
51
+ # and split, compress or draw pages: client.pdf.split, .compress, .to_image
45
52
  ```
46
53
 
47
54
  Webhooks:
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "formfeed"
7
- version = "0.3.24"
7
+ version = "0.3.26"
8
8
  description = "Formfeed API client: template-based PDF and image generation (sync and async, httpx)."
9
9
  readme = "README.md"
10
10
  # PEP 639: the SPDX expression replaces the licence classifier, the two must not be combined
@@ -12,7 +12,13 @@ from .models import (
12
12
  LibraryFilePage,
13
13
  ListenSession,
14
14
  PdfInfo,
15
+ FormFill,
16
+ FormFillSkip,
17
+ FormFillWarning,
18
+ PdfForm,
19
+ PdfFormField,
15
20
  Render,
21
+ RenderOutput,
16
22
  RenderInput,
17
23
  RenderPage,
18
24
  SharedPartial,
@@ -57,7 +63,13 @@ __all__ = [
57
63
  "LibraryFilePage",
58
64
  "ListenSession",
59
65
  "PdfInfo",
66
+ "FormFill",
67
+ "FormFillSkip",
68
+ "FormFillWarning",
69
+ "PdfForm",
70
+ "PdfFormField",
60
71
  "Render",
72
+ "RenderOutput",
61
73
  "RenderInput",
62
74
  "RenderPage",
63
75
  "SharedPartial",
@@ -90,4 +102,4 @@ __all__ = [
90
102
  "verify_webhook_signature",
91
103
  ]
92
104
 
93
- __version__ = "0.3.24"
105
+ __version__ = "0.3.26"
@@ -343,6 +343,34 @@ def _split_file(fields: dict[str, Any]) -> tuple[Any, str | None, dict[str, Any]
343
343
  return file, file_name, rest
344
344
 
345
345
 
346
+ def _tool_fields(fields: dict[str, Any]) -> dict[str, Any]:
347
+ """A PDF tool's own fields without those left at their default (``None``), but redact's ``fill``, whose
348
+ ``None`` draws no box."""
349
+ return {key: value for key, value in fields.items() if value is not None or key == "fill"}
350
+
351
+
352
+ def _pdf_parts(file: bytes | Any, file_name: str | None, fields: dict[str, Any]) -> tuple[dict[str, Any], dict[str, str]]:
353
+ """An uploaded PDF under ``file`` (bytes, or a binary file object read once, so that a retry sends the same
354
+ bytes), the fields beside it as the API reads them; a ``None`` fill goes as the JSON text ``null``."""
355
+ own = getattr(file, "name", None)
356
+ name = file_name or (os.path.basename(own) if isinstance(own, str) else None) or "document.pdf"
357
+ data = file.read() if hasattr(file, "read") else file
358
+ form = {key: "null" if value is None else _form_value(value) for key, value in _tool_fields(fields).items()}
359
+ return {"file": (name, data, "application/pdf")}, form
360
+
361
+
362
+ def _pdf_request(
363
+ source: Render | LibraryFile | str | None, file: bytes | Any, file_name: str | None, fields: dict[str, Any]
364
+ ) -> tuple[dict[str, Any] | None, dict[str, Any] | None, dict[str, str] | None]:
365
+ """A PDF tool's request as body, files and form: the stored source's id as JSON, or the upload as multipart."""
366
+ if (source is None) == (file is None):
367
+ raise FormfeedError("invalid_request", "pass either source or file")
368
+ if file is not None:
369
+ files, form = _pdf_parts(file, file_name, fields)
370
+ return None, files, form
371
+ return {**_tool_fields(fields), "source": _source_id(source)}, None, None # type: ignore[arg-type]
372
+
373
+
346
374
  def _files_query(prefix: str | None, limit: int | None, cursor: str | None) -> str:
347
375
  params = httpx.QueryParams(_query(prefix=prefix, limit=limit, cursor=cursor))
348
376
  return f"/files{'?' + str(params) if params else ''}"
@@ -650,8 +678,10 @@ class _Workspaces:
650
678
 
651
679
 
652
680
  class _Pdf:
653
- """PDF tools on outputs of earlier renders. merge, protect and watermark return a new render
654
- (0.5 units each on live keys) and send an idempotency key; info is free."""
681
+ """PDF tools on outputs of earlier renders and PDFs of the file library; split, compress, to_image, redact,
682
+ fill and info also take an uploaded ``file`` (bytes or a binary file object), which is never stored. Every
683
+ tool but info returns a new render and sends an idempotency key, on the Starter plan and above: 0.5 units
684
+ each on live keys, to_image one unit per picture. info is free."""
655
685
 
656
686
  def __init__(self, client: Formfeed) -> None:
657
687
  self._c = client
@@ -675,8 +705,97 @@ class _Pdf:
675
705
  body = {**_options(options), "source": _source_id(source), **_watermark_body(text, image)}
676
706
  return Render.model_validate(self._c.request("POST", "/pdf/watermark", body, idempotency_key=idempotency_key or str(uuid.uuid4())))
677
707
 
678
- def info(self, source: Render | str) -> PdfInfo:
679
- return PdfInfo.model_validate(self._c.request("POST", "/pdf/info", {"source": _source_id(source)}))
708
+ def info(self, source: Render | LibraryFile | str | None = None, *, file: bytes | Any = None, file_name: str | None = None) -> PdfInfo:
709
+ """Page count, page sizes, encryption, metadata and the form, with every field's name, type, value and
710
+ options, which is how a form's names are found for ``fill``. Free; creates no render."""
711
+ body, files, form = _pdf_request(source, file, file_name, {})
712
+ return PdfInfo.model_validate(self._c.request("POST", "/pdf/info", body, files=files, form=form))
713
+
714
+ def _tool(
715
+ self, path: str, source: Render | LibraryFile | str | None, file: Any, file_name: str | None, fields: dict[str, Any], idempotency_key: str | None
716
+ ) -> Render:
717
+ body, files, form = _pdf_request(source, file, file_name, fields)
718
+ key = idempotency_key or str(uuid.uuid4())
719
+ return Render.model_validate(self._c.request("POST", path, body, files=files, form=form, idempotency_key=key))
720
+
721
+ def split(
722
+ self,
723
+ source: Render | LibraryFile | str | None = None,
724
+ *,
725
+ file: bytes | Any = None,
726
+ file_name: str | None = None,
727
+ every: int | None = None,
728
+ ranges: list[str] | None = None,
729
+ idempotency_key: str | None = None,
730
+ **options: Any,
731
+ ) -> Render:
732
+ """Cuts a PDF into parts, ``every`` pages each or one per entry of ``ranges`` (page selections such as
733
+ ``"1-3,5"`` or ``"4-"``). The render's output is a ZIP of the parts, or the PDF itself for one part."""
734
+ return self._tool("/pdf/split", source, file, file_name, {"every": every, "ranges": ranges, **options}, idempotency_key)
735
+
736
+ def compress(
737
+ self, source: Render | LibraryFile | str | None = None, *, file: bytes | Any = None, file_name: str | None = None, idempotency_key: str | None = None, **options: Any
738
+ ) -> Render:
739
+ """Makes a PDF smaller; the render keeps the source when it cannot."""
740
+ return self._tool("/pdf/compress", source, file, file_name, options, idempotency_key)
741
+
742
+ def to_image(
743
+ self,
744
+ source: Render | LibraryFile | str | None = None,
745
+ *,
746
+ file: bytes | Any = None,
747
+ file_name: str | None = None,
748
+ pages: str | None = None,
749
+ format: str | None = None,
750
+ dpi: int | None = None,
751
+ quality: int | None = None,
752
+ idempotency_key: str | None = None,
753
+ **options: Any,
754
+ ) -> Render:
755
+ """Draws ``pages`` (``"1"``, ``"1-3,5"``, ``"2-"``; every page when omitted) as ``png`` or ``jpg`` pictures at
756
+ ``dpi`` (36 to 300, 150 by default): one page answers the picture, several a ZIP of them named by page."""
757
+ fields = {"pages": pages, "format": format, "dpi": dpi, "quality": quality, **options}
758
+ return self._tool("/pdf/to-image", source, file, file_name, fields, idempotency_key)
759
+
760
+ def redact(
761
+ self,
762
+ source: Render | LibraryFile | str | None = None,
763
+ *,
764
+ file: bytes | Any = None,
765
+ file_name: str | None = None,
766
+ regions: list[dict[str, float]] | None = None,
767
+ text: str | list[str] | None = None,
768
+ match_case: bool | None = None,
769
+ whole_words: bool | None = None,
770
+ fill: str | None = "#000000",
771
+ idempotency_key: str | None = None,
772
+ **options: Any,
773
+ ) -> Render:
774
+ """Removes what lies under ``regions`` (``{"page", "x", "y", "width", "height"}`` in points from the page's
775
+ top-left corner, as a viewer shows it) and every place where a ``text`` stands, from the file itself; a box
776
+ in ``fill`` is drawn over each, none with ``fill=None``. The result is read again: text that is still there
777
+ fails with ``redaction_incomplete``, which names rectangles and texts by number, never a text."""
778
+ fields = {"regions": regions, "text": text, "match_case": match_case, "whole_words": whole_words, "fill": fill, **options}
779
+ return self._tool("/pdf/redact", source, file, file_name, fields, idempotency_key)
780
+
781
+ def fill(
782
+ self,
783
+ source: Render | LibraryFile | str | None = None,
784
+ *,
785
+ file: bytes | Any = None,
786
+ file_name: str | None = None,
787
+ fields: dict[str, Any] | None = None,
788
+ flatten: bool | None = None,
789
+ strict: bool | None = None,
790
+ idempotency_key: str | None = None,
791
+ **options: Any,
792
+ ) -> Render:
793
+ """Fills a form's ``fields`` by their full names, as ``info`` lists them: text (a number too), ``True`` or
794
+ ``False`` for a check box, an option, or a list box's options. ``flatten=True`` draws the values into the
795
+ pages; ``strict=False`` leaves unknown names and values a field does not take out and lists them in
796
+ ``form.skipped``. No calculation or display format of the form runs, and the values are never stored."""
797
+ body = {"fields": fields, "flatten": flatten, "strict": strict, **options}
798
+ return self._tool("/pdf/fill", source, file, file_name, body, idempotency_key)
680
799
 
681
800
  def convert(
682
801
  self,
@@ -1092,8 +1211,82 @@ class _AsyncPdf:
1092
1211
  body = {**_options(options), "source": _source_id(source), **_watermark_body(text, image)}
1093
1212
  return Render.model_validate(await self._c.request("POST", "/pdf/watermark", body, idempotency_key=idempotency_key or str(uuid.uuid4())))
1094
1213
 
1095
- async def info(self, source: Render | str) -> PdfInfo:
1096
- return PdfInfo.model_validate(await self._c.request("POST", "/pdf/info", {"source": _source_id(source)}))
1214
+ async def info(self, source: Render | LibraryFile | str | None = None, *, file: bytes | Any = None, file_name: str | None = None) -> PdfInfo:
1215
+ body, files, form = _pdf_request(source, file, file_name, {})
1216
+ return PdfInfo.model_validate(await self._c.request("POST", "/pdf/info", body, files=files, form=form))
1217
+
1218
+ async def _tool(
1219
+ self, path: str, source: Render | LibraryFile | str | None, file: Any, file_name: str | None, fields: dict[str, Any], idempotency_key: str | None
1220
+ ) -> Render:
1221
+ body, files, form = _pdf_request(source, file, file_name, fields)
1222
+ key = idempotency_key or str(uuid.uuid4())
1223
+ return Render.model_validate(await self._c.request("POST", path, body, files=files, form=form, idempotency_key=key))
1224
+
1225
+ async def split(
1226
+ self,
1227
+ source: Render | LibraryFile | str | None = None,
1228
+ *,
1229
+ file: bytes | Any = None,
1230
+ file_name: str | None = None,
1231
+ every: int | None = None,
1232
+ ranges: list[str] | None = None,
1233
+ idempotency_key: str | None = None,
1234
+ **options: Any,
1235
+ ) -> Render:
1236
+ return await self._tool("/pdf/split", source, file, file_name, {"every": every, "ranges": ranges, **options}, idempotency_key)
1237
+
1238
+ async def compress(
1239
+ self, source: Render | LibraryFile | str | None = None, *, file: bytes | Any = None, file_name: str | None = None, idempotency_key: str | None = None, **options: Any
1240
+ ) -> Render:
1241
+ return await self._tool("/pdf/compress", source, file, file_name, options, idempotency_key)
1242
+
1243
+ async def to_image(
1244
+ self,
1245
+ source: Render | LibraryFile | str | None = None,
1246
+ *,
1247
+ file: bytes | Any = None,
1248
+ file_name: str | None = None,
1249
+ pages: str | None = None,
1250
+ format: str | None = None,
1251
+ dpi: int | None = None,
1252
+ quality: int | None = None,
1253
+ idempotency_key: str | None = None,
1254
+ **options: Any,
1255
+ ) -> Render:
1256
+ fields = {"pages": pages, "format": format, "dpi": dpi, "quality": quality, **options}
1257
+ return await self._tool("/pdf/to-image", source, file, file_name, fields, idempotency_key)
1258
+
1259
+ async def redact(
1260
+ self,
1261
+ source: Render | LibraryFile | str | None = None,
1262
+ *,
1263
+ file: bytes | Any = None,
1264
+ file_name: str | None = None,
1265
+ regions: list[dict[str, float]] | None = None,
1266
+ text: str | list[str] | None = None,
1267
+ match_case: bool | None = None,
1268
+ whole_words: bool | None = None,
1269
+ fill: str | None = "#000000",
1270
+ idempotency_key: str | None = None,
1271
+ **options: Any,
1272
+ ) -> Render:
1273
+ fields = {"regions": regions, "text": text, "match_case": match_case, "whole_words": whole_words, "fill": fill, **options}
1274
+ return await self._tool("/pdf/redact", source, file, file_name, fields, idempotency_key)
1275
+
1276
+ async def fill(
1277
+ self,
1278
+ source: Render | LibraryFile | str | None = None,
1279
+ *,
1280
+ file: bytes | Any = None,
1281
+ file_name: str | None = None,
1282
+ fields: dict[str, Any] | None = None,
1283
+ flatten: bool | None = None,
1284
+ strict: bool | None = None,
1285
+ idempotency_key: str | None = None,
1286
+ **options: Any,
1287
+ ) -> Render:
1288
+ body = {"fields": fields, "flatten": flatten, "strict": strict, **options}
1289
+ return await self._tool("/pdf/fill", source, file, file_name, body, idempotency_key)
1097
1290
 
1098
1291
  async def convert(
1099
1292
  self,
@@ -10,6 +10,9 @@ Region = Literal["eu", "us"]
10
10
  Engine = Literal["jinja2", "liquid", "handlebars"]
11
11
  #: A Word template produces ``docx`` or ``pdf``, a PowerPoint template ``pptx`` or ``pdf``.
12
12
  OutputFormat = Literal["pdf", "png", "jpg", "webp", "docx", "pptx"]
13
+ #: What a render made: one of the output formats, or ``zip``, which holds the files of a PDF tool that made
14
+ #: several (``pdf.split``, ``pdf.to_image``). Never something a render asks for.
15
+ RenderOutput = Literal["pdf", "png", "jpg", "webp", "docx", "pptx", "zip"]
13
16
  TemplateKind = Literal["pdf", "image", "docx", "pptx"]
14
17
  RenderStatus = Literal["queued", "rendering", "succeeded", "failed"]
15
18
 
@@ -279,6 +282,30 @@ class Pdfa(_Model):
279
282
  truncated: bool = False
280
283
 
281
284
 
285
+ class FormFillSkip(_Model):
286
+ field: str
287
+ #: ``unknown`` for a name the form does not have, ``invalid`` for a value its field does not take.
288
+ reason: str
289
+
290
+
291
+ class FormFillWarning(_Model):
292
+ field: str
293
+ #: ``calculation_not_run`` or ``format_not_applied``.
294
+ code: str
295
+
296
+
297
+ class FormFill(_Model):
298
+ """What a fill did (``pdf.fill``). Entries name fields, never their values."""
299
+
300
+ filled: int = 0
301
+ #: In lenient mode (``strict=False``), what was left out.
302
+ skipped: list[FormFillSkip] = []
303
+ #: Calculations and display formats of the form that no viewer has run.
304
+ warnings: list[FormFillWarning] = []
305
+ #: The form was a hybrid of an AcroForm and XFA; its XFA part was removed.
306
+ xfa_removed: bool = False
307
+
308
+
282
309
  class Render(_Model):
283
310
  id: str
284
311
  status: RenderStatus
@@ -303,6 +330,8 @@ class Render(_Model):
303
330
  accessibility: Accessibility | None = None
304
331
  #: The validator's verdict on the file as PDF/A (``settings={"pdf": {"pdfa": "2b"}}`` or the template's settings); ``None`` unless it was set.
305
332
  pdfa: Pdfa | None = None
333
+ #: What a fill did (``pdf.fill``); ``None`` for every other render.
334
+ form: FormFill | None = None
306
335
  timings: dict[str, float] | None = None
307
336
  error: dict[str, Any] | None = None
308
337
  meta: dict[str, Any] = {}
@@ -537,12 +566,42 @@ class PdfPage(_Model):
537
566
  height_mm: float | None = None
538
567
 
539
568
 
569
+ class PdfFormField(_Model):
570
+ #: The full name, parts joined by dots, which ``pdf.fill`` takes.
571
+ name: str
572
+ #: What the field is for, from its tooltip.
573
+ label: str | None = None
574
+ #: ``text``, ``checkbox``, ``radio``, ``dropdown``, ``listbox``, ``signature`` or ``button``.
575
+ type: str
576
+ value: bool | str | list[str] | None = None
577
+ #: What ``pdf.fill`` takes for a choice, a radio group, or a check box with several on-values.
578
+ options: list[str] | None = None
579
+ required: bool = False
580
+ readonly: bool = False
581
+ #: Its value comes from a calculation a viewer runs, which filling does not.
582
+ calculated: bool = False
583
+ #: The display format a viewer applies, which filling does not.
584
+ format: str | None = None
585
+ #: Every page with a widget of the field.
586
+ pages: list[int] = []
587
+
588
+
589
+ class PdfForm(_Model):
590
+ #: ``acroform``, ``hybrid`` (with an XFA part), ``xfa`` (which ``pdf.fill`` refuses), ``None`` without a form.
591
+ type: str | None = None
592
+ #: The form holds a signature; ``pdf.fill`` refuses such a file.
593
+ signed: bool = False
594
+ fields: list[PdfFormField] = []
595
+
596
+
540
597
  class PdfInfo(_Model):
541
598
  source: str | None = None
542
599
  page_count: int
543
600
  pages: list[PdfPage] = []
544
601
  encrypted: bool = False
545
602
  metadata: dict[str, Any] = {}
603
+ #: The form, whose fields ``pdf.fill`` takes by these names; ``None`` when the file needs a password to open.
604
+ form: PdfForm | None = None
546
605
 
547
606
 
548
607
  class LibraryFile(_Model):
@@ -7,7 +7,7 @@ import time
7
7
  import httpx
8
8
  import pytest
9
9
 
10
- from formfeed import AsyncFormfeed, Formfeed, FormfeedError, Render, RenderInput, parse_webhook_event, verify_webhook_signature
10
+ from formfeed import AsyncFormfeed, Formfeed, FormfeedError, LibraryFile, Render, RenderInput, parse_webhook_event, verify_webhook_signature
11
11
 
12
12
  RENDER = {"id": "rnd_1", "status": "succeeded", "download_url": "https://cdn.test/o/x.pdf?exp=1&sig=2", "page_count": 1, "units": 1}
13
13
 
@@ -272,6 +272,111 @@ def test_async_pdf_tools_mirror_the_sync_client():
272
272
  assert json.loads(rec.calls[0].content) == {"sources": ["rnd_1", "rnd_2"]}
273
273
 
274
274
 
275
+ def test_page_tools_send_a_stored_source_as_json_and_an_upload_as_multipart():
276
+ client, rec = sync_client(lambda req, n: _json({**RENDER, "id": "rnd_zip", "output": "zip", "units": 0.5}))
277
+ parts = client.pdf.split("rnd_1", ranges=["1", "2-"])
278
+ assert parts.output == "zip"
279
+ assert rec.calls[0].url.path == "/v1/pdf/split"
280
+ assert json.loads(rec.calls[0].content) == {"ranges": ["1", "2-"], "source": "rnd_1"}
281
+ assert len(rec.calls[0].headers["idempotency-key"]) > 10
282
+
283
+ client.pdf.compress(LibraryFile.model_validate(FILE_PDF))
284
+ assert rec.calls[1].url.path == "/v1/pdf/compress"
285
+ assert json.loads(rec.calls[1].content) == {"source": "fil_2"}
286
+ client.pdf.to_image("terms.pdf", pages="1", dpi=72)
287
+ assert rec.calls[2].url.path == "/v1/pdf/to-image"
288
+ assert json.loads(rec.calls[2].content) == {"pages": "1", "dpi": 72, "source": "terms.pdf"}
289
+ client.pdf.redact("rnd_1", regions=[{"page": 1, "x": 52, "y": 88, "width": 200, "height": 16}], text=["Max Mustermann"], fill=None)
290
+ assert rec.calls[3].url.path == "/v1/pdf/redact"
291
+ assert json.loads(rec.calls[3].content) == {
292
+ "regions": [{"page": 1, "x": 52, "y": 88, "width": 200, "height": 16}],
293
+ "text": ["Max Mustermann"],
294
+ "fill": None,
295
+ "source": "rnd_1",
296
+ }
297
+ client.pdf.redact("rnd_1", text="Erika Mustermann")
298
+ assert json.loads(rec.calls[4].content) == {"text": "Erika Mustermann", "fill": "#000000", "source": "rnd_1"}
299
+
300
+ # an upload: the PDF as `file`, lists and objects as JSON text, None left out but for fill
301
+ client.pdf.split(file=b"%PDF-1.7", file_name="contract.pdf", every=2, expires_in=None, meta={"order": 7})
302
+ body = _form_fields(rec.calls[5])
303
+ assert b'filename="contract.pdf"' in body and b'name="every"\r\n\r\n2' in body
304
+ assert b'name="meta"\r\n\r\n{"order":7}' in body
305
+ assert b'name="expires_in"' not in body and b'name="source"' not in body
306
+ client.pdf.redact(file=b"%PDF-1.7", text="DE36 0000 0000 0000 0000 00", whole_words=True, fill=None)
307
+ body = _form_fields(rec.calls[6])
308
+ assert b'filename="document.pdf"' in body and b'name="fill"\r\n\r\nnull' in body
309
+ assert b'name="text"\r\n\r\nDE36 0000 0000 0000 0000 00' in body and b'name="whole_words"\r\n\r\ntrue' in body
310
+ assert rec.calls[6].headers["idempotency-key"]
311
+ with pytest.raises(FormfeedError):
312
+ client.pdf.compress()
313
+ with pytest.raises(FormfeedError):
314
+ client.pdf.compress("rnd_1", file=b"%PDF-1.7")
315
+
316
+
317
+ def test_a_form_is_read_with_info_and_filled_by_its_names():
318
+ form = {
319
+ "type": "acroform",
320
+ "signed": False,
321
+ "fields": [
322
+ {
323
+ "name": "customer.name",
324
+ "label": "Name",
325
+ "type": "text",
326
+ "value": None,
327
+ "options": None,
328
+ "required": True,
329
+ "readonly": False,
330
+ "calculated": False,
331
+ "format": None,
332
+ "pages": [1],
333
+ },
334
+ {"name": "newsletter", "label": None, "type": "checkbox", "value": True, "options": None, "required": False, "readonly": False, "calculated": False, "format": None, "pages": [1]},
335
+ ],
336
+ }
337
+
338
+ def respond(req, n):
339
+ if req.url.path.endswith("/pdf/info"):
340
+ return _json({"source": "antrag.pdf", "page_count": 1, "pages": [], "encrypted": False, "metadata": {}, "form": form})
341
+ return _json({**RENDER, "id": "rnd_filled", "units": 0.5, "form": {"filled": 2, "skipped": [], "warnings": [{"field": "total", "code": "calculation_not_run"}], "xfa_removed": False}})
342
+
343
+ client, rec = sync_client(respond)
344
+ info = client.pdf.info(file=b"%PDF-1.7", file_name="antrag.pdf")
345
+ assert info.form is not None and info.form.fields[0].name == "customer.name"
346
+ assert info.form.fields[1].value is True
347
+ assert b'filename="antrag.pdf"' in _form_fields(rec.calls[0])
348
+ assert "idempotency-key" not in rec.calls[0].headers
349
+
350
+ filled = client.pdf.fill("antrag.pdf", fields={"customer.name": "Erika Mustermann", "newsletter": True}, flatten=True)
351
+ assert filled.form is not None and filled.form.filled == 2 and filled.form.warnings[0].code == "calculation_not_run"
352
+ assert rec.calls[1].url.path == "/v1/pdf/fill"
353
+ assert json.loads(rec.calls[1].content) == {"fields": {"customer.name": "Erika Mustermann", "newsletter": True}, "flatten": True, "source": "antrag.pdf"}
354
+ assert rec.calls[1].headers["idempotency-key"]
355
+
356
+ with open(__file__, "rb") as handle: # a binary file object is read once, so a retry sends the same bytes
357
+ client.pdf.fill(file=handle, fields={"size": "M", "tags": ["a", "b"]}, strict=False)
358
+ body = _form_fields(rec.calls[2])
359
+ assert b'filename="test_client.py"' in body
360
+ assert b'name="fields"\r\n\r\n{"size":"M","tags":["a","b"]}' in body and b'name="strict"\r\n\r\nfalse' in body
361
+
362
+
363
+ def test_async_page_tools_mirror_the_sync_client():
364
+ rec = Recorder(lambda req, n: _json({**RENDER, "id": "rnd_png", "output": "png", "units": 1}))
365
+
366
+ async def run():
367
+ async with AsyncFormfeed("ff_test_k", transport=httpx.MockTransport(rec.handler)) as client:
368
+ picture = await client.pdf.to_image(file=b"%PDF-1.7", file_name="contract.pdf", pages="1")
369
+ await client.pdf.fill("rnd_1", fields={"size": "M"})
370
+ return picture
371
+
372
+ assert asyncio.run(run()).output == "png"
373
+ assert rec.calls[0].url.path == "/v1/pdf/to-image" and b'name="pages"\r\n\r\n1' in _form_fields(rec.calls[0])
374
+ assert json.loads(rec.calls[1].content) == {"fields": {"size": "M"}, "source": "rnd_1"}
375
+
376
+
377
+ FILE_PDF = {"id": "fil_2", "name": "terms.pdf", "content_type": "application/pdf", "bytes": 3, "sha256": "aa", "url": "https://cdn.test/a/ws/terms.pdf"}
378
+
379
+
275
380
  FILE = {"id": "fil_1", "name": "brand/logo.png", "content_type": "image/png", "bytes": 3, "sha256": "aa", "url": "https://cdn.test/a/ws/brand/logo.png"}
276
381
 
277
382
 
File without changes
File without changes