Scanning woes dispelled

Once again I found myself in a situation where I had to print a document, sign it, scan it and return it as PDF. Being a Linux user and owning a scanner/printer/fax that is largely unsupported (Canon Pixma MP780), I’ve usually ended up using the nifty scan to PDF scanner at work. However the scanner feature of the Pixma is to some extent supported using pixma_scan. (The printer works using TurboPrint). So I figured it should be possible to somehow merge the PNM files the scanner program produces into a multi-page document and convert this to PDF.

Google revealed that quite a few people have asked similar questions but no answers provided a complete solution. So I set about to write a bash script that would save me the hassle next time:

#!/bin/bash
dialog --title "Canon Pixma - Scan to PDF" --inputbox "Enter number of pages" 8 40 2>/tmp/dialog
if [ $? -ne 1 ] ; then
 pages=$(cat /tmp/dialog)
 for i in `seq $pages` ; do
   sudo pixma_scan -x 0 -y 0 -a -v 0 -o scan_$i.pnm
   # Exit if there was an error
   if [ $? -ne 0 ] ; then
     exit $?
   fi
 done
 # Convert PNM files to PostScript
 for i in `ls *.pnm` ; do pnmtops $i > $i.ps ; done
 if [ $pages -gt 1 ] ; then
   # Merge the PostScript files to one
   gs -q -dNOPAUSE -sDEVICE=pswrite -dBATCH -sOutputFile=scan.ps *.pnm.ps
 else
   mv scan_1.pnm.ps scan.ps
 fi
 # Create the PDF file
 ps2pdf scan.ps scan.pdf
 # Clean up
 sudo rm *.pnm
 rm *.ps
fi

The script will use the automatic document feeder, does not care about document size and is quite simple. But it does the job. Most of the tools here (except pixma_scan) should be readily available in your favourite distro.