Files
Lucas Vivohost f313e9edfa refactor: optimize PDF image splitting script
refactor: optimize PDF image splitting script

- simplify path and filename handling
- safely quote file paths
- improve temporary directory management
- remove redundant shell pipelines
- simplify image batching
- add error handling and progress output
- document usage and processing steps
2026-09-14 12:44:39 +02:00

102 lines
2.0 KiB
Bash
Executable File

#!/bin/bash
# Convert a PDF into processed JPG images and split them into
# multiple PDF files, with a maximum of 100 images per output PDF.
set -e
if [ "$#" -ne 1 ]; then
echo "Usage: $0 <pdf-file>"
exit 1
fi
pdf_file="$1"
if [ ! -f "$pdf_file" ]; then
echo "Error: '$pdf_file' does not exist."
exit 1
fi
echo "Using $pdf_file"
# Resolve the input directory and filename.
pdf_dir="$(cd "$(dirname "$pdf_file")" && pwd)"
pdf_name="$(basename "$pdf_file")"
base_name="${pdf_name%.*}"
buffer_dir="$pdf_dir/.BUFFERFOLDER"
# Recreate the temporary working directory.
rm -rf "$buffer_dir"
mkdir -p "$buffer_dir"
cp "$pdf_file" "$buffer_dir/$pdf_name"
cd "$buffer_dir"
echo "Extracting images..."
# Extract PDF images as PNG.
pdfimages -png "$pdf_name" "$base_name"
count=0
shopt -s nullglob
for img in *.png; do
jpg="${img%.png}.jpg"
echo "Processing $jpg"
# PNG -> JPG
convert "$img" "$jpg"
rm "$img"
# Normalize image dimensions.
convert "$jpg" -resize 2550x3300! "$jpg"
# Use different crop dimensions for images containing "000".
if [[ "$jpg" == *000* ]]; then
convert "$jpg" -crop 2206x3200+200+50 "$jpg"
else
convert "$jpg" -crop 2106x3200+200+50 "$jpg"
fi
# Remove white background.
convert "$jpg" -fuzz 20% -transparent White "$jpg"
# Center image on a white 2550x3300 canvas.
convert "$jpg" \
-resize 2550x3300 \
-gravity center \
-background White \
-extent 2550x3300 \
"$jpg"
# Group images into batches of 100.
split_var=$((count / 100))
split_dir="split_${split_var}"
mkdir -p "$split_dir"
mv "$jpg" "$split_dir/"
((count++)) || true
done
# Convert each group of images into a PDF.
for split_dir in split_*; do
[ -d "$split_dir" ] || continue
split_number="${split_dir#split_}"
echo "Converting Part $split_number"
convert "$split_dir"/*.jpg \
"$pdf_dir/${base_name}_split_${split_number}.pdf"
done
# Remove temporary files.
cd "$pdf_dir"
rm -rf "$buffer_dir"
echo "Done."