#!/bin/bash # # Script to produce rasterised LaTeX formulae # Dependencies: pdflatex, ghostscript, imagemagick # Brad Atcheson # 7 Nov 2008 USAGE="Usage: `basename "$0"` '' output.png Produces rasterised LaTeX formulae Remember to enclose the latex commands in single quotes (eg 'x^0') The displaymath environment is assumed Options: [-r resolution in DPI (default:300)] [-h help]" # print usage info to stderr if [ "$#" == "0" ]; then echo "$USAGE" 1>&2 exit 1 fi # parse cmdline dpi=300 while getopts ":r:h" options do case $options in r ) dpi=$OPTARG;; h ) echo "$USAGE" 1>&2; exit 1;; * ) echo "Unrecognised argument: $options" 1>&2; exit 1;; esac done shift $(($OPTIND - 1)) # build the temp tex file # keep it as small as possible to avoid wasting time/mem rasterising # the blank space on the page. Hopefully 6"x3" will be large enough for # most inputs. If not, just make the page a little bigger here file="temp.$RANDOM" pagewidth="6in" pageheight="3in" echo "\documentclass{article}" >$file.tex echo "\pagestyle{empty}" >>$file.tex echo "\pdfpagewidth=$pagewidth" >>$file.tex echo "\pdfpageheight=$pageheight" >>$file.tex echo "\setlength{\voffset}{-1in}" >>$file.tex echo "\setlength{\topmargin}{0pt}" >>$file.tex echo "\setlength{\headheight}{0pt}" >>$file.tex echo "\setlength{\headsep}{0pt}" >>$file.tex echo "\setlength{\hoffset}{-1in}" >>$file.tex echo "\setlength{\marginparwidth}{0pt}" >>$file.tex echo "\setlength{\oddsidemargin}{0pt}" >>$file.tex echo "\setlength{\marginparsep}{0pt}" >>$file.tex echo "\setlength{\footskip}{0pt}" >>$file.tex echo "\setlength{\textwidth}{$pagewidth}" >>$file.tex echo "\setlength{\textheight}{$pageheight}" >>$file.tex echo "\begin{document}" >>$file.tex echo "\begin{displaymath}" >>$file.tex echo "$1" >>$file.tex echo "\end{displaymath}" >>$file.tex echo "\end{document}" >>$file.tex # produce a fullpage pdf pdflatex -halt-on-error $file.tex >/dev/null if [ ! -f $file.pdf ]; then echo "Error running pdflatex. See $file.log for details" 1>&2 rm $file.aux exit 2 fi rm $file.{aux,log} # get the bounding box box=`gs -q -dBATCH -dNOPAUSE -sDEVICE=bbox $file.pdf 2>&1 | grep Hi` blx=`echo $box | cut -d " " -f 2` bly=`echo $box | cut -d " " -f 3` trx=`echo $box | cut -d " " -f 4` try=`echo $box | cut -d " " -f 5` width=`echo "$trx-$blx" | bc -l` height=`echo "$try-$bly" | bc -l` # scale and round coordinates (depends on resolution) # and add a one-pixel border width=`printf "%.0f" $(echo "$width / 72 * $dpi + 2" | bc -l)` height=`printf "%.0f" $(echo "$height / 72 * $dpi + 2" | bc -l)` originx=`printf "%.0f" $(echo "$blx / 72 * $dpi - 1" | bc -l)` originy=`printf "%.0f" $(echo "$bly / 72 * $dpi - 1" | bc -l)` # convert cropped region to bitmap, flipping coordinate system # because pdf uses bottom-left as origin convert -density $dpi $file.pdf \ -gravity SouthWest \ -crop ${width}x${height}+${originx}+${originy} \ +repage \ "$2" # cleanup rm $file.{pdf,tex}