For merging PDF files one can use the PyMuPdf library for Python as shown here.
First, install PyMuPdf (it requires Python 3.6 or later):
python -m pip install --upgrade pip
python -m pip install --upgrade pymupdf
Define mergePDFs
via ExternalFunction
:
mergePDFs = ExternalFunction["Python", "import fitz
def merge_pdfs(sources, output):
result = fitz.open()
for pdf in sources:
with fitz.open(pdf) as mfile:
result.insert_pdf(mfile)
result.save(output)
return output"]
It can be used as follows:
SetDirectory[$UserDocumentsDirectory];
mergePDFs[DeleteCases[FileNames["*.pdf"], "result.pdf"], "result.pdf"]
"result.pdf"
It works extremely fast. For example, merging 505 PDF files takes only about 0.7 seconds on my laptop producing a PDF of size 11 MB.
P.S. There is a limitation due to a bug in the current (1.19.4) version of PyMuPdf: it can merge no more than 508 files at one call and cannot merge into one of the source files (fixed in version 1.19.5).
Here is an example of what we can get with this function:
plots = {Plot[{Sin[x], Sin[2 x], Sin[3 x]}, {x, 0, 2 Pi}, PlotLegends -> "Expressions"],
Plot[{Sin[x], Sin[2 x], Sin[3 x]}, {x, 0, 10}, PlotLayout -> "Column"],
Plot[{BesselJ[0, x], BesselJ[1, x], BesselJ[2, x], BesselJ[3, x], BesselJ[4, x],
BesselJ[5, x]}, {x, -20, 20}, PlotLayout -> {"Column", UpTo[4]}]};
tempFiles =
Table[Export[StringTemplate["~temp~``.pdf"][i], plots[[i]]], {i, 1, Length[plots]}];
If[mergePDFs[tempFiles, "plots.pdf"] === "plots.pdf",
DeleteFile@tempFiles; "plots.pdf", $Failed] // SystemOpen
gswin32 -dNOPAUSE -sDEVICE=pdfwrite -sOUTPUT=merged.pdf -dBATCH 1.pdf 2.pdf 3.pdf
$\endgroup$