Skip to content

Batch compress PDFs from the command line

Since 1.0View as Markdown

Optimize a whole folder of PDFs in one command, with a report of what each file gained.

Install the pdfnetstack tool and run batch with an input and an output folder. Each file is optimized losslessly and verified, and --report writes one CSV row per document. Without an output folder, batch only measures and writes nothing.

Terminal window
dotnet tool install -g PdfNetStack.Tool
pdfnetstack batch ./incoming ./optimized --report report.csv
pdfnetstack batch ./incoming # measure only, writes nothing
pdfnetstack batch ./incoming ./optimized --jpeg-quality 60 --jobs 4

--jobs sets how many documents run in parallel, --threads the threads per document. The tool needs the .NET 8 or later runtime.

recipe-batch-compress-pdf-cli.cs
#:package PdfNetStack@1.2.0
using PdfNetStack;
Directory.CreateDirectory("optimized");
foreach (string path in Directory.GetFiles(".", "*.pdf"))
{
string output = Path.Combine("optimized", Path.GetFileName(path));
PdfOptimizationResult result = await PdfOptimizer.OptimizeFileAsync(path, output);
Console.WriteLine($"{Path.GetFileName(path)}: {result.Disposition}, {result.SavingPercent:F1}% saved");
}

Files that are already well compressed come back as OriginalRetained: the rewrite saved less than MinSavingPercent (1% by default), so the original bytes were kept.