Downsample images in a PDF in C#
Bring every image down to the resolution the page actually shows it at.
Short answer
Section titled “Short answer”Set MaxImageDpi on PdfOptimizerOptions. The optimizer measures each image at the largest size
it is drawn anywhere in the document, and resamples images drawn above 1.5 times the target down
to the target, with a Lanczos filter. A raw image stays lossless after resampling and a JPEG stays a
JPEG, so nothing changes format unless you also set ConvertImagesToJpeg.
var options = new PdfOptimizerOptions { MaxImageDpi = 150 };PdfOptimizationResult result = await PdfOptimizer.OptimizeFileAsync("oversampled.pdf", "downsampled.pdf", options);Console.WriteLine($"{result.Statistics.ImagesDownsampled} image(s) downsampled, {result.SavingPercent:F1}% saved");Console.WriteLine(result.Reason);The sample’s photograph, 1600 pixels drawn 3 inches wide (about 530 dpi), becomes a 150 dpi image and the file shrinks by 93.8%.
- Masks, bilevel, indexed, 16 bit, Lab, Separation and DeviceN images, JPEG 2000, JBIG2 and CCITT images, and images inside Type 3 glyphs keep their resolution.
- Each downsampled image is decoded and compared with an exact resample of the original: same
components and aspect, mean colors kept, and a minimum SSIM.
MinImageSsimraises that minimum. - Command line:
pdfnetstack optimize in.pdf out.pdf --max-dpi 150.