Skip to content

Linearize a PDF for fast web view in C#

Since 1.1View as Markdown

Lay a PDF out first page first, so a browser shows it while the rest is still downloading.

Set Linearize = true in PdfOptimizerOptions and optimize the file. The output is linearized as ISO 32000-1 Annex F describes, with hint tables, and verified against the source like any other rewrite. Statistics.Linearized tells you whether it was.

recipe-linearize-pdf.cs
#:package PdfNetStack@1.2.0
using PdfNetStack;
var options = new PdfOptimizerOptions { Linearize = true };
PdfOptimizationResult result = await PdfOptimizer.OptimizeFileAsync("report.pdf", "report.web.pdf", options);
Console.WriteLine($"{result.Disposition}, linearized: {result.Statistics.Linearized}");
Console.WriteLine(result.Reason);

On the command line: pdfnetstack optimize report.pdf report.web.pdf --linearize.

  • A linearized file has no object streams, so it can be larger than the input. A linearized rewrite of a file that is not linearized yet is kept even then.
  • The other passes still run: unused resources go, content streams are compacted and duplicates merge.
  • A page tree that cannot be laid out page by page is written as usual, and the result’s reason says why.