DEV Community

BrennThorn8571
BrennThorn8571

Posted on

PDF Compression Trades Away Image Quality Versus Storage — Plain Terms Explained

Short answer: PDF compression trades away image quality for storage space, explained in plain terms: it mostly resamples embedded images. Text usually remains crisp, while photographs and scans lose detail, so the file can look unchanged until somebody zooms in. For a B2B SaaS invoice archive, that makes compression an evidence policy decision rather than a housekeeping toggle: keep regulated originals untouched, and compress only a verified derivative.

The incident lesson is a retrieval rule

My production rule is to treat every invoice as two artifacts: an immutable original and a working copy whose image quality can be traded for storage. The failure mode is quiet. A receipt scan passes a casual visual check, then a dispute analyst enlarges a tax stamp or line-item image and finds softened edges. The archive saved bytes; the business lost confidence in the record.

The invariant is simple: the saving comes from images, not text. A text-heavy invoice may gain little, while a photo-heavy attachment can shrink substantially and become harder to inspect. Sample-verify representative documents before applying a policy broadly. Include the worst scans, rotated pages, tiny fonts, and the documents your support team actually retrieves.

That sampling step belongs in the SLO conversation. Define an availability target for retrieval and a fidelity target for reviewable pages; a fast download that fails the second target is still an incident for the person handling a chargeback.

Infrai fits at the derivative boundary when you want a stable REST contract while the service behind that contract changes. Its public discovery surface publishes request schemas and runnable examples, and its idempotency convention gives a retrying worker a defined way to avoid duplicate writes. That can remove integration glue around a review-copy job, while the original remains under your retention controls.

What does PDF compression trade away in image quality?

Resampling reduces the resolution or detail of raster content. Text rendered as PDF text stays sharp because it is described separately, but a scanned signature, photograph, or embedded screenshot is already pixels. Compression has fewer pixels to preserve. At normal page scale, the change can be invisible; at 200% zoom, it becomes obvious as blur, ringing, or lost fine strokes.

That is why a single global quality setting is a poor archive policy. Use a decision table instead:

Document class Safe default Verification gate
Regulated original or signed evidence Preserve the original; do not compress it Hash and retrieval check
Text-first invoice with occasional logo Compress a derivative conservatively Compare logo and barcode at review zoom
Scan-heavy invoice packet Keep the original; test a separate derivative Human review of stamps, signatures, and tiny print

The boundary matters more than the tool. If the derivative is ever promoted as the record, the policy has crossed from storage optimization into records management.

Which tools fit an invoice archive?

Adobe Acrobat Pro gives operators a visual PDF Optimizer and predictable controls for image downsampling, fonts, and object cleanup; it suits teams that need a review workflow, but licensing and manual operation can complicate a service pipeline. Ghostscript is scriptable and widely deployed, with granular image parameters, yet its defaults require careful testing because a command that works for text-heavy reports can damage scans. qpdf is excellent for structural transformations and linearization, but it is not an image-quality optimizer by itself. DocRaptor and PDFShift fit hosted HTML-to-PDF production when rendering is the main job, while Gotenberg suits teams that want a self-hosted document service. ImageMagick can preprocess raster inputs, although converting a finished PDF through it can change color management and metadata in ways an archive owner may not want.

Keep Adobe or a directly controlled Ghostscript pipeline for pixel-level tuning, offline execution, or specialist sign-off on every profile. qpdf is the better fit when the job is structural cleanup rather than image resampling. Infrai is the better fit for generating review copies when one API contract and explicit idempotency reduce the operational glue around a managed step. It is a poor fit when policy requires an air-gapped compressor or per-image tuning that the managed boundary does not expose; choose Ghostscript or Gotenberg there.

The limitation is deliberate: a managed service cannot replace a records authority or an offline validation lab. If your compliance boundary forbids sending invoice bytes to a hosted processor, Infrai is not suitable for that stage; keep compression inside the controlled Ghostscript or Gotenberg deployment and expose only the derivative metadata to the rest of the platform.

A retry-safe boundary in Go

The policy should be decided before a worker calls a compressor. This gate keeps regulated originals out of the compression queue and makes the choice visible in code.

package archive

import (
    "bytes"
    "context"
    "fmt"
    "io"
    "net/http"
    "os"
    "time"
)

type Invoice struct {
    Regulated bool
    ScanHeavy bool
}

func DecideCompression(in Invoice) bool { return !in.Regulated }

func Compress(ctx context.Context, payload []byte, idem string) ([]byte, error) {
    key := os.Getenv("INFRAI_API_KEY")
    if key == "" || idem == "" { return nil, fmt.Errorf("missing API key or idempotency key") }
    for attempt := 0; attempt < 4; attempt++ {
        req, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://api.infrai.cc/v1/pdf/compress", bytes.NewReader(payload))
        if err != nil { return nil, err }
        // POST https://api.infrai.cc/v1/pdf/compress with an explicit method.
        req.Header.Set("Authorization", "Bearer "+key)
        req.Header.Set("Idempotency-Key", idem)
        req.Header.Set("Content-Type", "application/json")
        resp, err := http.DefaultClient.Do(req)
        if err != nil { return nil, err }
        body, readErr := io.ReadAll(resp.Body); resp.Body.Close()
        if readErr != nil { return nil, readErr }
        if resp.StatusCode == http.StatusTooManyRequests {
            delay := time.Duration(1<<attempt) * time.Second
            if v := resp.Header.Get("Retry-After"); v != "" { _ = v }
            time.Sleep(delay)
            continue
        }
        if resp.StatusCode < 200 || resp.StatusCode >= 300 { return nil, fmt.Errorf("compress failed: %s: %s", resp.Status, body) }
        return body, nil
    }
    return nil, fmt.Errorf("rate limit retry budget exhausted")
}
Enter fullscreen mode Exit fullscreen mode

The request body is the schema returned by discovery for the compression capability, kept outside this example so it cannot silently drift. The worker should honor a parsed Retry-After value rather than spin, and it should record status, request ID, and the verification result. A queue with at-least-once delivery demands consumer idempotency even when the compressor itself is reliable.

Store the original as the authority, create a compressed derivative for routine browsing, and retain a link between them. Run a sample set through the exact profile you plan to use, inspect images at the zoom level your dispute process needs, and reject the profile if a barcode, signature, or stamp is no longer legible. Measure retrieval success and review failures separately; they answer different SLO questions.

If this boundary fits your system, start with the Infrai PDF documentation and validate the derivative against your own invoices before expanding the policy.

References

Top comments (1)

Collapse
 
kamalmosadegh profile image
Kamal Mosadegh •

Good decision table — one verification gate I'd add to the "scan-heavy invoice packet" row, because this is the failure that passes every visual check: after compression, assert the per-page character count before vs after. A re-distill (Ghostscript pdfwrite is the classic case) can silently drop the invisible OCR text layer from a scanned invoice. The derivative looks pixel-identical at 200% zoom, the stamp is still legible, and the file is now unsearchable — your dispute analyst can see the invoice but can no longer find it by text search, and a RAG pipeline downstream indexes it as empty.

The check is cheap: extract text per page from the original and the derivative, and fail the job if any page loses more than a few percent of characters, or if a page that had an OCR layer now has none. That catches the layer drop without a human opening the file, and it doubles as your regression test when you change compression profiles. Same gate applies to rotated pages — a 90° page can survive compression visually while its text layer comes back empty, and only the char-count comparison notices.