Skip to content

PDF Merge — Go source

Combine PDF files in order, entirely in your browser — reorder, merge, download. Nothing uploads.

This is the Go implementation — the same logic the interactive tool runs, in a shareable, citable form.

// Package pdfmerge is the Go twin of CosmoDev's src/lib/pdf-merge.ts (dual
// source: the web lib is TypeScript (pdf-lib), the CLI lib is Go — kept in
// lock-step on page-count behaviour). Stdlib-only: instead of pdf-lib it
// concatenates UNENCRYPTED, non-object-stream PDFs by rebuilding the
// cross-reference table — every non-free object of each input is copied into
// one new document with renumbered object ids, and a fresh Catalog + Pages
// tree is written over the copied page objects.
//
// v1 scope (mirrored by the tests): inputs using PDF 1.5+ cross-reference
// STREAMS (/Type /XRef), object streams (/Type /ObjStm — page dicts may live
// inside them), hybrid-reference files (/XRefStm), or /Encrypt return
// ErrUnsupported. The TS lib handles those via pdf-lib; the Go twin serves the
// common classic case. Object headers are located by line-anchored scan
// ("N G obj" at the start of a line), so exotic files whose object headers do
// not begin a line are outside v1 scope too.
package pdfmerge

import (
	"bytes"
	"errors"
	"fmt"
	"regexp"
	"strconv"
	"strings"
)

// ErrUnsupported is returned when an input uses a PDF feature outside the
// classic xref-table subset this twin merges. It mirrors the TS lib's
// PdfToolError('encrypted'/'invalid') carve-outs for /Encrypt and stream xrefs.
var ErrUnsupported = errors.New("pdf-merge: unsupported PDF (v1 merges classic xref-table PDFs only — cross-reference streams, object streams, and encrypted files are not supported)")

// errInvalid mirrors the TS PdfToolError('invalid', 'Not a readable PDF file.')
var errInvalid = errors.New("pdf-merge: not a readable PDF file")

// errEmpty mirrors the TS PdfToolError('invalid', 'Nothing to merge.')
var errEmpty = errors.New("pdf-merge: nothing to merge")

var (
	// Line-anchored object-header scan: "N G obj" at the start of a line.
	reObjHeader = regexp.MustCompile(`(?m)^(\d+)\s+(\d+)\s+obj\b`)
	// Indirect reference "N G R" inside a dict body (never inside stream data).
	reRef = regexp.MustCompile(`(\d+)\s+(\d+)\s+R`)
	// /Type /Page (but NOT /Pages — \b fails between "Page" and "s").
	reTypePage  = regexp.MustCompile(`/Type\s+/Page\b`)
	reTypePages = regexp.MustCompile(`/Type\s+/Pages\b`)
)

// object is one copied source object. dict holds everything from the end of
// the "N G obj" header to either "endobj" (plain object) or the "stream"
// keyword (stream object); stream holds the verbatim stream bytes (nil for
// plain objects).
type object struct {
	num, gen int
	dict     []byte
	stream   []byte
}

// parsedInput is one input document's scanned objects (in file order).
type parsedInput struct {
	objects []object
	pages   []int // obj nums whose dict is /Type /Page
}

// MergePDFs concatenates unencrypted classic xref-table PDFs into one new
// document and returns its bytes. All of every input's objects are copied
// (with renumbered ids and rewritten indirect refs in dict bodies), then a
// fresh Catalog + Pages tree is written whose /Kids are the copied page
// objects in input order. It is the Go twin of mergePdfs() in
// src/lib/pdf-merge.ts and must agree with it on page counts.
func MergePDFs(inputs [][]byte) ([]byte, error) {
	if len(inputs) == 0 {
		return nil, errEmpty
	}
	parsed := make([]*parsedInput, len(inputs))
	for i, in := range inputs {
		p, err := parseInput(in)
		if err != nil {
			return nil, fmt.Errorf("input %d: %w", i+1, err)
		}
		parsed[i] = p
	}

	// Pass 1: assign new object ids across all inputs (sequential from 1).
	var buf bytes.Buffer
	buf.WriteString("%PDF-1.4\n%\xe2\xe3\xcf\xd3\n")
	var pageRefs []string
	next := 1
	offsets := []int{0} // xref entry 0 (the free head)
	maps := make([]map[int]int, len(inputs))
	for i, p := range parsed {
		m := make(map[int]int, len(p.objects))
		for _, o := range p.objects {
			m[o.num] = next
			next++
		}
		maps[i] = m
		for _, num := range p.pages {
			pageRefs = append(pageRefs, fmt.Sprintf("%d 0 R", m[num]))
		}
	}

	// Pass 2: write every copied object with renumbered refs in its dict.
	for i, p := range parsed {
		for _, o := range p.objects {
			offsets = append(offsets, buf.Len())
			gen := o.gen
			fmt.Fprintf(&buf, "%d %d obj\n", maps[i][o.num], gen)
			buf.Write(rewriteRefs(o.dict, maps[i]))
			if o.stream != nil {
				buf.WriteString("\nstream\n")
				buf.Write(o.stream)
				buf.WriteString("\nendstream\n")
			}
			buf.WriteString("endobj\n")
		}
	}

	// Fresh Catalog + Pages tree over the copied page objects.
	catID, pagesID := next, next+1
	offsets = append(offsets, buf.Len())
	fmt.Fprintf(&buf, "%d 0 obj\n<< /Type /Catalog /Pages %d 0 R >>\nendobj\n", catID, pagesID)
	offsets = append(offsets, buf.Len())
	kids := "[ " + strings.Join(pageRefs, " ") + " ]"
	fmt.Fprintf(&buf, "%d 0 obj\n<< /Type /Pages /Kids %s /Count %d >>\nendobj\n", pagesID, kids, len(pageRefs))

	// Rebuilt cross-reference table + trailer.
	size := catID + 2 // highest id + 1 (ids are 1-based, contiguous)
	xrefOff := buf.Len()
	buf.WriteString("xref\n")
	fmt.Fprintf(&buf, "0 %d\n", size)
	buf.WriteString("0000000000 65535 f \n")
	for _, off := range offsets[1:] {
		fmt.Fprintf(&buf, "%010d 00000 n \n", off)
	}
	buf.WriteString("trailer\n")
	fmt.Fprintf(&buf, "<< /Size %d /Root %d 0 R >>\n", size, catID)
	fmt.Fprintf(&buf, "startxref\n%d\n%%%%EOF\n", xrefOff)
	return buf.Bytes(), nil
}

// padRefs defensively copies refs so bytes.Join never aliases callers' slices.

// rewriteRefs maps "N G R" indirect references in a dict body to the new
// numbering. Stream data is never passed through here (content-stream text
// could contain look-alike tokens).
func rewriteRefs(dict []byte, m map[int]int) []byte {
	return reRef.ReplaceAllFunc(dict, func(g []byte) []byte {
		parts := reRef.FindSubmatch(g)
		n, err := strconv.Atoi(string(parts[1]))
		if err != nil {
			return g
		}
		newN, ok := m[n]
		if !ok {
			return g
		}
		return []byte(strconv.Itoa(newN) + " 0 R")
	})
}

// parseInput scans one input PDF: it rejects unsupported features (xref
// streams, object streams, hybrid xref, /Encrypt), then line-scans every
// object header and splits stream objects into dict + verbatim data.
func parseInput(pdf []byte) (*parsedInput, error) {
	if !bytes.Contains(pdf, []byte("%PDF-")) {
		return nil, errInvalid
	}
	if err := checkXrefKind(pdf); err != nil {
		return nil, err
	}
	if err := checkTrailer(pdf); err != nil {
		return nil, err
	}

	in := &parsedInput{}
	byNum := make(map[int]int)
	for _, loc := range reObjHeader.FindAllSubmatchIndex(pdf, -1) {
		num, _ := strconv.Atoi(string(pdf[loc[2]:loc[3]]))
		gen, _ := strconv.Atoi(string(pdf[loc[4]:loc[5]]))
		bodyStart := loc[1]
		bodyEnd := bytes.Index(pdf[bodyStart:], []byte("endobj"))
		if bodyEnd < 0 {
			return nil, errInvalid
		}
		body := pdf[bodyStart : bodyStart+bodyEnd]
		obj := object{num: num, gen: gen}
		if si := findStreamKeyword(body); si >= 0 {
			obj.dict = bytes.TrimRight(body[:si], " \t\r\n")
			data := body[si+len("stream"):]
			// Spec: the stream keyword is followed by CRLF or LF (not a lone CR).
			data = bytes.TrimPrefix(data, []byte("\r\n"))
			data = bytes.TrimPrefix(data, []byte("\n"))
			if ei := bytes.Index(data, []byte("endstream")); ei >= 0 {
				data = bytes.TrimRight(data[:ei], "\r\n")
			}
			obj.stream = data
		} else {
			obj.dict = bytes.TrimRight(body, " \t\r\n")
		}
		if bytes.Contains(obj.dict, []byte("/ObjStm")) {
			return nil, ErrUnsupported // page dicts may live inside object streams
		}
		if prev, ok := byNum[num]; ok {
			in.objects[prev] = obj // incremental update: last definition wins
		} else {
			byNum[num] = len(in.objects)
			in.objects = append(in.objects, obj)
		}
		if reTypePage.Match(obj.dict) && !reTypePages.Match(obj.dict) {
			in.pages = append(in.pages, num)
		}
	}
	if len(in.objects) == 0 {
		return nil, errInvalid
	}
	return in, nil
}

// checkXrefKind follows the last startxref offset: a classic PDF points at the
// "xref" keyword; a PDF 1.5+ xref stream points at "N G obj" whose dict is
// /Type /XRef — reject before scanning so stream-xref files fail fast.
func checkXrefKind(pdf []byte) error {
	idx := bytes.LastIndex(pdf, []byte("startxref"))
	if idx < 0 {
		return errInvalid
	}
	rest := pdf[idx+len("startxref"):]
	fields := bytes.Fields(bytes.TrimLeft(rest, " \t\r\n"))
	if len(fields) == 0 {
		return errInvalid
	}
	off, err := strconv.Atoi(string(fields[0]))
	if err != nil || off < 0 || off >= len(pdf) {
		return errInvalid
	}
	target := bytes.TrimLeft(pdf[off:], " \t\r\n")
	if bytes.HasPrefix(target, []byte("xref")) {
		return nil
	}
	if reObjHeader.Match(target) {
		return ErrUnsupported // cross-reference stream (/Type /XRef)
	}
	return errInvalid
}

// checkTrailer rejects encrypted files and hybrid-reference files.
func checkTrailer(pdf []byte) error {
	idx := bytes.LastIndex(pdf, []byte("trailer"))
	if idx < 0 {
		return nil // no classic trailer keyword — xref-kind check already ran
	}
	trailer := pdf[idx:]
	if end := bytes.Index(trailer, []byte("startxref")); end >= 0 {
		trailer = trailer[:end]
	}
	if bytes.Contains(trailer, []byte("/Encrypt")) {
		return ErrUnsupported // password-protected inputs are out of scope
	}
	if bytes.Contains(trailer, []byte("/XRefStm")) {
		return ErrUnsupported // hybrid-reference file (embedded xref stream)
	}
	return nil
}

// findStreamKeyword returns the index of the dict-terminating "stream"
// keyword (whitespace/'>' before it, EOL after it), or -1 for a plain object.
func findStreamKeyword(body []byte) int {
	for i := 0; i+6 <= len(body); i++ {
		if !bytes.HasPrefix(body[i:], []byte("stream")) {
			continue
		}
		if i == 0 || !isDelim(body[i-1]) {
			continue
		}
		if i+6 < len(body) && (body[i+6] == '\n' || body[i+6] == '\r') {
			return i
		}
	}
	return -1
}

func isDelim(b byte) bool {
	return b == ' ' || b == '\t' || b == '\r' || b == '\n' || b == '>'
}

Also available in 13 other languages

Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →