Convert PNMs to DjVu

I’ve decided to scan some notebooks. After researching a bit, I’ve decided to use DjVu (instead of PDF which I normally use). I’ve chose to use DjVu because it offered great quality with very good compression rate (~26KB per page) in lineart (black and white).

While XSane can natively save a multipage project into PDF it can’t do so for DjVu. So, the solution is to use the PNMs generated by XSane and convert them using the command line tools offered by DjVuLibre to bundle them together to a DjVu file. As you can guess doing this manually is pretty hard work. To make this task easier I’ve written a small bash script to automate the process.

# pnm2djvu 
#(C) 2008 Guy Rutenberg
#pnm2djvu - A small script that takes a directory with PNMs and converts them to 
#monochrome (bitonal) djvu file with the PNMs ordered alphabetically.

if [ -z "$1" ]; then
	echo "Directory of PNMs reguired"
if [ -z "$2" ]; then
	echo "filename for output required"

pnms=`ls "$1/" | grep ".pnm$"`
for i in ${pnms}; do
	echo "Processing page number ${pagenum}"
	cjb2 "$1/$i"  "page$i.djvu"
	if [ -f "$2" ]; then
		djvm -i "$2" "page$i.djvu"
		djvm -c "$2" "page$i.djvu"
	rm "page$i.djvu"
	pagenum=`expr $pagenum + 1`

Using the script is pretty simple. Pass as the first argument a path to a directory holding the PNMs (it can also be “.”), and the name of the output DjVu file. If the file already exist the script will append all the PNMs to it, otherwise it will just create a new one.

I’ve released this script following the “release early” practice in the open-source community. This script is far from perfect and I plan t improve when I’ve some more time. Currently this script has some major drawbacks such as fixed DPI (300) and it only support bitonal (black and white) compression. As I wrote above, I plan to address this issues and make the script more flexible in the future.

Despite its drawbacks I hope you will still find this script useful. If you have any questions or suggestions please comment.

2 thoughts on “Convert PNMs to DjVu”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.