Linux – Bash Resize, split, Rotate or concatenate PDFs

This has probably been done a thousand times and ways, and much better than my humble fiddling. Consider this my memory pad for later.

I am doing some scripted pdf magic with files that come in from the scanner. They are either too big for web use, wrong format, not the right orientation (user error) or similar. So here’s a little collection:

Convert all (huge) PDFs into small ones with ghostscript (assuming ./Z-OLD for old versions exists):

for i in *.pdf; do gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/ebook -dNOPAUSE -dQUIET -dBATCH -sOutputFile=$i-small.pdf $i; mv $i Z-OLD/; rename .pdf-small.pdf .pdf *-small.pdf; done

Convert all PNGs in working directory into small PDFs (assuming ./png exists):

for i in *.png; do convert $i $i.pdf; mv $i png/; gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/ebook -dNOPAUSE -dQUIET -dBATCH -sOutputFile=$i-small.pdf $i.pdf; rename .png-small.pdf .pdf *.png-small.pdf; rm *.png.pdf; done

Concatenate PDFs into one file (the last argument is the new outputfile):

pdfunite A.pdf B.pdf C.pdf ABC.pdf

A lazy “rotate all” script that helps me if I put the paper on the scanner the wrong way. Leaves four versions of every pdf it finds, but 90/180/270° degrees tilted to the original.

#!/bin/bash
INFILE=ls.txt
ls *pdf -1 > $INFILE
while IFS=”²” read -r line
do
PDF=`basename $line | rev | cut -c 5- | rev`
#left turn
pdftk “$line” cat 1-endwest output “$PDF”_left.pdf
#right turn
pdftk “$line” cat 1-endeast output “$PDF”_right.pdf
#turn 180 degrees:
pdftk “$line” cat 1-endsouth output “$PDF”_upsidedown.pdf
done <$INFILE

And yes, I know, there’s better ways. Worx 4 me, I guess. 🙂