Docs / Guides

Optimizing file size

SoftZenPdf.Optimizer makes PDFs smaller with fine-grained control: you choose each optimization, and every object is replaced only when its new version is smaller. Scanned documents, merged reports and files full of photographs often shrink to a fraction of their size. It can also linearize files for fast web view.

Installing

Terminal
dotnet add package SoftZenPdf.Optimizer

It brings in SoftZenPdf and needs no native libraries.

Optimizing a file

Program.cs
using SoftZenPdf;
using SoftZenPdf.Optimizer;

var optimizer = new PdfOptimizer();
optimizer.AddOptimizationHandler(new CompressionOptimizer());                     // streams and object streams
optimizer.AddOptimizationHandler(new DuplicateResourceOptimizer());               // one copy of repeated fonts and images
optimizer.AddOptimizationHandler(new ImageResolutionOptimizer(150));              // downsample images above 225 ppi
optimizer.AddOptimizationHandler(new ImageQualityOptimizer
{
    JpegProcessor = new JpegCompressor(0.75f),
    BitmapProcessor = new BitmapCompressor()
});

var result = optimizer.Optimize("merged.pdf", "merged-optimized.pdf");
Console.WriteLine($"{result.OriginalSize:N0} → {result.OptimizedSize:N0} bytes, {result.Reduction:P0} smaller");

Each OptimizationHandler does one kind of optimization, and handlers run in the order they are added. The output is a complete new file: unused objects and earlier revisions are dropped, and nothing in the input is changed.

The handlers

HandlerWhat it does
CompressionOptimizerRecompresses page content, fonts, forms and other streams with Deflate at the strongest setting, strips filters such as ASCII85 in front of image data, and packs objects into compressed object streams.
FontDuplicationOptimizerKeeps one copy of fonts embedded more than once, for example after merging documents.
DuplicateResourceOptimizerKeeps one copy of any repeated resource: images, forms, fonts, colour spaces, graphics states and more.
ImageQualityOptimizerRecompresses images, with one processor for JPEGs and one for bitmaps.
ImageResolutionOptimizerDownsamples images that have more pixels than the size they are drawn at needs.
ColorSpaceConverterConverts CMYK images to RGB.

A good order is: resolution, then colour conversion, then image quality, with compression and de-duplication anywhere.

Compression and object streams

Program.cs
using SoftZenPdf;
using SoftZenPdf.Optimizer;

var optimizer = new PdfOptimizer();
optimizer.AddOptimizationHandler(new CompressionOptimizer
{
    Level = System.IO.Compression.CompressionLevel.SmallestSize,
    UseObjectStreams = true,      // PDF 1.5 object and cross-reference streams
});
optimizer.Optimize("report.pdf", "report-compressed.pdf");

Object streams usually save the most on text-heavy and form-heavy files. Files that declare PDF/A-1 conformance keep a classic cross-reference table, since PDF/A-1 does not allow object streams. XMP metadata streams are left as they are, so tools that scan files for metadata can still read them.

Duplicate fonts and resources

Program.cs
using SoftZenPdf;
using SoftZenPdf.Optimizer;

var optimizer = new PdfOptimizer();
optimizer.AddOptimizationHandler(new FontDuplicationOptimizer());     // only fonts
optimizer.AddOptimizationHandler(new DuplicateResourceOptimizer());   // images, forms, colour spaces and the rest
var result = optimizer.Optimize("merged.pdf", "merged-deduplicated.pdf");

foreach (var handler in result.Handlers)
    Console.WriteLine($"{handler.Handler}: {handler.ObjectsRemoved} duplicates removed, {handler.SavedBytes:N0} bytes saved");

Objects are compared by content, streams by their decoded data, so the same image or font compressed differently still counts as a duplicate. Different subsets of the same font are not merged. Pages, annotations, form fields, bookmarks and structure elements are never merged, even when identical.

Image quality

Program.cs
using SoftZenPdf;
using SoftZenPdf.Optimizer;

var optimizer = new PdfOptimizer();
optimizer.AddOptimizationHandler(new ImageQualityOptimizer
{
    JpegProcessor = new JpegCompressor(0.6f) { SubsampleChroma = true },
    BitmapProcessor = new BitmapToJpegConverter(0.75f),   // photos become JPEG; logos and diagrams stay lossless
});
var result = optimizer.Optimize("report.pdf", "report-images.pdf");

foreach (var image in result.Images)
    Console.WriteLine($"{image.Width}x{image.Height} {image.Format} → {image.OptimizedFormat}: {image.Outcome} ({image.Reason})");
  • JpegCompressor(quality): recompresses JPEGs at a quality from just above 0 to 1 (0.75 is a good general setting). JPEGs already saved at that quality or lower are left alone, and the colour space, /Decode array and masks are kept.
  • BitmapCompressor: lossless, so every pixel keeps its exact colour. RGB images with only grey pixels become greyscale, images with few colours become a palette, sample values are stored with fewer bits where they fit exactly, and PNG predictors are used when smaller.
  • BitmapToJpegConverter(quality): turns photographs (8-bit images with more than 256 colours) into JPEG, and compresses logos, diagrams and screenshots losslessly instead, since JPEG would blur them.

result.Images lists every image a handler looked at, with its size before and after and what happened: optimized, kept because the result was not smaller, skipped or failed, and why.

Downsampling to a resolution

Program.cs
using SoftZenPdf;
using SoftZenPdf.Optimizer;

var optimizer = new PdfOptimizer();
optimizer.AddOptimizationHandler(new ImageResolutionOptimizer(150)
{
    Threshold = 1.5,       // only images above 225 ppi
    JpegQuality = 0.75f,   // the same quality as the JpegCompressor below, so JPEGs are encoded only once
});
optimizer.AddOptimizationHandler(new ImageQualityOptimizer { JpegProcessor = new JpegCompressor(0.75f) });
optimizer.Optimize("report.pdf", "report-150ppi.pdf");
  • How large each image is drawn is measured from the page content, including form XObjects. An image drawn more than once is sized for its largest use.
  • Images also used where their size cannot be measured (in an annotation, a pattern or a glyph) are left alone.
  • 150 ppi suits reading on screen, 300 ppi printing. With the default Threshold of 1.5, only images above 1.5 times the target are reduced.
  • Reduced JPEGs are saved as JPEG; set JpegQuality to the same quality as your JpegCompressor, as above, so each JPEG is encoded once rather than twice.
  • Images with 1, 2, 4 or 16 bits per sample, palette images, stencil masks and images with colour-key masks are not resized.

CMYK to RGB

Program.cs
using SoftZenPdf;
using SoftZenPdf.Optimizer;

var optimizer = new PdfOptimizer();
optimizer.AddOptimizationHandler(new ColorSpaceConverter { Formula = CmykToRgbFormula.Multiply });
optimizer.AddOptimizationHandler(new ImageQualityOptimizer { JpegProcessor = new JpegCompressor(0.75f) });
optimizer.Optimize("report.pdf", "report-rgb.pdf");

RGB takes three samples per pixel instead of four and lets JPEGs store colour at lower resolution, so CMYK photographs often shrink by a third. JPEGs stay JPEG at their quality, other images stay lossless, and palette images only have their palette converted.

The conversion uses a device formula, not the colour profile a print workflow would use, so photographs can look more saturated than in a colour-managed viewer. CmykToRgbFormula.Multiply (the default) is the closer match; Iso32000 is the formula of ISO 32000-1 §10.3.5. Documents with a CMYK output intent (PDF/A or PDF/X for print) are left alone. Use it for files meant for screens, not for files going to a printer.

Fast web view

Program.cs
using SoftZenPdf;
using SoftZenPdf.Optimizer;

var optimizer = new PdfOptimizer { Linearize = true };
optimizer.AddOptimizationHandler(new CompressionOptimizer());
optimizer.Optimize("report.pdf", "report-web.pdf");   // the first page shows before the rest has downloaded

Linearize writes the file in the linearized layout of ISO 32000-1 Annex F: the first page and everything it needs come first, followed by each other page in order, with hint tables that tell a viewer where each page starts. A browser or viewer that loads the file over the web can show the first page, and jump to any other, without waiting for the whole download. Viewers report such files as having fast web view.

  • It works with any handlers, or none, and keeps encryption and bookmarks; when bookmarks open with the document, they come with the first page.
  • Linearized files use a classic cross-reference table, so object streams are not used and a warning says so. The file can be a little larger than without Linearize.
  • Because you asked for the layout, the output is written even when it is not smaller; an input that is already linearized is still kept when the result would not be smaller.

Checking the result

Program.cs
using SoftZenPdf;
using SoftZenPdf.Optimizer;

var optimizer = new PdfOptimizer { KeepOriginalIfNotSmaller = true };
optimizer.AddOptimizationHandler(new CompressionOptimizer());
OptimizationResult result = optimizer.Optimize("report.pdf", "report-checked.pdf");

if (result.KeptOriginal) Console.WriteLine("Already optimal: the input was written unchanged.");
else Console.WriteLine($"Saved {result.SavedBytes:N0} bytes ({result.Reduction:P1}).");
foreach (var warning in result.Warnings) Console.WriteLine(warning);

With KeepOriginalIfNotSmaller (on by default), an input that is already as small as it gets is written unchanged. Warnings notes anything worth knowing, such as a damaged input that was repaired, or digital signatures that no longer validate because the file was rewritten.

Encrypted files

Program.cs
using SoftZenPdf;
using SoftZenPdf.Optimizer;

var optimizer = new PdfOptimizer();
optimizer.AddOptimizationHandler(new CompressionOptimizer());
optimizer.Optimize("protected.pdf", "protected-optimized.pdf", password: "owner");   // keeps the passwords and permissions

The output keeps the input's encryption, passwords and permissions. Optimizing needs permission to change the file's content, so open it with the owner password when the permissions do not allow that.

Limits

  • JBIG2 and JPEG 2000 images are not recompressed or resized.
  • Inline images and images in annotations, patterns or glyphs are not resized.
  • Colours in page content (such as text drawn in CMYK) are not converted.

SoftZenPdf.Optimizer is covered by your SoftZenPdf license. Until a key is set (see Licensing), optimized files carry the evaluation mark on every page and are always written optimized.

API: PdfOptimizer (with Linearize), OptimizationResult, ImageQualityOptimizer, ImageResolutionOptimizer, ColorSpaceConverter.