OneCompiler

Inside ISO 32000-1 PDF Document Merging: Indirect Object Graph Renumbering, /Pages B-Tree Grafting, and Cross-Reference (xref) Reconstruction in JavaScript

76

Example heading with h2 size

Example heading with h3 size

Following is sample java code.

int i = 10;
if(i>0){
    System.out.println('positive');
}
```Concatenating two plain-text files or CSV streams is a trivial byte-append operation. Merging two or more **Portable Document Format (PDF — ISO 32000-1 / ISO 32000-2)** documents, however, is a graph-theory and binary-compiler problem. If you naively concatenate the byte buffers of two PDF files, the resulting file is structurally corrupt: both documents define their own `1 0 obj`, `2 0 obj`, and `3 0 obj` indirect objects, both contain independent `/Catalog` roots, and the trailing cross-reference (`xref`) byte offsets of the second document no longer match their physical byte positions relative to the start of the combined buffer.

In this engineering deep dive, we examine how a specification-compliant PDF merger parses multiple input PDFs as directed acyclic graphs (DAGs) of indirect objects, performs collision-free object ID renumbering, grafts `/Page` leaf nodes into a unified `/Pages` balanced tree, isolates `/Resources` dictionaries (fonts, XObjects, color spaces), and serializes a single deterministic `xref` table—entirely in browser memory using JavaScript `Uint8Array` buffers.

---

## 1. Why PDF Files Cannot Be Byte-Concatenated: The Indirect Object Graph

Every PDF document is structured around four physical layers:

1. **Header (`%PDF-1.7`):** Declares the specification version and a 4-byte high-bit binary comment to signal binary transport.
2. **Body (Indirect Objects):** A collection of numbered nodes (`<objNum> <genNum> obj ... endobj`) representing dictionaries, arrays, streams, and primitives.
3. **Cross-Reference Table (`xref` or `/XRef` stream):** An indexed lookup table mapping each object number (`1..N`) to its exact 10-digit byte offset from byte `0` of the file.
4. **Trailer (`trailer << /Root ... /Size ... >> startxref <offset> %%EOF`):** Points the PDF parser to the byte offset of the `xref` table and identifies the root `/Catalog` object.

When merging Document A and Document B into a single output PDF, the engine must execute four graph transformations:

1. **Transitive Closure & Reachability Walk:** Starting from each source document's `/Pages` tree, traverse only reachable `/Page` nodes and their dependent sub-objects (`/Contents` streams, `/Resources`, `/Font` descriptors, `/XObject` images, and `/Annots`).
2. **Monotonic Object ID Remapping:** Assign a globally unique object number (`newObjId`) to every imported indirect object from Document B, C, etc., and rewrite all internal indirect references (`<oldId> <gen> R` → `<newId> 0 R`).
3. **`/Pages` Tree Grafting & `/Parent` Pointer Rewiring:** Attach all imported `/Page` dictionaries into the target `/Pages` node array (`/Kids [...]`), update each page's `/Parent` reference to point to the unified `/Pages` root, and recompute `/Count`.
4. **Byte-Offset Serialization & `xref` Generation:** Write the unified object graph sequentially into an output `Uint8Array` while recording the exact byte offset of each `N 0 obj` header to build the final `xref` table.

---

## 2. Step 1: Parsing Source Object Tables and Computing Offset Maps

Before merging, each input `ArrayBuffer` must be indexed so we can extract its raw indirect objects and resolve `N G R` references:

```javascript
export function indexPdfIndirectObjects(bytes) {
  const decoder = new TextDecoder('latin1');
  const text = decoder.decode(bytes);
  const objects = new Map();
  const objHeaderRegex = /(?:^|[\r\n\s])(\d+)\s+(\d+)\s+obj[\r\n\s]/g;
  let match;

  while ((match = objHeaderRegex.exec(text)) !== null) {
    const objNum = parseInt(match[1], 10);
    const genNum = parseInt(match[2], 10);
    const bodyStart = match.index + match[0].length;
    const endObjIdx = text.indexOf('endobj', bodyStart);
    if (endObjIdx === -1) continue;

    const rawBody = text.slice(bodyStart, endObjIdx).trim();
    objects.set(objNum, {
      objNum,
      genNum,
      bodyStart,
      bodyEnd: endObjIdx,
      rawBody,
      rawBytes: bytes.subarray(bodyStart, endObjIdx),
    });
  }
  return objects;
}

3. Step 2: Collision-Free Indirect Object Renumbering (Old ID → New ID)

When importing Document B's pages and resources into the merged document, we must never alter numeric operands inside compressed binary /FlateDecode streams. Instead, we split the dictionary header from any binary stream payload before remapping N G R tokens:

export function remapIndirectReferences(rawObjectStr, idMap) {
  const streamBoundary = rawObjectStr.search(/stream[\r\n]/);
  const headerPart =
    streamBoundary !== -1 ? rawObjectStr.slice(0, streamBoundary) : rawObjectStr;
  const streamPart =
    streamBoundary !== -1 ? rawObjectStr.slice(streamBoundary) : '';

  const remappedHeader = headerPart.replace(
    /\b(\d+)\s+(\d+)\s+R\b/g,
    (fullMatch, oldIdStr) => {
      const oldId = parseInt(oldIdStr, 10);
      const newId = idMap.get(oldId);
      return newId !== undefined ? `${newId} 0 R` : fullMatch;
    }
  );
  return remappedHeader + streamPart;
}

4. Step 3: Flattening and Grafting the /Pages Balanced Tree & Resource Isolation

In ISO 32000-1 Section 7.7.3, intermediate /Pages nodes can hold inherited attributes such as /MediaBox, /CropBox, and /Rotate. During page tree normalization, inherited attributes are propagated down to each terminal /Type /Page leaf node before grafting into the unified /Kids array.

Furthermore, resource names like /F1 or /Im0 inside a page's content stream (BT /F1 12 Tf (Hello) Tj ET) are scoped locally to that /Page object's /Resources dictionary. As long as each /Page dictionary retains its own remapped /Resources sub-graph, /F1 on Page 1 and /F1 on Page 2 resolve independently with zero cross-page interference.

In production client-side workflows where users need to combine multi-document packets, reorder page ranges, and preserve vector fidelity without transmitting sensitive files over the network, using an in-browser Merge PDF engine executes this entire object-graph remapping and /Pages tree assembly locally inside WebAssembly and JavaScript memory buffers.


5. Step 4: Serializing the Unified PDF and Rebuilding the xref Table

Once all reachable objects from the input documents have been assigned sequential IDs and all /Page leaves point to the unified /Pages root, the serializer writes the output buffer and constructs a strict 20-byte-per-row xref table:

export function serializeMergedPdf(mergedObjects, catalogObjId = 1) {
  const chunks = [];
  const offsets = new Map();
  let currentByteOffset = 0;

  const pushStr = (str) => {
    const buf = new TextEncoder().encode(str);
    chunks.push(buf);
    currentByteOffset += buf.byteLength;
  };

  pushStr('%PDF-1.7\n%\xE2\xE3\xCF\xD3\n');
  const sortedIds = [...mergedObjects.keys()].sort((a, b) => a - b);
  const maxObjId = sortedIds[sortedIds.length - 1] || 0;

  for (const id of sortedIds) {
    offsets.set(id, currentByteOffset);
    pushStr(`${id} 0 obj\n${mergedObjects.get(id)}\nendobj\n`);
  }

  const xrefStartOffset = currentByteOffset;
  const size = maxObjId + 1;
  pushStr(`xref\n0 ${size}\n0000000000 65535 f \r\n`);

  for (let i = 1; i <= maxObjId; i++) {
    const row = offsets.has(i)
      ? String(offsets.get(i)).padStart(10, '0') + ' 00000 n \r\n'
      : '0000000000 65535 f \r\n';
    pushStr(row);
  }

  pushStr(`trailer\n<< /Size ${size} /Root ${catalogObjId} 0 R >>\nstartxref\n${xrefStartOffset}\n%%EOF\n`);
  const output = new Uint8Array(currentByteOffset);
  let pos = 0;
  for (const chunk of chunks) {
    output.set(chunk, pos);
    pos += chunk.byteLength;
  }
  return output;
}

About the Author: Islam Ayoub — Systems & Client-Side WebAssembly / JavaScript Software Engineer researching binary document formats (ISO 32000 PDF internal object graphs, cross-reference tables, and font subsetting), vector rendering pipelines, and browser-native security tooling.