pdf-jammer/pdf-jammer.sh

67 lines
1.7 KiB
Bash
Executable File

#!/bin/bash
# _ __ _ _
# _ __ __| |/ _| (_) __ _ _ __ ___ _ __ ___ ___ _ __ ___| |__
#| '_ \ / _` | |_ _____| |/ _` | '_ ` _ \| '_ ` _ \ / _ \ '__/ __| '_ \
#| |_) | (_| | _|_____| | (_| | | | | | | | | | | | __/ | _\__ \ | | |
#| .__/ \__,_|_| _/ |\__,_|_| |_| |_|_| |_| |_|\___|_|(_)___/_| |_|
#|_| |__/
#
# Ensure necessary binaries
for cmd in pdfjam pdfcrop pdfinfo pdfcropmargins; do
if ! command -v "$cmd" &>/dev/null; then
echo "Please install $cmd to use this script."
exit 1
fi
done
# Args
if [ "$#" -lt 3 ] || [ "$#" -gt 4 ]; then
echo "Usage: $0 input.pdf rows columns [margin]"
exit 1
fi
input_pdf="$1"
rows="$2"
columns="$3"
margin="${4:-0}" # Set margin if provided, else default to 0
intermediate_pdf="$(mktemp).pdf"
cropped_output_pdf="$(mktemp).pdf"
# Cleanup temporary files on exit
trap 'rm -f "$intermediate_pdf" "$cropped_output_pdf"' EXIT
# Generate the grid PDF
pdfjam \
--nup "$columns"x"$rows" \
--a4paper \
--outfile "$intermediate_pdf" \
$(for i in $(seq 1 $((rows * columns))); do echo "$input_pdf"; done)
if [ $? -ne 0 ]; then
echo "Error: pdfjam failed to generate the grid PDF."
exit 1
fi
# Apply margin if provided
if [[ "$margin" != 0 ]]; then
pdfcropmargins \
-o "$cropped_output_pdf" \
-s \
-p 100 \
-a4 \
-$margin -$margin -$margin -$margin \
"$intermediate_pdf"
if [ $? -ne 0 ]; then
echo "Error: pdfcropmargins failed to apply the margins."
exit 1
fi
else
mv "$intermediate_pdf" "$cropped_output_pdf"
fi
final_pdf="jammed.pdf"
mv "$cropped_output_pdf" "$final_pdf"
echo "Final centered PDF created as $final_pdf"