Skip to content

Instantly share code, notes, and snippets.

@bagustris
Created April 16, 2026 07:41
Show Gist options
  • Select an option

  • Save bagustris/59a1a3ed26839a83c41b762bfdd2dbec to your computer and use it in GitHub Desktop.

Select an option

Save bagustris/59a1a3ed26839a83c41b762bfdd2dbec to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
# flat_pdf.sh - Bake PDF annotations into page content (flatten)
# Usage: flat_pdf.sh input.pdf
# Output: input-flat.pdf
set -e
if [[ $# -ne 1 ]]; then
echo "Usage: $0 input.pdf"
exit 1
fi
INPUT="$1"
BASENAME="${INPUT%.pdf}"
OUTPUT="${BASENAME}-flat.pdf"
if [[ ! -f "$INPUT" ]]; then
echo "Error: file not found: $INPUT"
exit 1
fi
python3 - "$INPUT" "$OUTPUT" << 'EOF'
import sys
import fitz # PyMuPDF
src_path, dst_path = sys.argv[1], sys.argv[2]
src = fitz.open(src_path)
dst = fitz.open()
for page in src:
w, h = page.rect.width, page.rect.height
mat = fitz.Matrix(6, 6) # 432 DPI
pix = page.get_pixmap(matrix=mat, alpha=False, annots=True)
new_page = dst.new_page(width=w, height=h)
new_page.insert_image(new_page.rect, pixmap=pix)
dst.save(dst_path, deflate=True)
print(f"Saved: {dst_path}")
EOF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment