summaryrefslogblamecommitdiff
path: root/concat_pdfs.sh
blob: 8d84d661d65761b3c96f45fd8f20420c3b54874b (plain) (tree)
































































                                                                                        
#!/bin/bash
# Copyright (C) 2017 Ryan Kavanagh <rkavanagh@cs.cmu.edu>
# Takes all pdf files (at most 4 directories deep)
# and concatenates them in a PDF, such that each
# PDF starts on an odd numbered page (useful for when
# you want to print all student submissions double-sidedly)
#
# Puts the filename in the top right corner of the page.

TMPDIR=`mktemp -d`
TEXFILE="${TMPDIR}/all.tex"

cat<<EOF>${TEXFILE}
\documentclass[twoside]{minimal}
\usepackage[letterpaper,top=0.25in,left=0.5in,right=0.5in,bottom=0.5in]{geometry}
\usepackage{pdfpages}
\usepackage{cprotect}
\makeatletter
\def\ps@headings{
\def\@oddfoot{}\def\@evenfoot{}
\def\@oddhead{}\def\@evenhead{}
}
\makeatother
\includepdfset{pages=-,pagecommand={\pagestyle{headings}}}
\pagenumbering{gobble}
\begin{document}
\cleardoublepage
EOF

c=0;
shopt -s nullglob # kill the globs that don't match
for pdf in */*.pdf */*/*.pdf */*/*/*.pdf */*/*/*/*.pdf;
do
    # We should also check that the file ${pdf} is non-empty
    # Here, sometimes students submit PDF files that gs accepts, but which
    # pdfpages doesn't like. Having gs rewrite the PDF fixes this.
    # We can also convert all of the submitted PDFs to grayscale to save
    # colour ink.
    mutool clean `pwd`"/${pdf}" `pwd`"/${pdf}" 
    gs -o "${TMPDIR}/${c}.pdf" \
	-sDEVICE=pdfwrite \
	-dPDFSETTINGS=/prepress \
	-sColorConversionStrategy=Gray \
	-dProcessColorModel=/DeviceGray \
	-dCompatibilityLevel=1.4 \
	`pwd`"/${pdf}"
    ESCAPED=`echo "${pdf}" | sed -e 's:&:\\\\&:g;s:\\$:\\\\$:g;s:%:\\\\%:g;s:_:\\\\_:g'`
    cat<<EOF>>${TEXFILE}
\makeatletter
\renewcommand{\@oddhead}{\hfill ${ESCAPED}}
\renewcommand{\@evenhead}{\hfill ${ESCAPED}}
\makeatother
\includepdf{${TMPDIR}/${c}.pdf}
\cleardoublepage
EOF
    c=`expr "${c}" + 1`
done

cat<<EOF>>${TEXFILE}
\end{document}
EOF
pdflatex ${TEXFILE}
pdflatex ${TEXFILE}

rm -fr ${TMPDIR}