Get Updates by Email

Thursday, 20 March 2014

Using PDFTK to compress PDFs

I created a bash script to compress all the PDF files in the sub-directory. The original would be processed by PDFTK to create a new file. If the new file was sized smaller than the original, the original would be deleted, otherwise the new file would be deleted.

I did notice that sometimes, PDFTK has some errors, and the new file created was sized 0 bytes. In those cases, we would copy the original file to the new, then run the above test: Is the new bigger than the old?

Here is the text of the bash script.

echo Will now compress all PDF files in this directory using PDFTK.
echo " "

for xxx in *.pdf

echo Processing "$xxx" ...
pdftk "$xxx" output "$" compress

if [ -f "$" ]
mv "$xxx" "$xxx.old"
mv "$" "$xxx"
echo "Old size is" $(stat --print="%s" "$xxx.old")
echo "New size is" $(stat --print="%s" "$xxx")

if [ $(stat --print="%s" "$xxx") == 0 ]; then
echo "New file size is 0. Original COPIED."
cp "$xxx.old" "$xxx"

if [ $(stat --print="%s" "$xxx") -ge $(stat --print="%s" "$xxx.old") ]; then
echo "New file is bigger or same - original RESTORED."
mv "$xxx.old" "$xxx"
echo "Old file is bigger - original DELETED."
rm "$xxx.old"


echo " "