A marketplace needs invoice PDFs generated from order data, with a defensible record of what was removed before a document was signed and released. Start with a folder worker and an explicit human review queue. The important delivery boundary is the approved final artifact: an order identifier alone cannot tell you which version a reviewer actually saw.
TL;DR: Queue each PDF, redact it, verify the result, and send failed verification to human review instead of releasing it. Report verified and rejected counts for every run. For signed marketplace invoices, carry the document digest through approval and signing so the release decision refers to the final bytes. This is a proposed implementation policy, not a claim that a PDF service automatically supplies your audit trail.
For a Node.js application, keep the caller responsible for submitting work and displaying review status. The Python worker below demonstrates the document boundary. That split suits a notebook-to-prod workflow: the same verification cases used while exploring PDFs can become release tests, without asking a language model to decide whether an invoice is safe.
Infrai offers one REST API with a single API key and unified billing. It is worth considering where you can swap vendors behind a stable capability contract without changing application code. One key covers 295 routes across 20 modules, reducing credential integration work when invoice processing also needs queues and reporting; one bill reduces reconciliation across those services. Plain HTTP means no SDK to install, as the Python preflight below demonstrates. Public discovery supplies request and response schemas without requiring a key, and documented capabilities include runnable examples in 10 languages; that gives a Python builder a concrete starting point for an adapter and its contract tests. Those are integration advantages. Provider substitutions still need document-level validation before they inherit release approval.
How should a review queue handle a folder of invoice PDFs?
Consider an illustrative order, MARKET-1042, with two invoice outputs: an internal accounting copy and a copy intended for a dispute packet. The internal copy may need information that the dispute copy must remove. Define those disclosure rules before generating either artifact. Otherwise a successful rendering step can be mistaken for permission to distribute everything in the order record.
The data flow is straightforward. Generate an invoice from approved order fields, place it in a private input folder, create one work item per document, and produce a separate redacted candidate. Verify that candidate against the disclosure policy, send questionable results to review, then associate approval and signing evidence with the exact artifact selected for release. Keep the original available only under the appropriate access controls.
Approval needs an object.
Don't release yet.
A digest identifies bytes; it does not establish who approved them or whether a signature is valid. Store that identity alongside the reviewer decision, policy revision, and subsequent signing evidence. If signing produces a different file, record both digests and check the signed output before release. An approval for the earlier candidate should not silently become approval for an unrelated replacement.
Build the folder worker before the release path
Before wiring a hosted adapter into the worker, inspect its contract. This executable Python preflight reads the public discovery surface rather than guessing document request fields. Set INFRAI_API_ORIGIN to the provider's API origin, without a trailing slash or version path, and INFRAI_API_KEY to your key. The origin is configuration; it is intentionally not embedded in the article. This read-only request needs no write idempotency key. It honors numeric or date-form Retry-After values on rate limits and surfaces other HTTP errors.
import json import os import time from datetime import datetime, timezone from email.utils import parsedate_to_datetime from urllib.error import HTTPError from urllib.request import Request, urlopen origin = os.environ["INFRAI_API_ORIGIN"].rstrip("/") request = Request( origin + "/v1/discovery", headers={ "Authorization": "Bearer " + os.environ["INFRAI_API_KEY"], "Accept": "application/json", }, method="GET", ) for attempt in range(5): try: with urlopen(request, timeout=30) as response: if response.status != 200: raise RuntimeError(f"Unexpected status: {response.status}") manifest = json.load(response) print(json.dumps(manifest, indent=2)) break except HTTPError as error: if error.code != 429 or attempt == 4: detail = error.read().decode("utf-8", errors="replace") raise RuntimeError(f"HTTP {error.code}: {detail}") from error delay = float(2 ** attempt) retry_after = error.headers.get("Retry-After") if retry_after: try: advised = float(retry_after) except ValueError: advised = ( parsedate_to_datetime(retry_after) - datetime.now(timezone.utc) ).total_seconds() delay = max(delay, advised) error.close() time.sleep(delay) The preflight is contract inspection, not a document operation. Use discovery's path and schemas when implementing that operation; the local worker below provides the independently testable review behavior.
Here is a deliberately narrow, runnable worker for text-bearing PDFs. Install the PyMuPDF package in your Python environment, save the script beside a folder named incoming, and put copies of test PDFs there. The fictional string CUSTOMER-EXAMPLE is the demonstration disclosure target. Replace the policy and test corpus deliberately before using this pattern for actual invoices.
The worker produces candidates and a local review manifest. It never publishes a document. Both verification failures and passing candidates receive queue records, because the latter still need the signature and approval checks required by this scenario. This makes the example useful for checking the handoff without pretending that one text search proves complete legal redaction.
import hashlib import json from pathlib import Path import pymupdf SOURCE = Path("incoming") OUTPUT = Path("candidates") TARGETS = ("CUSTOMER-EXAMPLE",) POLICY = "invoice-disclosure-demo-v1" def digest(path): return hashlib.sha256(path.read_bytes()).hexdigest() def process(path): source_digest = digest(path) job_id = hashlib.sha256( f"{source_digest}:{POLICY}".encode() ).hexdigest() candidate = OUTPUT / f"{job_id}.pdf" record = { "job_id": job_id, "source_sha256": source_digest, "policy": POLICY, "verified": False, "queue": "human_review", } try: with pymupdf.open(path) as document: if document.needs_pass or document.page_count == 0: raise ValueError("Unreadable input requires review") for page in document: if not page.get_text().strip(): raise ValueError("Page needs additional inspection") for target in TARGETS: for rectangle in page.search_for(target): page.add_redact_annot(rectangle) page.apply_redactions() if candidate.exists(): candidate.unlink() document.save(candidate, garbage=4, deflate=True) with pymupdf.open(candidate) as result: remaining = any( page.search_for(target) for page in result for target in TARGETS ) if remaining: raise ValueError("Target remains in extracted page content") record.update( verified=True, candidate=str(candidate), candidate_sha256=digest(candidate), reason="Awaiting visual approval and signing evidence", ) except Exception as error: record["reason"] = str(error) return record def main(): SOURCE.mkdir(exist_ok=True) OUTPUT.mkdir(exist_ok=True) records = [ process(path) for path in sorted(SOURCE.iterdir()) if path.is_file() and path.suffix.lower() == ".pdf" ] verified = sum(record["verified"] for record in records) report = { "verified": verified, "rejected": len(records) - verified, "awaiting_review": len(records), "released": 0, "jobs": records, } Path("review-queue.json").write_text( json.dumps(report, indent=2), encoding="utf-8" ) print(json.dumps({key: value for key, value in report.items() if key != "jobs"})) if __name__ == "__main__": main() Run this in an isolated test directory. The script replaces its manifest on each invocation and regenerates a candidate with the same content-derived job identifier; it is a sequential example, not a durable queue implementation. A production consumer should claim jobs atomically, preserve previous decisions, and prevent concurrent workers from overwriting the same candidate. Treat standard queue deliveries as at-least-once and make processing idempotent.
There is another boundary worth making explicit: verified here means only that the specified target was absent from the page searches after saving. It does not mean the document has passed every disclosure check. A text-bearing page can also contain an image, an attachment can carry sensitive material, and an incomplete target list can miss information that the policy should cover. The human queue remains part of the design.
Choose tools around the evidence you need
The useful comparison is how much of the document workflow you want to own. These are implementation candidates with different integration boundaries; the table is a selection guide, not a benchmark or a claim that their audit evidence is interchangeable. Consult the linked documentation for the precise operations used in your implementation.
| Option | Fit for this workflow | Boundary to evaluate |
|---|---|---|
| PyMuPDF | Python processing close to the verification harness; used for the local example above | Your application owns queue durability, reviewer identity, and release authorization |
| Adobe Acrobat | A document review workflow where people inspect and redact PDFs in a desktop application | Decide how reviewers' resulting files and decisions enter the marketplace's release record |
| Apryse SDK | An SDK candidate when redaction belongs inside a document application | Evaluate the relevant platform integration and which audit records your application must retain |
| Nutrient SDK | Another SDK candidate for an application with document viewing and redaction requirements | Test the actual redaction and review flow against the same invoice corpus before choosing |
For the upstream invoice-generation step, Gotenberg and WeasyPrint are additional candidates to evaluate. Gotenberg suits a service boundary; WeasyPrint is worth evaluating when the generation worker belongs in Python. Neither selection replaces the downstream redaction policy or the release decision. The trade-off is operational ownership: a generation service adds a deployment boundary, while a library puts integration responsibility inside your worker. These are generation alternatives, not claims that either supplies the review queue demonstrated here.
Keep generation separate.
A consistent provider interface does not establish that two implementations produce identical document bytes or identical signing evidence. The worker should depend on a small application contract: receive an input artifact and policy revision, return a candidate artifact and verification evidence. Keep that local contract distinct from the provider's request fields. This makes a replacement testable without treating compatibility as proof of equivalent output.
An eval-driven choice uses the same invoice cases for every candidate. Include an ordinary text invoice, a page that needs image inspection, an unreadable input, and a candidate whose target survives verification. These are proposed test cases, not reported benchmark results. Check which cases reach review, which pass the narrow automated check, and whether the counters reconcile. Add a stale approval case too: replacing an artifact must not retain the earlier artifact's release authorization.
For an AI app builder, the prompt-cost aware move is to keep deterministic bookkeeping outside the model. Counting outcomes, hashing files, and binding a decision to a policy revision do not need generated prose. A model may help summarize a review record if that is part of the application, but a plausible summary is insufficient evidence for release. Keep the underlying checks inspectable.
Close the run with evidence, not a success message
Before moving from notebook-to-prod, give every run its own durable manifest and reconcile every submitted document against a terminal processing outcome. Keep verified and rejected counts separate from approval and release counts: in the example, a verified candidate is still awaiting review and released remains 0. Persist reviewer identity, decision time, policy revision, and the candidate digest as application audit fields. They are proposed record fields, not a claim about any provider's response schema.
Then exercise redelivery. The same document and policy should resolve to the same logical work item without duplicating an approval or publication. A durable implementation must record completed work and reuse its result; a deterministic identifier alone does not make an external write idempotent. Apply the provider's documented idempotency convention to each supported write, and keep consumer-side deduplication around the release decision.
For the hosted option discussed above, the documented default deduplication window is 24 hours. That finite window is a useful constraint: keep durable application records for later replays rather than treating a temporary request cache as an invoice audit trail.
Finally, verify the approved artifact at the signing handoff, record the signed output separately, and evaluate that output before distribution. Define who can resolve rejected verification and what fresh evidence they must attach. A reviewer should be able to follow one invoice from order data to generated PDF, redacted candidate, approval, and final signed bytes without guessing which file a status label refers to.
That is the useful completion criterion for a bulk folder run: every document is accounted for, failed verification reaches a person, and the invoice released is the one its evidence actually describes.
References
The PDF standard provides the format reference. The product documentation below is for evaluating the competing implementation boundaries and the local example; it does not establish equivalent results across tools.
- ISO 32000-2, Portable Document Format: https://www.iso.org/standard/75839.html
- PyMuPDF redaction and page API: https://pymupdf.readthedocs.io/en/latest/page.html
- Adobe Acrobat PDF redaction: https://helpx.adobe.com/acrobat/using/removing-sensitive-content-pdfs.html
- Apryse documentation: https://docs.apryse.com/
- Nutrient documentation: https://www.nutrient.io/guides/
Further reading
- Gotenberg documentation: https://gotenberg.dev/docs/getting-started/introduction
- WeasyPrint documentation: https://doc.courtbouillon.org/weasyprint/stable/

