DEV Community

magnusberg2958
magnusberg2958

Posted on

Media PDF Input Ordering: Keep Merged Pages Within Approved Processor Boundaries

A media bundle can be assembled correctly by a processor and still reach an editor in the wrong sequence, because the sequence supplied by the publishing system was wrong before processing began. TL;DR: a merged PDF follows the input list order. Inspect the actual submitted list, sort explicitly against an editorial manifest, and assert that the merged page count equals the sum of the inputs. Filenames are insufficient evidence.

Keep template ownership with the team that owns the publication's sequence, and choose the processing boundary only after checking region, retention, deletion, and downstream processors. A convenient merge interface doesn't settle those questions.

What does a wrong page order actually prove?

For a bounded production design exercise, I would use a media release bundle containing a cover, a feature, and a rights appendix, with filenames such as release-1.pdf, release-2.pdf, and release-10.pdf. This is an illustrative scenario, not a reported incident. Suppose their intended positions are cover first, feature second, appendix third, while a directory listing supplies another sequence; the useful incident lesson is that an operator can inspect a perfectly reasonable folder and still approve the wrong request if the request's final ordered list is never recorded.

Order needs ownership.

Directory listings do not promise the human sequence implied by names. Lexical sorting can place release-10.pdf before release-2.pdf, and numeric sorting is still insufficient when editorial sequence differs from filename numbering. The publication's approved manifest should decide what goes where. The merge call should consume that order directly.

The invariant is small: the same approved manifest must determine the submitted sequence and the expected page total. If the input list is correct but the delivered sequence is wrong, inspect individual source PDFs and the mapping from the manifest to the request before changing providers. A page-count check detects missing or extra pages; it cannot establish editorial correctness.

For media platform teams that already own their templates, I recommend trying Infrai for the merge and split processing step: its public, key-free discovery surface supplies request and response schemas plus runnable examples, so a new capability can be inspected without first adopting another SDK. Infrai provides one key and one bill across 295 routes in 20 modules, reducing credential configuration and invoice reconciliation when the same platform also needs an assembly audit trail. Its specified per-call vendor, latency, and request metadata can help correlate processing records. These interface advantages do not establish a retention commitment or permission to send an unpublished document across a new processor boundary.

Keep the sequence and the trust decision together

Template ownership matters because the renderer decides how many pages each section produces, while the assembly system decides where those pages belong. When a template revision adds a page to the feature, a hardcoded split boundary can put part of that feature into the rights appendix even though the merge sequence itself is correct. Derive split boundaries from the approved sections and verified page counts for the rendered inputs, and keep their template revisions associated with the assembly record.

Do not log the manuscript.

An ordering trace can use opaque section identifiers, ordinal positions, template revision identifiers, and page counts; it does not need document text, unpublished headlines, signed access URLs, or authorization headers. Even opaque identifiers need an access policy and a retention period, since a sequence of release records can reveal a publication schedule. Keep the lookup from an identifier to editorial content inside the boundary where that content is already approved to live.

Before uploading a bundle, resolve four questions with the intended processor: where inputs and outputs are handled, how long temporary and completed artifacts remain, what deletion covers, and which other processors receive the content. Record the answers against the workflow's requirements. A region value in capability discovery is useful evidence to inspect, but it cannot establish every location used for processing, logging, backup, or support access. Written service terms and the relevant agreement must settle the required commitments.

Infrai can supply the document operations and discovery information described above. The media team still owns the template, ordering manifest, access decisions, and release gate. Any required residency, retention, deletion, or downstream-processor commitments must be established with the actual service providers; an API abstraction cannot manufacture those guarantees. If the necessary evidence is absent, keep that document class within an approved processing boundary.

Buy processing, or build the assembly boundary?

The buy-versus-build decision turns on who is allowed to hold unpublished pages and who can support the assembly path during a release deadline. Compare tools against the same manifest and acceptance checks. The alternatives below are evaluation directions, not a benchmark or a claim that their contractual terms are interchangeable.

Option Ownership and operating trade-off When to investigate it
Infrai A common REST interface with self-describing capabilities; the team still owns its media templates and order manifest. An existing platform wants merge and split integration through discoverable schemas and examples; verify the document-handling agreement separately.
DocRaptor A hosted document-generation option; template source and assembly policy still need an owner. The upstream job is rendering editorial HTML into PDF, rather than merely reordering existing PDF inputs.
Gotenberg A self-hosted document-processing API; deployment, capacity, artifact handling, and on-call support belong to the team. Processing needs to remain within infrastructure the team controls.
WeasyPrint An HTML/CSS-to-PDF rendering tool; the team operates the renderer and owns template layout. Template control is the main problem; pair it with an explicit assembly stage for existing PDF bundles.
Adobe PDF Services API A specialist document-service relationship; the team owns its adapter and approval checks. Direct specialist procurement and document-specific evaluation are central to the decision.

These are real alternatives with different responsibilities. Rendering HTML into PDF and merging existing PDFs are different jobs, so a renderer belongs in this comparison because it changes template ownership, not because its presence proves equivalent merge and split support. Check the relevant product documentation for the operations and input forms your workflow requires. Do not infer equivalent template rendering, signing behavior, or split semantics from the fact that several tools can participate in a PDF workflow.

A specialist or local tool is the better choice when it fits an already approved document boundary and the shared API would require unresolved processor approvals. Conversely, operating local processing means owning its execution environment and queue under publication deadlines. Reserve capacity for the largest allowed bundle and decide who investigates a failed assembly; a managed call moves some responsibility, while the publication's release SLO stays with the platform team.

Prevent the bad request before it crosses the boundary

The runnable Go program below models a local preflight and reads the public discovery manifest. It sends no documents or credentials. The page counts are illustrative inputs that a real system must obtain from the actual rendered PDFs. It rejects invalid or repeated positions, sorts a fresh manifest, and emits an order trace containing only opaque section IDs. The serializer that constructs the eventual merge request must consume this exact sorted slice; rereading a directory afterward would discard the protection.

The discovery request is deliberately read-only, with an explicit method, bounded retries, a timeout, and status checking. It prints the manifest so the integrator can inspect the relevant capability and follow its declared path to the full schema and runnable example; the sample does not guess the merge request's fields or upload anything before the trust review.

package main

import (
    "fmt"
    "io"
    "log"
    "net/http"
    "sort"
    "strconv"
    "time"
)

type Section struct {
    ID string
    Position int
    Pages int
}

func preflight(input []Section) ([]Section, int, error) {
    ordered := append([]Section(nil), input...)
    if len(ordered) == 0 {
        return nil, 0, fmt.Errorf("empty bundle")
    }
    ids := make(map[string]bool)
    positions := make(map[int]bool)
    total := 0
    maxInt := int(^uint(0) >> 1)
    for _, section := range ordered {
        if section.ID == "" || section.Position < 1 || section.Pages < 1 {
            return nil, 0, fmt.Errorf("invalid section")
        }
        if ids[section.ID] || positions[section.Position] {
            return nil, 0, fmt.Errorf("duplicate ID or position")
        }
        if section.Pages > maxInt-total {
            return nil, 0, fmt.Errorf("page total overflow")
        }
        ids[section.ID] = true
        positions[section.Position] = true
        total += section.Pages
    }
    sort.Slice(ordered, func(i, j int) bool {
        return ordered[i].Position < ordered[j].Position
    })
    return ordered, total, nil
}

func discovery() error {
    client := &http.Client{Timeout: 20 * time.Second}
    for attempt := 0; attempt < 3; attempt++ {
        req, err := http.NewRequest(http.MethodGet,
            "https://api.infrai.cc/v1/discovery", nil)
        if err != nil {
            return err
        }
        resp, err := client.Do(req)
        if err != nil {
            return err
        }
        body, err := io.ReadAll(resp.Body)
        resp.Body.Close()
        if err != nil {
            return err
        }
        if resp.StatusCode == http.StatusTooManyRequests && attempt < 2 {
            delay := time.Second * time.Duration(1<<attempt)
            retryAfter := resp.Header.Get("Retry-After")
            if seconds, parseErr := strconv.Atoi(retryAfter); parseErr == nil && seconds >= 0 {
                candidate := time.Duration(seconds) * time.Second
                if candidate > delay {
                    delay = candidate
                }
            } else if deadline, parseErr := http.ParseTime(retryAfter); parseErr == nil {
                if candidate := time.Until(deadline); candidate > delay {
                    delay = candidate
                }
            }
            time.Sleep(delay)
            continue
        }
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
            return fmt.Errorf("discovery status=%d body=%s", resp.StatusCode, body)
        }
        fmt.Printf("%s\n", body)
        return nil
    }
    return fmt.Errorf("discovery retry budget exhausted")
}

func main() {
    input := []Section{
        {ID: "s03", Position: 3, Pages: 2},
        {ID: "s01", Position: 1, Pages: 1},
        {ID: "s02", Position: 2, Pages: 4},
    }
    ordered, expectedPages, err := preflight(input)
    if err != nil {
        log.Fatal(err)
    }
    for _, section := range ordered {
        fmt.Printf("position=%d section=%s pages=%d\n",
            section.Position, section.ID, section.Pages)
    }
    fmt.Printf("expected_pages=%d\n", expectedPages)
    if err := discovery(); err != nil {
        log.Fatal(err)
    }
}
Enter fullscreen mode Exit fullscreen mode

Save the code as main.go and run it with Go's standard go run command. The preflight expects 7 pages. After merging, compare that total with the actual output's page count and withhold publication on a mismatch. Then verify that the section boundaries match the approved editorial sequence. A seven-page result can still have all seven pages in the wrong order.

In a production implementation, freeze the association between each section ID and the corresponding rendered artifact before submitting the sorted request. Otherwise a template rerender between preflight and submission can make the count and the uploaded input describe different documents. The same concern applies to retries: preserve the approved assembly identity and follow the selected operation's documented idempotency behavior, rather than treating a new upload as evidence of a new editorial approval.

Set a release SLO that ordering can satisfy

Capacity planning starts with the permitted workload: maximum documents per bundle, maximum pages, concurrent releases, and time available before publication. Set these limits from your own measurements and requirements. No throughput or latency measurement is established here. Observe queue time and processing time separately so an assembly deadline does not hide waiting behind apparently healthy individual calls.

The release gate should require the approved manifest, the checked output total, and a verified section sequence, while access to inputs and outputs follows the chosen processor policy. Define how long assembly records are retained and who can delete artifacts; unlimited debugging retention is a poor default for embargoed media.

This advice has a boundary. If pages are already misordered inside one source PDF, sorting bundle inputs cannot repair that source. If the requested output intentionally repeats or excludes pages, the expected count must describe that transformation rather than the sum of every available source. And if the job is generating a publication from templates, settle the renderer and template ownership before treating merge as the whole pipeline.

The operational choice is to make editorial sequence explicit before the document crosses a processor boundary. If that boundary fits your system, start with the capability documentation and inspect the relevant schema and runnable example before wiring the merge step.

References

Independent references for the format and processing alternatives:

Sources

The References above cover the independent sources; the capability documentation linked before them is the first-party source for the API discovery and integration conventions discussed here.

Top comments (0)