Skip to content

Instantly share code, notes, and snippets.

@astronasutarou
Created April 23, 2024 05:33
Show Gist options
  • Save astronasutarou/10b2389878a83eddaecf971f62ad6ca8 to your computer and use it in GitHub Desktop.
Save astronasutarou/10b2389878a83eddaecf971f62ad6ca8 to your computer and use it in GitHub Desktop.
A bash script to crop out the margins of the PDF file.
#!/bin/bash
INPUT=${1:?}
OUTPUT=${2:-${INPUT//.pdf/-crop.pdf}}
get_bbox() {
gs -sDEVICE=bbox \
-dBATCH -dNOPAUSE \
-c save pop \
-f ${INPUT} 2>&1 \
| grep 'HiResBoundingBox' \
| awk 'BEGIN{x0=9999;y0=9999;} {x0=(x0<$2)?x0:$2;y0=(y0<$3)?y0:$3;W=(W>$4)?W:$4;H=(H>$5)?H:$5;} END {printf "%.6f %.6f %.6f %.6f", x0, y0, W, H}'
}
BBOX=$(get_bbox)
gs -o ${OUTPUT} \
-sDEVICE=pdfwrite \
-c "[/CropBox [${BBOX}]" \
-c "/PAGES pdfmark" \
-f ${INPUT}
echo "## intput file: ${INPUT}"
pdfinfo ${INPUT}
echo ""
echo "## output file: ${OUTPUT}"
pdfinfo ${OUTPUT}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment