Some time ago I had a need to export PDFs with multiple pages each containing only one plot occupying the whole page. I wasn't able to find a way to do this using Mathematica, and was forced to export them one-by-one as PDF, and then to merge produced PDFs into one file using pdfunite
from Poppler utils:
gf = Table[Plot[Sin[a x], {x, -10, 10}], {a, 1, 10}]
tempFiles = Table[Export[ToString@StringForm["``.pdf", i], gf[[i]]], {i, 1, Length[gf]}]
command = StringJoin["pdfunite ",
Table["\"" <> tempFiles[[i]] <> "\" ", {i, 1, Length[tempFiles]}], "\"Result.pdf\""];
If[Run[command] == 0, DeleteFile @ tempFiles; SystemOpen["Result.pdf"]];
Related:
Also, it is possible to use Poppler installed on Linux running under Windows Subsystem for Linux as I show here.
As an alternative, 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 what we get with the above methods:
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
