Batch compress PDFs from the command line
Optimize a whole folder of PDFs in one command, with a report of what each file gained.
Short answer
Section titled “Short answer”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.
dotnet tool install -g PdfNetStack.Tool
pdfnetstack batch ./incoming ./optimized --report report.csvpdfnetstack batch ./incoming # measure only, writes nothingpdfnetstack 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.
The same in C#
Section titled “The same in C#”#:package PdfNetStack@1.2.0using 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.
Related
Section titled “Related”- Command line: every command and option
- Compress PDF
- API: PdfOptimizer