#!/usr/bin/python3
r"""Magnify and shift the pages of a PDF file, like pdfjam --scale --offset,
but preserving hyperlinks, bookmarks and everything else.

Intended for documents typeset in a publisher style designed for a page
smaller than A4 (e.g., LNCS, or an ACM journal format of acmart), to get
reasonable margins and font size on A4 paper. Reformatting the source
for A4 is still preferable. For acmart, for example, these lines give
12 pt type with about 80 characters per line on A4:

  \documentclass[acmsmall,12pt]{acmart}
  \geometry{a4paper,hmargin=35mm,vmargin=25mm}

Each page is scaled by --scale around its centre, centred on the output
paper, and then shifted by --offset. With --twoside, the horizontal
offset is mirrored on even pages. Page content is wrapped in a single
transformation; link rectangles and the coordinates of explicit
destinations (links, outline, named destinations) are transformed to
match. Nothing else in the file is touched.

Examples:
  LNCS:
    python3 pdfmag.py --scale 1.25 --offset '-4.5mm -13mm' -o a4.pdf lncs.pdf
  ACM journal layout printed by acmart on A4:
    python3 pdfmag.py --twoside --scale 1.15 --offset '7mm -15mm' -o a4.pdf acm.pdf

For other layouts, first find the area covered by the text on each page,
with "gs -q -dNOPAUSE -dBATCH -sDEVICE=bbox file.pdf" (coordinates in
points, origin at the bottom left), then choose a --scale factor that
leaves 20-30 mm margins, and an --offset that centres the result.

pdfjam (part of TeX Live) accepts the same parameters, plus --a4paper,
but discards hyperlinks and bookmarks. For a PostScript file of an LNCS
document, try pstops '0@1.25(-2.95cm,-4.5cm)' or
pstops '0@1.20(-2.40cm,-3.7cm)'.

Requires pikepdf (Ubuntu/Debian package python3-pikepdf,
or "pip install pikepdf").

Markus Kuhn, 2026
"""

import argparse
import re
import sys

import pikepdf
from pikepdf import Array, Dictionary, Name

UNITS = {'pt': 72 / 72.27, 'bp': 1.0, 'mm': 72 / 25.4,
         'cm': 72 / 2.54, 'in': 72.0, '': 1.0}
PAPERS = {'a4': (595.276, 841.89), 'a5': (419.528, 595.276),
          'a3': (841.89, 1190.551), 'letter': (612.0, 792.0)}


def length(s):
    """Parse a TeX-style length such as '7mm' or '-1.5cm' into bp."""
    m = re.fullmatch(r'\s*([-+]?(?:\d+\.?\d*|\.\d+))\s*([a-z]*)\s*', s)
    if not m or m.group(2) not in UNITS:
        raise argparse.ArgumentTypeError(f'bad length: {s!r}')
    return float(m.group(1)) * UNITS[m.group(2)]


def offset(s):
    parts = s.split()
    if len(parts) != 2:
        raise argparse.ArgumentTypeError(f'offset needs two lengths: {s!r}')
    return tuple(length(p) for p in parts)


def paper(s):
    if s.lower() in PAPERS:
        return PAPERS[s.lower()]
    parts = s.lower().split('x')
    if len(parts) != 2:
        raise argparse.ArgumentTypeError(f'unknown paper: {s!r}')
    return tuple(length(p) for p in parts)


def num(x):
    """Format a number compactly for a PDF content stream."""
    return f'{x:.4f}'.rstrip('0').rstrip('.')


class Transform:
    def __init__(self, s, tx, ty):
        self.s, self.tx, self.ty = s, tx, ty

    def x(self, v):
        return self.s * float(v) + self.tx

    def y(self, v):
        return self.s * float(v) + self.ty

    def rect(self, r):
        x0, y0, x1, y1 = (float(v) for v in r)
        return Array([self.x(min(x0, x1)), self.y(min(y0, y1)),
                      self.x(max(x0, x1)), self.y(max(y0, y1))])


# positions of x and y coordinates in explicit destination arrays,
# counted from the element after the page reference
DEST_COORDS = {
    '/XYZ': 'xy', '/FitH': 'y', '/FitBH': 'y', '/FitV': 'x', '/FitBV': 'x',
    '/FitR': 'xyxy', '/Fit': '', '/FitB': '',
}


def fix_dest(arr, transforms):
    """Transform an explicit destination [page /Fit... coords] in place."""
    if len(arr) < 2 or not isinstance(arr[0], Dictionary) \
            or not isinstance(arr[1], Name) or str(arr[1]) not in DEST_COORDS:
        return
    t = transforms.get(arr[0].objgen)
    if t is None:
        return
    for i, axis in enumerate(DEST_COORDS[str(arr[1])], start=2):
        if i >= len(arr):
            break
        try:
            v = float(arr[i])
        except (TypeError, ValueError):
            continue            # null: keep current position
        arr[i] = t.x(v) if axis == 'x' else t.y(v)


def walk(obj, transforms, top=True):
    """Find explicit destination arrays among the direct descendants of an
    object (indirect objects are each visited once by the caller)."""
    if not top and obj.is_indirect:
        return
    if isinstance(obj, Array):
        if len(obj) >= 2 and isinstance(obj[1], Name):
            fix_dest(obj, transforms)
        for v in obj:
            if isinstance(v, (Array, Dictionary)):
                walk(v, transforms, False)
    elif isinstance(obj, Dictionary):
        for k in obj.keys():
            v = obj[k]
            if isinstance(v, (Array, Dictionary)):
                walk(v, transforms, False)


def main():
    ap = argparse.ArgumentParser(
        description=__doc__.rsplit('\n\n', 1)[0],   # without author line
        formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument('input')
    ap.add_argument('-o', '--outfile', required=True)
    ap.add_argument('--scale', type=float, required=True)
    ap.add_argument('--offset', type=offset, default=(0.0, 0.0),
                    help="e.g. '7mm -15mm' (positive = right, up)")
    ap.add_argument('--paper', type=paper, default=PAPERS['a4'],
                    help='a4 (default), a5, a3, letter, or WxH like 210mmx297mm')
    ap.add_argument('--twoside', action='store_true',
                    help='mirror the horizontal offset on even pages')
    args = ap.parse_args()

    W, H = args.paper
    s = args.scale
    ox, oy = args.offset

    with pikepdf.open(args.input) as pdf:
        transforms = {}
        for n, page in enumerate(pdf.pages, start=1):
            if int(page.obj.get('/Rotate', 0)) % 360:
                sys.exit(f'page {n}: /Rotate not supported')
            x0, y0, x1, y1 = (float(v) for v in page.mediabox)
            cx, cy = (x0 + x1) / 2, (y0 + y1) / 2
            dx = -ox if args.twoside and n % 2 == 0 else ox
            # x' = W/2 + s (x - cx) + dx
            t = Transform(s, W / 2 - s * cx + dx, H / 2 - s * cy + oy)
            transforms[page.obj.objgen] = t

            page.contents_add(pdf.make_stream(
                f'q {num(s)} 0 0 {num(s)} {num(t.tx)} {num(t.ty)} cm\n'
                .encode()), prepend=True)
            page.contents_add(pdf.make_stream(b'\nQ\n'))
            page.obj.MediaBox = Array([0, 0, W, H])
            for box in ('/CropBox', '/BleedBox', '/TrimBox', '/ArtBox'):
                if box in page.obj:
                    del page.obj[box]

            for annot in page.obj.get('/Annots', []):
                if '/Rect' in annot:
                    annot.Rect = t.rect(annot.Rect)
                if '/QuadPoints' in annot:
                    q = [float(v) for v in annot.QuadPoints]
                    annot.QuadPoints = Array(
                        [t.x(v) if i % 2 == 0 else t.y(v)
                         for i, v in enumerate(q)])

        for obj in pdf.objects:
            if isinstance(obj, (Array, Dictionary)):
                walk(obj, transforms)

        pdf.save(args.outfile)


if __name__ == '__main__':
    main()
