Skip to content

Instantly share code, notes, and snippets.

@mrnejc
Created December 23, 2022 15:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrnejc/2328af331c059377c1617da6cba600c0 to your computer and use it in GitHub Desktop.
Save mrnejc/2328af331c059377c1617da6cba600c0 to your computer and use it in GitHub Desktop.
convert PDF to CBZ via GhostScript, some parameters can be set (requires ghostscript, ionice, zip, jhead & imagemagick/graphicsmagick)
#!/bin/bash
SAVEIFS="$IFS"
IFS=$(echo -en "\n\b")
# requires ghostscript, ionice, zip, jhead & imagemagick/graphicsmagick
# do not delete temp directory with temp files
DELETE=false
# default resolution is 150 dpi
PDF_RES=150
# default JPEG qulity is 80%
JPEGQ=80
for param in "$@"
do
if [ "$param" = "--delete" ] || [ "$param" = "-d" ]; then
echo "config: will delete temporary files"
DELETE=true
elif [ "$param" = "--96dpi" ]; then
echo "config: render PDF to 96 dpi"
PDF_RES=96
elif [ "$param" = "--200dpi" ]; then
echo "config: render PDF to 200 dpi"
PDF_RES=200
elif [ "$param" = "--300dpi" ]; then
echo "config: render PDF to 300 dpi"
PDF_RES=300
elif [ "$param" = "--help" ]; then
echo "options [--delete] [--96dpi|--200dpi|--300dpi]"
exit 0
fi
done
# for all PDFs
for PDF in $(ls -1 *.pdf);
do
echo "Working on $PDF:"
# get filename without extension
FILEP=${PDF%.*}
# clean filename without spaces
FILEPC=`echo $FILEP | sed 's| |\.|g'`
mkdir $FILEPC
echo " - [1/3] Extracting pages from [$PDF]"
gs -q -dNOPAUSE -dBATCH \
-sDEVICE=png16m \
-r$PDF_RES \
-dTextAlphaBits=4 -dUseCropBox \
-sOutputFile=$FILEPC/%03d.png $PDF
echo " - [2/3] Converting pages to JPG, quality is $JPEGQ %"
for I in $(ls -1 $FILEPC/*.png)
do
convert $I -quality $JPEGQ ${I%%.png}.jpg && rm $I
done
jhead -purejpg -q $FILEPC/*.jpg
CBZ=$FILEP-$PDF_RES-dpi.cbz
echo " - [3/3] Packing to CBZ file [$CBZ]"
ionice -c 3 find "$FILEPC/" -type f | sort | zip -j -T -9 "$CBZ" -@ > /dev/null
if [ "$DELETE" = "true" ]; then
rm -rf $FILEPC
fi
echo ""
done
IFS="$SAVEIFS"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment