Skip to content

Reduce PDF size for email in C#

Since 1.1View as Markdown

Shrink a PDF further than lossless compression allows, by lowering the resolution and quality of its photographs.

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.

  • Add MinImageSsim = 0.95 to 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 JpegQuality only: 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.