#!/bin/bash

# 2025-02-02 Simple wrapper over pdfimages, for cases where the pdf is
# just one image, e.g. from a scanner.

# Required software: imagemagick, poppler

# 2025-04-26 Alternative for more complex files:
# magick -density 150 $FILE ${FILE//.pdf/.png};
# Note that the density parameter must come before the input file.

# 2025-02-03 Allow old command name, prefer the new one
for CMD in magick convert; do
    which $CMD && break
done

OUTTYPE=png

while getopts j OPT; do
    case $OPT in
	j)
	    OUTTYPE=jpeg
	    ;;
    esac
done

shift $(($OPTIND - 1))

for FILE in "$@"; do
    TEMP_PREFIX=$(mktemp -p /dev/shm/ -u)
    
    # pdfimages can output PNG etc. directly, but using a "raw" format
    # and converting separately is faster and makes smaller files

    TEMPFILE=$(pdfimages -print-filenames "$FILE" $TEMP_PREFIX)

    OUTFILE="${FILE//.pdf/.$OUTTYPE}"

    if [ -f "$OUTFILE" ]; then
	echo $OUTFILE already exists, skipping
	continue
    fi
    
    $CMD $TEMPFILE "$OUTFILE"

    rm $TEMPFILE
done
