Skip to content

Instantly share code, notes, and snippets.

@drrost
Created March 31, 2025 14:33
Show Gist options
  • Save drrost/ae024821be06dc8ea3a288f15c262785 to your computer and use it in GitHub Desktop.
Save drrost/ae024821be06dc8ea3a288f15c262785 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Check if an argument is provided
if [ -z "$1" ]; then
echo "Error: You must provide the path to a PDF file as an argument."
exit 1
fi
pdf_file="$1"
# Check if the file exists
if [ ! -f "$pdf_file" ]; then
echo "Error: File '$pdf_file' not found."
exit 1
fi
# Prepare output directory
dir="$(dirname "$pdf_file")"
base_name="$(basename -- "$pdf_file" .pdf)"
output_dir="$dir/images"
mkdir -p "$output_dir"
# Get number of pages
page_count=$(pdfinfo "$pdf_file" | awk '/Pages:/ {print $2}')
# Convert to PNG
if [ "$page_count" -gt 1 ]; then
pdftoppm -png "$pdf_file" "$output_dir/$base_name"
else
pdftoppm -png "$pdf_file" "$output_dir/$base_name"
mv "$output_dir/${base_name}-1.png" "$output_dir/${base_name}.png"
fi
# Build output PDF name
output_pdf="${output_dir}/${base_name}_converted.pdf"
# Find PNGs safely (supporting spaces and Unicode), and store in an array
IFS=$'\n' read -d '' -r -a png_files < <(find "$output_dir" -maxdepth 1 -type f -name "${base_name}-*.png" -print | sort && printf '\0')
# If no multiple PNGs found, check for single-page file
if [ ${#png_files[@]} -eq 0 ]; then
png_files=("$output_dir/${base_name}.png")
fi
# Check that at least one PNG file exists
if [ ! -f "${png_files[0]}" ]; then
echo "Error: No PNG files found for conversion."
exit 1
fi
# Combine into PDF using ImageMagick v7
if magick "${png_files[@]}" "$output_pdf"; then
echo "Conversion complete: $output_pdf"
mv "$output_pdf" "$dir/"
rm -rf "$output_dir"
else
echo "Error: Failed to create the output PDF."
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment