Here's a bash script that uses Ghostscript to extract specified PDF pages as PNGs. I'll explain the options and ask for clarifications first:
Script Options:
Resolution : Should the PNGs use a specific DPI (default is 300)? Ghostscript's -r parameter controls this.
Color Depth : Use 24-bit color (png16m) or grayscale (pnggray)? The script currently uses png16m.
Output Location : Save PNGs in the current directory or next to the original PDF?
Clarifying Questions:
Do you want a default resolution (300 DPI) or should the script allow specifying it via a parameter?
Should the script handle invalid page numbers (e.g., non-numeric input or out-of-range pages)?
Should output files be saved in the same directory as the PDF or the current working directory?
Assuming defaults for now (300 DPI, current directory, error handling for invalid pages), here's the script:
bash Copy code
#!/bin/bash
# Check if Ghostscript is installed
if ! command -v gs &> /dev/null; then
echo "Ghostscript is required. Install with: sudo apt install ghostscript (Debian/Ubuntu)"
exit 1
fi
# Usage help
usage() {
echo "Usage: $0 <PDF_PATH> <PAGES>"
echo "PAGES can be individual numbers (e.g., 3,5) or ranges (e.g., 1-4)"
exit 1
}
# Validate input
[[ $# -ne 2 ]] && usage
[[ ! -f "$1" ]] && echo "Error: PDF file not found" && exit 1
pdf_path="$1"
pages_str="$2"
base_name=$(basename "$pdf_path" .pdf)
# Parse pages into an array
parse_pages() {
local IFS=',' # Split on commas
local pages=()
for range in $1; do
if [[ $range == *-* ]]; then
# Handle ranges like 2-5
start=${range%-*}
end=${range#*-}
if (( start > end )); then
echo "Invalid range: $range (start > end)"
exit 1
fi
for ((i=start; i<=end; i++)); do
pages+=($i)
done
else
# Validate single page number
if ! [[ $range =~ ^[0-9]+$ ]]; then
echo "Invalid page number: $range"
exit 1
fi
pages+=($range)
fi
done
echo "${pages[@]}"
}
pages=($(parse_pages "$pages_str"))
[[ ${#pages[@]} -eq 0 ]] && echo "No valid pages specified" && exit 1
# Process each page
for page in "${pages[@]}"; do
output_file="${base_name}_${page}.png"
echo "Processing page $page → $output_file"
# Ghostscript command (300 DPI, 24-bit color)
gs -q -dBATCH -dNOPAUSE -sDEVICE=png16m -r300 \
-dFirstPage="$page" -dLastPage="$page" \
-sOutputFile="$output_file" "$pdf_path" || {
echo "Error processing page $page"
exit 1
}
done
echo "Done! PNG files saved in current directory:"
ls -1 "${base_name}_".png
To use:
bash Copy code
chmod +x script.sh
./script.sh example.pdf "2-4,7" # Extract pages 2,3,4,7
Key Features:
Handles page ranges (e.g., "1-3")
Validates page numbers
Outputs files like example_2.png, example_3.png, etc.
Shows progress and error messages
Let me know if you want to adjust any parameters (resolution, output location, etc.)!