photos2pdf/03-pdf.sh
2023-12-10 12:14:40 +01:00

99 lines
2.5 KiB
Bash
Executable File

#!/bin/bash
# shellcheck disable=SC2046
##
# Configuration
# Paper size of all pages
paper="a4paper"
# Offset in page where image should be placed
offset="1cm 3cm"
# Factor to scale image by before placing in page
scale=0.75
# Filename of complete result PDF
result="pdf/result.pdf"
##
# Main Program
dir="$(dirname "$(readlink -f "$0")")"
if ! cd "$dir" ; then
echo "ERROR: Could not change to directory \"$dir\"; aborted." >&2
exit 1
elif ! mkdir -p pdf tmp ; then
echo "ERROR: Could not create \"$dir/{pdf,tmp}\"; aborted." >&2
exit 1
elif ! rm -f -- "pdf/"*.* ; then
echo "ERROR: Could not delete existing results in \"$dir/pdf\"; aborted." >&2
exit 1
else
rv=0
for png in "out/"*.png ; do
echo "INFO: Processing \"$png\" ..." >&2
read -r width height < <(
identify -verbose "$png" | \
perl -ne '/Geometry: (\d+)x(\d+)/ && print "$1 $2"'
)
if [[ -z $width ]] || [[ -z $height ]] ; then
echo "ERROR: Could not identify width or height of \"$png\"; skipped." >&2
rv=1
continue
elif [[ $width -gt $height ]] ; then
backdrop=template/a4paper/landscape.pdf
jam_landscape=--landscape
else
backdrop=template/a4paper/portrait.pdf
jam_landscape=--no-landscape
fi
base=$(basename "$png" .png)
pdf=tmp/$base.pdf
jammed=tmp/$base-pdfjam.pdf
backdropped=tmp/$base.backdropped.pdf
if ! convert "$png" "$pdf" ; then
echo "ERROR: Could not convert \"$png\" to PDF; skipped." >&2
rv=1
continue
elif ! pdfjam \
--quiet \
--outfile tmp \
--paper "$paper" \
"$jam_landscape" \
--scale "$scale" \
--offset "$offset" \
"$pdf"
then
echo "ERROR: Could not align \"$pdf\"; skipped." >&2
rv=1
continue
elif ! pdftk \
"$jammed" \
stamp "$backdrop" \
output "$backdropped"
then
echo "ERROR: Could not watermark \"$pdf\"; skipped." >&2
rv=1
continue
fi
done
if ! pdftk $(ls -- "tmp/"*.backdropped.pdf) cat output "$result" ; then
echo "ERROR: Could not concatenate \"$result\"." >&2
rv=1
elif ! rm -f -- "tmp/"*.pdf ; then
echo "ERROR: Could not remove tempfiles in \"$dir/tmp\"." >&2
rv=1
fi
exit "$rv"
fi