将多个可变 PDF 合并到一页上

将多个可变 PDF 合并到一页上

我文件夹中有 n 个 PDF。每个 PDF 只包含一个小图。我想将所有这些合并到一页上,一个接一个。我希望能够指定 PDF 所在的目录并让 LaTeX 组装它们。如果我可以从命令行调用它,那就更好了,这样我就不必打开编辑器了。我的情况是这样的这个(至少提问者的伪代码正是我所想的)但我对答案的理解不足以使其适用于组合 PDF。

如果这样更简单的话,我可以传入确切的 PDF 文件路径作为参数,而不仅仅是目录。这两种方法我都同意。

谢谢。

答案1

批量解决方案将此.bat文件保存在同一目录中

@echo off 
setlocal EnableDelayedExpansion

(
echo \documentclass{article}
echo \usepackage{graphicx}
echo \begin{document} 
)> combine.tex
for /r %%a in (*.pdf) do (
set mtfile=%%a
set mtfile=!mtfile:%~dp0=!
set mtfile=!mtfile:\=/!
set mtfile="!mtfile:.=".!
echo \includegraphics{!mtfile!}>> combine.tex
echo.>> combine.tex
)
echo \end{document}>> combine.tex

rem could need to renove rem from next line and edit it to point pdflatex directory
rem set path=C:\programm...\miktex\bin;%path%
pdflatex combine.tex

通过运行此文件,您将创建combine.tex并编译它。

答案2

受到 touhami 的巧妙而简单的方法的启发,我使用了相同的技术,但使用的是 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)

从命令行调用如下:

python .\combine_pdfs.py -i C:\Users\yourname\Desktop\dir_with_pdfs -o combined

相关内容