Skip to content

Instantly share code, notes, and snippets.

@qooxzuub
Last active July 16, 2024 09:30
Show Gist options
  • Save qooxzuub/7c919a7cc75070446efd8bab4f533016 to your computer and use it in GitHub Desktop.
Save qooxzuub/7c919a7cc75070446efd8bab4f533016 to your computer and use it in GitHub Desktop.
Crop pdf using qpdf and jq (2)
#!/usr/bin/env bash
if (( $# != 3 )); then
echo Usage: $0 in.pdf out.pdf '"x_bl,y_bl,x_tr,y_tr"'
exit 1
fi
##################################################
## jq code to get minimal(?) json for qpdf to use
## to patch the cropboxes for every page object
# save the page objects
cmd='[(.pages[].object | "obj:" + .)] as $pageObjects | '
# .qpdf needs to be an array with two entries.
# Copy the first entry .qpdf[0]
cmd+='{ qpdf: [ .qpdf[0], '
# For the second entry, select the page objects
# from .qpdf[1] and insert the cropboxes
cmd+='(.qpdf[1] | with_entries(select( .key as $k | any( $pageObjects[] == $k ))'
cmd+=' | .value.value["/CropBox"] = ['"$3"'] )) ]}'
##################################################
tmp="$(tempfile)"
qpdf --json-output --json-key=pages "$1" | jq "$cmd" > "$tmp"
qpdf "$1" --update-from-json="$tmp" "$2" && rm "$tmp"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment