Created
April 15, 2014 20:04
-
-
Save bkanuka/10767052 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
NAME="img2pdf" | |
USAGE="$NAME - uses LaTeX to place images full-page | |
and convert to PDF. Useful for printing. | |
$NAME [options] filename [filename] | |
options: | |
-h, --help show this help | |
-m, --margin size of margins. Default none. | |
-p, --paper-size paper size. See 'geometry' pacakge for | |
possible sizes. Default letterpaper. | |
-o, --output output file. Default [first filename].pdf | |
" | |
# Set defaults: | |
PAPER=letterpaper | |
MARGIN=0.0cm | |
## Start parsing ## | |
ARGS=$(getopt -o "hp:m:o:" -l "help,paper-size:,margin:,output:" -n "$NAME" -- "$@") | |
if [ $? -ne 0 ]; then | |
# if error in parsing args | |
echo "$USAGE" | |
exit 1 | |
fi | |
eval set -- "$ARGS" | |
while true; do | |
case "$1" in | |
-h|--help) | |
echo "$USAGE" | |
exit 0 | |
;; | |
-l|--paper-size) | |
PAPER=$2 | |
shift 2 | |
;; | |
-m|--margin) | |
MARGIN=$2 | |
shift 2 | |
;; | |
-o|--output) | |
OUTFILE=$2 | |
shift 2 | |
;; | |
--) | |
shift | |
break | |
;; | |
*) | |
echo "$USAGE" | |
exit 1 | |
;; | |
esac | |
done | |
# $1, $@, etc. are left as positional args | |
## Finished parsing ## | |
if [[ -z $1 ]]; then | |
# if no positional argument given | |
echo "No file specified. See '$NAME -h' for help." | |
exit 1 | |
fi | |
if [[ -z $OUTFILE ]]; then | |
OUTFILE=${1##*/} | |
OUTFILE=${OUTFILE%.*} | |
OUTFILE=${OUTFILE}.pdf | |
fi | |
ORIGDIR=$(pwd) | |
TEMPDIR=$(mktemp -d --tmpdir ${NAME}XXXX) | |
TEMPFILE=$(tempfile -d $TEMPDIR) | |
LOGFILE=$(tempfile -d $TEMPDIR -s .lp.log) | |
cat >> $TEMPFILE.tex <<EOF | |
\documentclass{article} | |
\pagestyle{empty} | |
\usepackage[${PAPER},margin=${MARGIN}]{geometry} | |
\usepackage{graphicx} | |
\begin{document} | |
EOF | |
for FILE in "$@"; do | |
if [[ ! -f "$FILE" ]] | |
# if $FILE is not a file | |
then | |
echo "File $FILE does not exist" | |
exit 1 | |
fi | |
cp "$FILE" "$TEMPDIR" | |
echo '\centering' >> $TEMPFILE.tex | |
echo "\includegraphics[width=\textwidth,height=\textheight,keepaspectratio]{$FILE}" >> $TEMPFILE.tex | |
done | |
echo '\end{document}' >> $TEMPFILE.tex | |
cd $TEMPDIR | |
pdflatex -halt-on-error $TEMPFILE.tex > $LOGFILE | |
if [[ $? -ne 0 ]] | |
then | |
tail $LOGFILE | |
echo " " | |
echo "LaTeX errors encountered." | |
echo "Full log written to $LOGFILE" | |
cd $ORIGDIR | |
exit 1 | |
fi | |
cd $ORIGDIR | |
cp $TEMPFILE.pdf $OUTFILE | |
rm -rf $TEMPDIR |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment