Inspired by touhami's brilliantly simple approach, I used the same technique but with Python.
import os, fnmatch, subprocess, getopt, sys
def combinePdfs(inputPdfsDir, outputFileName):
removeOldCombinedFigure(inputPdfsDir + outputFileName + '.pdf')
latexText = buildLatexText(inputPdfsDir)
tempFilePath = inputPdfsDir + outputFileName + '.tex'
saveTexFile(tempFilePath, latexText)
callPdfLatex(tempFilePath)
deleteGenereatedFiles(inputPdfsDir + outputFileName)
def removeOldCombinedFigure(oldCombinedPath):
try:
os.remove(oldCombinedPath)
except OSError:
pass
def buildLatexText(inputPdfsDir):
graphics = fnmatch.filter(os.listdir(inputPdfsDir), "*.pdf")
graphicHeight = 1.0 / len(graphics)
latexText = """
\documentclass{article}
\usepackage{graphicx}
\usepackage[margin=0.0in]{geometry}
\\begin{document}
\\begin{figure}
\\centering"""
for g in graphics:
latexText += "\n\includegraphics[height="
latexText += str(graphicHeight)
latexText += "\\textheight,width=\\textwidth,keepaspectratio]{"
latexText += g
latexText += "}"
latexText += "\n\end{figure}"
latexText += "\n\end{document}"
return latexText
def saveTexFile(texFilePath, latexText):
tempFile = file(texFilePath, 'w')
tempFile.write(latexText)
tempFile.close()
def callPdfLatex(tempFilePath):
inputPdfsDir = os.path.dirname(tempFilePath)
windowsTempFilePath = tempFilePath.replace("/", "\\")
outDirCommand = "-output-directory=" + inputPdfsDir
args = ["C:\\Program Files (x86)\\MiKTeX\\miktex\\bin\\pdflatex.exe", outDirCommand, windowsTempFilePath]
subprocess.call(args, shell = True)
def deleteGenereatedFiles(generatedFileNameNoExt):
os.remove(generatedFileNameNoExt + '.aux')
os.remove(generatedFileNameNoExt + '.log')
os.remove(generatedFileNameNoExt + '.tex')
def usage():
print('combine_pdfs.py -i C:\\dir_with_pdfs -o combinedPdf')
def main(argv):
opts, args = getopt.getopt(argv, "h:i:o:")
inputDir = None
outputFile = None
for opt, arg in opts:
print opt
if opt in ("-h", "--help"):
usage()
sys.exit(2)
elif opt in ("-i", "--input_dir"):
inputDir = arg
if not inputDir.endswith('\\'):
inputDir += '\\'
elif opt in ("-o", "--output_file"):
outputFile = arg
else:
usage()
sys.exit(2)
combinePdfs(inputDir, outputFile)
if __name__ == "__main__":
argv = sys.argv[1:]
main(argv)
Call from the command line like this:
python .\combine_pdfs.py -i C:\Users\yourname\Desktop\dir_with_pdfs -o combined