#!/bin/bash

#### User modifiable options

PDFTOHTMLBIN_DIR=.
RM=/bin/rm

#### End of User modifiable options


function printhelp (){
echo "pdftohtml version 0.20
Usage: pdftohtml [options] <PDF-file> [<html-file>]
  -f <int>      : first page to convert
  -l <int>      : last page to convert
  -d <dir>      : target directory (default: basename of pdf-file)
  -o <file>     : name of output file; - means stdout (default index.html)
  -q            : don't print any messages or errors
  -h            : print this usage information
  -p            : exchange .pdf links by .html
  -c            : generate complex HTML document
  -F            : don't use frames in HTML document
  -i            : ignore images
  -e <string>   : set extension for images (in the Html-file) (default png)
"
}

TARGET=index.html
FRAMES=""

while getopts f:l:d:o:qcFih OPT; do
  case "$OPT" in
  f)
    FIRST="-f $OPTARG";;
  l)
    LAST="-l $OPTARG";;
  e)
    EXT="-e $OPTARG";;
  d)
    DIR=$OPTARG;;
  o)
    if [ $OPTARG = "-" ]; then
      STDOUT=-stdout
    else
      TARGET=$OPTARG
    fi;;
  q)
    QUIET=-q;;
  F)
    FRAMES="-noframes";;
  c)
    CSS=-c;;
  i)
    IGNOREIMAGES=-i;;
  h)
   printhelp
   exit 1;;
  *)
   echo Option not supported. Please use -h for usage information.;;
esac
done

shift `expr $OPTIND - 1`
if [ $# -eq 0 ]; then
  printhelp
  exit 1
fi

PDFFILE=$1
if [ x$DIR = "x" ]; then
  DIR=./`basename $PDFFILE .pdf`
fi

# Check if target directory exists
if [ ! -x $DIR ]; then
  mkdir -p $DIR
fi

$PDFTOHTMLBIN_DIR/pdftohtml.bin $FRAMES $STDOUT $FIRST $LAST $EXT $QUIET $CSS $IGNOREIMAGES $PDFFILE $DIR/$TARGET

# Convert the images from ppm to png
images=$DIR/images.log

for ppmfile in `cat $images`; do
  file=`basename $ppmfile .ppm`
  file=`basename $file .pbm`
  pnmtopng $DIR/$ppmfile > $DIR/$file.png
  $RM $DIR/$ppmfile
  echo "pnmtopng $DIR/$ppmfile > $DIR/$file.png"
done
$RM -f $images


      
