Reduce PDF size for email in C#
Shrink a PDF further than lossless compression allows, by lowering the resolution and quality of its photographs.
Short answer
Section titled “Short answer”Set the lossy image options on PdfOptimizerOptions and optimize as usual. MaxImageDpi
downsamples images drawn sharper than the page needs, ConvertImagesToJpeg stores raw
photographs as JPEG, and JpegQuality sets the quality of new JPEGs and requantizes existing ones.
Text, vectors, fonts, line art and screenshots are untouched, and the output is still verified
against the source.
var options = new PdfOptimizerOptions{ MaxImageDpi = 150, // no image sharper than the page needs ConvertImagesToJpeg = true, // photographs stored raw become JPEG JpegQuality = 80, // new JPEGs, and existing JPEGs requantized down to it};PdfOptimizationResult result = await PdfOptimizer.OptimizeFileAsync("brochure.pdf", "brochure-email.pdf", options);Console.WriteLine($"{result.Disposition}: {result.OriginalBytes:N0} to {result.OutputBytes:N0} bytes, {result.SavingPercent:F1}% saved");Console.WriteLine(result.Reason);On the sample brochure, a lossless 1600 pixel photograph drawn about 6 inches wide, this takes the file from 2,452,280 to 62,318 bytes.
Variations
Section titled “Variations”- Add
MinImageSsim = 0.95to keep any image whose change would be visible; that image then keeps its own encoding, or stays raw after downsampling. - Version 1.0 on NuGet has
JpegQualityonly: it requantizes existing JPEG images and does nothing else lossy. - From the command line:
pdfnetstack optimize in.pdf out.pdf --max-dpi 150 --to-jpeg --jpeg-quality 80.
Related
Section titled “Related”- Compress PDF: every lossy option and what the proof checks
- Downsample images in a PDF
- Command line
- API: PdfOptimizerOptions