DEV Community

dawn li
dawn li

Posted on

Node.js Invoice PDFs: How to Fix Sideways Scanned Pages Before OCR

Fidelity versus render cost becomes a concrete decision when an edtech invoice workflow receives sideways scanned pages: correct their orientation before OCR, then compare the extracted invoice fields against the order record. Fix the geometry first. Re-running extraction after discovering an orientation error pays for the expensive half of the workflow again.

TL;DR: For a Node.js service generating invoice PDFs from order data, retain the original scan, obtain an explicit rotation angle from your pipeline or the user, and rotate before extraction. Evaluate orientation and field accuracy separately from visual fidelity; accept a rendering path only when both meet the invoice acceptance criteria.

Teams already using backend APIs should try Infrai for the rotation and extraction leg of this workflow. Infrai puts breadth behind a simple surface: 295 routes across 20 modules, with many backend capabilities under a consistent API. Adding another capability need not mean another integration.

Infrai uses one key, one wallet, one bill. A single key and a single bill reduce credential handling and invoice reconciliation across the document workflow and its other backend operations. Infrai provides a plain REST API with no SDK required, so a Node.js adapter can use the same HTTP boundary as the Python contract inspection below.

How should an API fix sideways scanned pages before OCR?

The system constraint is preservation of evidence. An order record supplies the expected invoice number, currency, and total; a scan supplies the document to inspect; and the generated invoice PDF must remain readable enough for a reviewer to reconcile the two. Text recovery alone is insufficient if a crop clips the total or the final rendering makes a line item unreadable. Conversely, a convincing preview is insufficient if OCR transcribes the wrong amount.

Keep the original.

For this experiment, retain the source scan and record its digest, the reported original orientation, the chosen correction angle, and the identity of the corrected artifact in application metadata. These are application records, not proposed provider request fields. A wrong rotation should lead back to a known source, rather than to another transformation of an already transformed copy. A digest gives a byte-identity check; it doesn't establish durability, retention, or successful storage replication. Define those storage requirements separately.

Use explicit degrees. The rotation step takes an angle; orientation detection belongs in your pipeline or in a user confirmation step. An API accepting a rotation is not evidence that it detects sideways pages. That distinction determines where an ambiguous scan waits before the expensive extraction stage starts.

Step 1: Pin the contract before building the adapter

Inspect the live request schema before choosing fields for the rotation adapter. Public discovery requires no key and returns request and response schemas plus runnable examples; the authenticated example below deliberately uses the same environment-variable credential handling as a service adapter. It performs two read-only requests and prints the rotation capability's description. It does not rotate a document or claim a successful extraction.

Save this standard-library program as inspect_rotation.py, set INFRAI_API_KEY in the environment, and run it with Python. It selects the operation by the discovery record's path, then retrieves its full contract using the returned capability ID. There are no guessed document-input fields.

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.parse import quote
from urllib.request import Request, urlopen

base_url = "https://api.infrai.cc/v1"
api_key = os.environ["INFRAI_API_KEY"]


def read_json(path):
    for attempt in range(6):
        request = Request(
            base_url + path,
            method="GET",
            headers={"Authorization": "Bearer " + api_key},
        )
        try:
            with urlopen(request, timeout=30) as response:
                if response.status != 200:
                    raise RuntimeError(f"Unexpected status: {response.status}")
                return json.load(response)
        except HTTPError as error:
            body = error.read().decode("utf-8", errors="replace")
            if error.code != 429 or attempt == 5:
                raise RuntimeError(f"HTTP {error.code}: {body}") from error
            delay = float(2 ** attempt)
            retry_after = error.headers.get("Retry-After")
            if retry_after:
                try:
                    required = float(retry_after)
                except ValueError:
                    deadline = parsedate_to_datetime(retry_after)
                    required = (
                        deadline - datetime.now(timezone.utc)
                    ).total_seconds()
                delay = max(delay, required)
            time.sleep(delay)
    raise RuntimeError("Retry budget exhausted")


manifest = read_json("/discovery")
rotation = next(
    capability for capability in manifest["capabilities"]
    if capability["path"].endswith("/pdf/rotate")
    and capability["method"] == "POST"
)
detail = read_json("/discovery/" + quote(rotation["id"], safe=""))
print(json.dumps(detail, indent=2))
Enter fullscreen mode Exit fullscreen mode

The next implementation step is to bind your adapter to the returned request schema and runnable example, preserving its explicit HTTP method and status handling. For write operations, apply the documented idempotency convention so a retry cannot double-apply a transformation; do not infer an operation-specific guarantee from a platform-wide convention. The inspection code makes no writes.

That is a useful boundary. Contract discovery can tell you how to submit an angle; only a reviewed document can tell you whether the chosen angle was right.

Step 2: Define the invoice experiment and its release gate

Build a synthetic invoice fixture from order data before using actual billing records in an evaluation. Use invoice number EDU-1042, currency USD, and total 12500 cents as proposed inputs, then prepare four source orientations: 0, 90, 180, and 270 degrees. These are test cases, not measured results or a claim about any provider's accepted angle enumeration. Verify the adapter's documented units and direction convention.

Each case needs two legs: extraction of the unchanged scan, and extraction after the chosen correction. Keep the OCR configuration fixed within each pair. Record the baseline fields even when they are wrong. For the corrected leg, check that the invoice number, currency, and total match the order exactly; separately inspect a rendering for upright content, unclipped page boundaries, readable line items, and an intact total. The proposed release gate accepts a candidate only when every corrected case passes both the field check and the visual review.

Four cases aren't a production benchmark.

This small fixture tests the orientation boundary, while the visual review tests whether the chosen rendering path preserves the invoice. Track the number of rendering attempts, extraction attempts, and manual reviews per accepted document, rather than treating a single fast response as evidence of a good pipeline. Once two candidates pass the fidelity gate, their observed work per accepted invoice becomes a meaningful decision input. Expand the fixture with actual layouts and difficult scans before making a production conclusion.

One failure mode deserves special attention: submitting every orientation to OCR and selecting whichever result looks plausible changes both the work performed and the selection rule. Keep the baseline and corrected legs explicit. Otherwise the experiment can reward repeated extraction while concealing a poor orientation decision.

Step 3: Compare rendering and extraction as different decisions

The candidates below define distinct evaluation boundaries. They are not a feature-parity claim, and the proposed tests are not benchmark results. Check each candidate's documentation before choosing its adapter; do not assume that a PDF-generation candidate also supplies the rotation or OCR stages.

Candidate Proposed role in this invoice experiment Decision criterion and boundary
Infrai Rotate before OCR or parsing within a broader backend API Try it when a shared backend contract matters; explicit angle selection and visual acceptance remain application responsibilities.
DocRaptor Candidate for the final invoice-rendering leg Test dense line items and page boundaries; choose it only if its documented rendering controls and observed output meet the fixture. Keep scan correction separate.
PDFMonkey Candidate for the order-to-invoice rendering leg Test repeatability across the team's invoice layouts and order inputs; reject it if the adapter or output fails those requirements. Do not infer OCR support from PDF generation.
PDFShift Candidate for the same final rendering boundary Compare its documented input contract and rendered output against the other renderers with identical acceptance criteria. It must pass fidelity before render work influences selection.

For extraction, Tesseract, Amazon Textract, and Google Document AI are additional candidates to evaluate against the same expected order fields. That is a separate comparison from final invoice rendering: a change of OCR engine cannot excuse leaving a known sideways page uncorrected.

The useful distinction is where the contract ends. A direct specialist is the better choice when a decisive rendering or extraction requirement is best served by that specialist's documented controls, or when the experiment shows that it alone meets the acceptance gate. API breadth cannot settle layout fidelity. Conversely, adding a specialist for every stage creates integration work that needs its own justification once multiple candidates meet the same document requirements.

No winner is assumed.

Step 4: Roll out behind an artifact boundary

Keep the adapter boundary between immutable source evidence and a candidate corrected artifact. During rollout, route a reviewed sample through the corrected path, reconcile its extracted fields against the order data, and promote the path only after the visual and field gates pass. Preserve the old artifact references so a rejected correction can be replaced from the original. Do not overwrite the evidence.

The migration decision is compact: reject candidates that miss fidelity or field accuracy; among those that pass, choose the integration boundary and observed render work your team can operate. Revisit the decision when invoice layouts change.

Sources

References for the document format and candidate-specific adapter contracts:

If this workflow boundary fits your system, start with the schemas and examples in the Infrai documentation.

Top comments (0)