Skip to content

Instantly share code, notes, and snippets.

@pfrozi
Created July 13, 2023 12:13
Show Gist options
  • Save pfrozi/b656d52ef14cd9f8e76b09961f419eca to your computer and use it in GitHub Desktop.
Save pfrozi/b656d52ef14cd9f8e76b09961f419eca to your computer and use it in GitHub Desktop.
PDF to JPG converter via Ghostscript
#!/bin/bash
if command -v gs >/dev/null 2>&1 ; then
echo "gs found"
else
echo "GPL Ghostscript not found"
fi
out_pages=$(echo $1 | sed -e "s/\.pdf$/-p%02d\.jpg/g")
out_files=$(echo $1 | sed -e "s/\.pdf$/-p*\.jpg/g")
out_final=$(echo $1 | sed -e "s/\.pdf$/\.jpg/g")
# total_pages=$(gs -q -c "(${1}) (r) file runpdfbegin pdfpagecount = quit" -f $1)
echo "Parameters"
echo 'In($1) = ' $1
echo 'Out($out_pages) = ' $out_pages
echo 'Out($out_final) = ' $out_final
# echo 'TotalPages = ' $total_pages
echo "Parameters - Consts"
DPI=150
ALPHABITS=2
QUALITY=80
FIRSTPAGE=1
LASTPAGE=99
# MEMORY in MB
MEMORY=10
# echo 'DPI: ' $DPI
# echo 'ALPHABITS: ' $ALPHABITS
# echo 'QUALITY: ' $QUALITY
# echo 'FIRSTPAGE: ' $FIRSTPAGE
# echo 'LASTPAGE: ' $LASTPAGE
# echo 'MEMORY: ' $MEMORY
gs \
-sDEVICE=jpeg \
-sOutputFile=$out_pages \
-r${DPI} \
-dNOPAUSE \
-dFirstPage=${FIRSTPAGE} \
-dLastPage=${LASTPAGE} \
-dJPEGQ=${QUALITY} \
-dGraphicsAlphaBits=${ALPHABITS} \
-dTextAlphaBits=${ALPHABITS} \
-dNumRenderingThreads=4 \
-dBufferSpace=${MEMORY}000000 \
-dBandBufferSpace=${MEMORY}000000 \
-c ${MEMORY}000000 setvmthreshold \
-f $1 \
-c quit
montage \
-border 0 \
-tile 1x0 \
-quality 100 -geometry 595x842+11+22 \
$out_files \
$out_final
rm -f ${out_files}
@pfrozi
Copy link
Author

pfrozi commented Jul 13, 2023

Example:

./converter-pdf2jpg.sh ./test.pdf

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment