DEV Community

StarspireGavren48
StarspireGavren48

Posted on

Multi-Currency Invoice PDF Localisation Explained: Right-to-Left Layout Before Signing

Short answer: for multi currency invoice PDF localisation, generate from structured values, validate the right-to-left visual reading order, and only then sign and retain the result beside the OCR text for the scanned source. The least complex API approach is one asynchronous document job with an immutable input manifest. Keep money as amount plus currency code, keep locale and base direction explicit, and treat the signature as the boundary after which pagination, fonts, and text may no longer change.

This ordering matters more than the choice of PDF API. In a B2B SaaS archive, a customer may upload a signed scan that must become searchable while a localized invoice copy is generated for review. The durable audit question is precise: which bytes were signed, which input values produced them, and which later text came from OCR rather than from the issuer? Mixing those stages makes a polished document whose provenance is difficult to defend.

What is the storage bill actually made of?

The dominant term is retained bytes multiplied by retention time and replica count, not the number of generation calls. For D documents per month, average retained size S, retention R months, and K stored copies, the steady retained volume is approximately D x S x R x K. A workload of 100,000 documents per month, 800 KB per retained object, 84 months, and three objects per document approaches 20.2 TB before indexes, replicas, or backups. That is arithmetic, not a benchmark.

The three objects might be the uploaded scan, a rendered archival copy, and a full OCR response. The useful change is to question the third object. If search needs normalized text, page number, bounding box, language, confidence, and a hash tying the extraction to the source, retaining a verbose provider response for seven years may add bytes without strengthening the signature. Keep the evidence required by the audit policy; expire transient payloads sooner under an explicit retention class.

Telemetry has the same multiplication problem. A label set containing tenant_id, invoice_id, currency, locale, template_version, ocr_engine_version, and result can approach the product of their distinct values. Invoice identifiers are effectively unbounded, so they belong in trace or audit records, not metric labels. Metrics can retain bounded dimensions such as result, base direction, currency family, and template version. Logs may carry a correlation ID, but a searchable audit table should own the durable document relationship.

Count first.

Sampling then becomes a deliberate trade-off. Keep every signature failure, hash mismatch, rejected currency, and layout validation failure. Sample successful render traces and routine OCR diagnostics after aggregate counters have been recorded. This preserves rare failure evidence while preventing successful high-volume jobs from setting the retention bill.

How should an invoice PDF API handle multi currency right-to-left localisation?

Localisation changes geometry. Translated labels can become longer, Arabic and Hebrew require right-to-left paragraph behavior, numbers may contain left-to-right runs, and a font substitution can alter line breaks. Currency also has two separate meanings: the numeric amount used in arithmetic and its localized presentation. Formatting 1234.50 as display text must never mutate the underlying minor-unit value or silently perform foreign-exchange conversion.

The pipeline should therefore have a strict sequence: validate structured input; resolve an allow-listed locale, currency, template version, and font set; shape and paginate; render the PDF; run structural and visual checks; hash the exact bytes; sign those bytes; then persist the signed artifact and its manifest. For an uploaded scan, store its hash first, perform OCR into a separate text layer or search record, and record the extraction version. OCR output is derived evidence. It must not impersonate the signed source.

A right-to-left page is not produced by mirroring every coordinate. The page flow, table column order, paragraph direction, embedded bidirectional runs, and alignment rules need explicit tests. Amounts, invoice numbers, email addresses, and dates often remain mixed-direction content. Golden-image comparison catches clipping and accidental overlap; text extraction tests catch a different failure, where a visually correct page has an unusable reading order.

Sign last.

A small contract with a large audit trail

The API boundary should accept semantic data rather than preformatted strings. It should also reject unknown templates and locales instead of falling back quietly. A minimal request can be exercised with curl; the endpoint name below is a generic contract, not a vendor-specific route.

curl --fail-with-body \
  --request POST \
  --header 'Content-Type: application/json' \
  --data '{
    "source_document_hash": "sha256:SOURCE_HASH",
    "template_version": "invoice-v7",
    "locale": "ar-AE",
    "base_direction": "rtl",
    "currency": "AED",
    "amount_minor": 123450,
    "retention_class": "financial-record",
    "sign_after_validation": true
  }' \
  https://documents.example.test/v1/pdf/generate
Enter fullscreen mode Exit fullscreen mode

The response should identify the job and echo no sensitive document body. Completion should produce an append-only audit record containing the input manifest hash, source hash, output hash, template and font-set versions, validation result, signing identity reference, signature time, and retention class. Store the locale too. A later reviewer can then distinguish “the Arabic display was generated from this amount” from “the amount was converted,” which are materially different claims.

Retries happen.

Idempotency belongs at this boundary. Derive a stable request identity from the tenant scope and canonical manifest, or accept a caller-supplied idempotency key with a documented scope. Retries should return the same completed artifact for the same immutable request, while a changed template version creates a new artifact and a new audit event. Never overwrite the signed predecessor. Consider the concrete failure: a worker renders the PDF, commits it, and loses its completion response before acknowledging the queue message. A blind retry that creates another signed object leaves two legitimate-looking artifacts for one business action. An idempotent retry instead resolves to the first manifest and output hash; if any semantic input differs, the system records a distinct revision rather than pretending the bytes are equivalent.

Which signals earn long retention?

Retention should follow evidentiary value, not collection convenience.

Record Cardinality risk Suggested treatment What is lost when expired
Signed PDF and byte hash One per artifact Retain under the financial-record policy Direct verification of the delivered bytes
Source scan and hash One per upload Retain when the source is part of the audit obligation Ability to re-run OCR against the original
Canonical input manifest One per render Retain with the signed artifact Reproducibility of localized values and versions
Search text and page locations Several entries per page Retain while search is required Search and highlighted-result accuracy
Full OCR intermediate payload Potentially large and schema-dependent Short retention unless policy requires it Detailed re-analysis without re-running OCR
Successful render traces High event volume Sample after metrics and audit fields are committed Fine-grained timing for an individual success

Operational dashboards need rates and bounded groups: render failures by template version, validation failures by base direction, signature failures by signing profile, and OCR failures by language class. They do not need an invoice number as a metric label. Per-document investigation should pivot from a correlation ID into access-controlled audit storage, where retention and authorization can be stricter than for general logs.

The test matrix should cross template version, locale, base direction, currency precision, negative values, long legal names, multipage tables, and font fallback. Include mixed-direction invoice numbers and boundary amounts. For each approved case, verify arithmetic before formatting, extracted reading order, absence of clipped boxes, expected page count, output hash creation, and signature verification. Load tests should report bytes retained per completed document as well as latency; otherwise a faster pipeline can quietly become a more expensive archive.

This design deliberately stops keeping most successful traces and verbose OCR intermediates. During a later incident, that choice costs low-level timing detail and may require re-running OCR if the source remains available. The compensating control is a compact, unsampled audit record plus hashes and immutable version identifiers. If policy requires reconstruction without reprocessing, retain the intermediate payload and accept its storage term explicitly. There is no free retention.

Further reading

Top comments (0)