-
Notifications
You must be signed in to change notification settings - Fork 0
/
pdfcrop
executable file
·46 lines (38 loc) · 1.16 KB
/
pdfcrop
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#!/usr/bin/env zsh
IN_FILE="$1"
OUT_FILE="${IN_FILE%.pdf}_cropped.pdf"
PADDING_X=10
PADDING_Y=10
# Determine bounding box
MINMAX_AWK='{
if (NR==1) {left = $1; bottom = $2; right=$3; top=$4;}
else {
if ($1 < left) left = $1;
if ($2 < bottom) bottom = $2;
if ($3 > right) right = $3;
if ($4 > top) top = $4;
}}
END {print left, bottom, right, top}'
BBOX=(`gs -q -dBATCH -dNOPAUSE -sDEVICE=bbox "$IN_FILE" 2>&1 | grep -v HiResBoundingBox | sed 's/.*: *//' | awk "$MINMAX_AWK"`)
# BBOX=(left bottom right top)
echo "BBOX: $BBOX"
# Compute offset and new size
OFFSET_X=`expr $BBOX[1] - $PADDING_X`
OFFSET_Y=`expr $BBOX[2] - $PADDING_Y`
NEW_WIDTH=`expr $BBOX[3] - $OFFSET_X + $PADDING_X`
NEW_HEIGHT=`expr $BBOX[4] - $OFFSET_Y + $PADDING_Y`
echo "Offset: $OFFSET_X $OFFSET_Y"
echo "New size: $NEW_WIDTH $NEW_HEIGHT"
# Translate parameters for `pdfwrite`
OFFSET_X=`expr 0 - $OFFSET_X`
OFFSET_Y=`expr 0 - $OFFSET_Y`
NEW_WIDTH=`expr $NEW_WIDTH \* 10`
NEW_HEIGHT=`expr $NEW_HEIGHT \* 10`
# Crop PDF
gs \
-o "$OUT_FILE" \
-sDEVICE=pdfwrite \
-g"$NEW_WIDTH"x"$NEW_HEIGHT" \
-c "<</PageOffset [$OFFSET_X $OFFSET_Y]>> setpagedevice" \
-f "$IN_FILE"
echo "Output written to '$OUT_FILE'."