A 600-page parts catalog that was linearized for the web loses its Fast Web View the moment a reviewer adds one sticky note in a desktop editor and saves. The file still starts with a /Linearized dictionary inside its first kilobyte, and the hint tables are untouched. But the editor appended an incremental update, so the /L entry, which records the length of the whole file, now describes a shorter file than the one sitting on the server. ISO 32000-1 Table F.1 says a mismatched /L means the file shall be treated as an ordinary PDF, its linearization information ignored unless a reader validates it first
The payoff of linearization is on the network. Everything page one needs sits at the front, so a viewer using HTTP Range requests can draw the first page after a few kilobytes, then read the hint tables to find page 380 and fetch only that range. An ordinary PDF keeps its cross-reference table at the end and scatters page objects wherever the writer emitted them. Linearizing therefore has to be the last step that rewrites a file
Why PDFium reads linearized files but cannot write them
The FPDFAvail_* availability API detects the linearization dictionary, decodes the hint tables and asks the host for exactly the byte ranges it needs, which is what the progressive download and cancellation workflow in PDFium Component is built on. The public save ABI, on the other hand, offers a plain copy save and a save with a target PDF version. Neither one reorders objects or emits a hint stream
PDFium Component fills that gap with TPdf.SaveAsLinearized, which works in two steps. It first calls the ordinary SaveAs into an intermediate store, so PDFium still owns the semantic save: edited pages, form field values and version handling go through the same path as every other save. The component then restructures that intermediate PDF according to ISO 32000-1 Annex F and writes the result to your target. That pass never has to understand an annotation or a form field. It deals only in objects, references and byte offsets
TPdf.SaveAsLinearized has a TStream overload and a file name overload. Both take the same optional Option: TSaveOption and PdfVersion: TPdfVersion parameters as SaveAs, defaulting to saNone and pvUnknown, and both return True on success. The file overload writes to a temporary file next to the target and moves it into place only after the save succeeds, so a failed run leaves the previous file untouched
var
Pdf: TPdf;
begin
Pdf := TPdf.Create(nil);
try
Pdf.FileName := 'catalog-2026.pdf';
Pdf.Active := True;
// ... edit pages, fill form fields, stamp: whatever the pipeline does ...
if not Pdf.SaveAsLinearized('catalog-2026-web.pdf', saNoIncremental, pv17) then
raise Exception.Create('Linearized save failed');
finally
Pdf.Free;
end;
end;
Save options that would undo the layout
TPdf.SaveAsLinearized validates its parameters before doing any work. saIncremental raises an error, because an incremental update appends a new revision to the end of the file, which is the sticky-note problem from the opening. A PdfVersion below pv12 is rejected too, since linearization arrived with PDF 1.2; pvUnknown keeps the version of the source document
Encrypted input needs saRemoveSecurity. The writer renumbers every object, and the standard security handler derives the key for each string and stream from the object number and generation (ISO 32000-1 §7.6.2), so the old ciphertext cannot survive a renumbering. The output of SaveAsLinearized is therefore unencrypted
Signatures are the harder call. A full rewrite changes the bytes that every signature's /ByteRange covers, so signatures in the source stop validating after SaveAsLinearized. Signing the linearized file afterward keeps the new signature intact, but a signature is itself an incremental update, and the /L mismatch from the opening comes straight back. On one file you get a valid signature or working Fast Web View. For contracts and anything a recipient might verify, keep the signature and accept full downloads; linearization pays off on catalogs, manuals and reports that nobody signs
procedure PublishForWeb(const SourceFile, TargetFile, Password: string);
var
Pdf: TPdf;
Option: TSaveOption;
begin
Pdf := TPdf.Create(nil);
try
Pdf.FileName := SourceFile;
Pdf.Password := Password; // must be set before Active
Pdf.Active := True;
// Policy check added by you: a linearizing rewrite invalidates signatures
if Pdf.SignatureCount > 0 then
raise Exception.CreateFmt('%s carries %d signature(s); publish it unlinearized',
[SourceFile, Pdf.SignatureCount]);
if Pdf.SecurityHandlerRevision > 0 then
Option := saRemoveSecurity // the web copy is written without encryption
else
Option := saNoIncremental;
if not Pdf.SaveAsLinearized(TargetFile, Option, pvUnknown) then
raise Exception.CreateFmt('Linearized save of %s failed', [SourceFile]);
finally
Pdf.Free;
end;
end;
How the writer groups objects for Fast Web View
The writer parses the current revision, whether its cross-reference data is a classic table, a hybrid file or a cross-reference stream, and unpacks every object that lives inside an object stream into a standalone object. It then builds a reference graph and sorts objects into the five groups Annex F lays out: document-level objects needed to open the file, the first page, objects private to one later page, objects shared by several later pages, and everything else
The document-level group starts with the catalog and pulls in whatever is reachable from its /ViewerPreferences, /Threads, /OpenAction and /AcroForm entries, plus /Outlines when /PageMode is /UseOutlines. The first-page group begins with the page object, followed by its content streams and then the fonts, images and other resources it reaches. Later pages are sorted by a reference count: an object reached from exactly one page joins that page's group, and an object reached from two or more pages goes to the shared group
The trap in that graph walk is /Parent. Every page dictionary points back up to its page tree node, and a naive traversal follows that link, then walks down through /Kids into every sibling page and its content streams. One step up, and the first-page group contains the whole document. The file is still technically linearized and useless to a range-first viewer. The walk in TPdf.SaveAsLinearized skips the /Parent link of the page being collected and never enters page tree nodes or other pages, so a page's group holds only what that page draws. The page tree nodes themselves land in the final group
Object streams and cross-reference streams in the input come out as ordinary generation 0 indirect objects, every reference is rewritten to the new numbers, and the output uses classic cross-reference sections. That costs bytes, but every object stays addressable by a plain byte offset, which is what the hint tables describe. TPdf.SaveAsObjectStream writes the opposite layout and requires PDF 1.5 or newer. For files served over HTTP, use SaveAsLinearized; for archives opened only from a local disk, SaveAsObjectStream gives the smaller file and nobody would read the hints anyway
Object numbering follows the layout. Later pages, shared objects and the remainder take the low numbers from 1 upward, indexed by the main cross-reference section at the end; the linearization dictionary, document-level objects, hint stream and first-page objects take the numbers above them, indexed by the first-page section near the front
What the linearization dictionary records
The linearization dictionary is the first object in the file and has to sit within its first 1024 bytes, where a viewer looks before reading anything else. TPdf.SaveAsLinearized writes the six entries of Table F.1 that a viewer needs up front: /L the file length, /H the offset and length of the primary hint stream, /O the object number of the first page, /E the offset of the end of the first page, /N the page count, and /T the position of the first entry in the main cross-reference table
Every one of those values depends on the final layout, and the dictionary sits in front of that layout. With natural-width numbers the values feed back into themselves: a file length that grows from 999999 to 1000000 adds a byte to the dictionary, which shifts every later offset, which can widen yet another number. The writer cuts the loop twice. Each value is written as a ten-digit integer with leading zeros, which the integer syntax of §7.3.3 permits, and the whole object is padded to a fixed 320 bytes. Once every other part has its final offset, the dictionary is rebuilt at the same width, and the writer checks that the finished output is exactly /L bytes long
/T is where strict checkers and forgiving viewers most often part ways. Table F.1 defines it as the offset of the white-space character preceding the first entry of the main cross-reference table, which is the end of the 0 N subsection header line. Pointing it at the xref keyword instead is a common slip that many viewers tolerate and strict linearization checkers report
The first-page trailer carries /Root, the source's /Info and /ID when present, and a fixed-width /Prev pointing at the main cross-reference section. The main trailer's startxref points back at the first-page section, so a reader that ignores linearization and starts from the end still finds every object
Why do hint table offsets ignore the hint stream?
Hint table offsets in a linearized PDF are read as if the hint stream did not exist in the file. That keeps the hint stream's own size out of the numbers it contains. Annex F also lets the primary hint stream go either before or after the first-page section; TPdf.SaveAsLinearized places it before, directly after the document-level objects. Any real offset that lies after the hint stream has to be reduced before it goes into the page offset or shared object hint table
Reduced by how much? The tempting answer is the length of the stream data. The correct answer is the length of the entire hint indirect object, from N 0 obj through the stream dictionary, the stream and endstream keywords and the closing endobj. Subtract only the data length and every later offset is off by a few dozen bytes. Page one still renders, because a viewer finds the first-page objects through the first-page cross-reference section rather than the hint tables, so the mistake survives a quick visual check. It shows up only when a viewer jumps to a later page and requests a range that starts in the middle of the wrong object
Both tables are bit-packed with the most significant bit first, as Annex F specifies, and the writer starts each per-page item array on a byte boundary. The stream dictionary's /S entry gives the offset of the shared object table inside the decoded data. The shared object table lists the first-page objects before the shared group, with one object per entry and every MD5 signature flag cleared. The stream gets /Filter /FlateDecode only when compression actually makes it smaller than the raw table bytes
Checking a linearized PDF from Delphi
The quickest check asks PDFium itself. TPdf.InspectAvailability is a class function that runs the availability API against a stream without loading the document, and its Linearization field reports plnLinearized, plnNotLinearized or plnUnknown, the last meaning PDFium could not decide. Pair it with an /L check against the real file size, which catches the appended-update case from the opening
uses
System.SysUtils, System.Classes, System.Math, System.StrUtils, PDFium;
// Your own helper, not part of PDFium Component: PDFium must call the file
// linearized, and the declared /L must equal the bytes actually on disk
function IsFastWebView(const FileName: string): Boolean;
var
Stream: TFileStream;
Head: AnsiString;
Text, Digits: string;
P: Integer;
begin
Result := False;
Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
try
if TPdf.InspectAvailability(Stream).Linearization <> plnLinearized then
Exit;
// Annex F puts the linearization dictionary inside the first 1024 bytes
SetLength(Head, Min(Stream.Size, 1024));
Stream.Position := 0;
if Length(Head) > 0 then
Stream.ReadBuffer(Head[1], Length(Head));
Text := string(Head);
P := Pos('/Linearized', Text);
if P = 0 then
Exit;
P := PosEx('/L ', Text, P + Length('/Linearized'));
if P = 0 then
Exit;
Inc(P, 3);
Digits := '';
while (P <= Length(Text)) and CharInSet(Text[P], ['0'..'9']) do
begin
Digits := Digits + Text[P];
Inc(P);
end;
Result := (Digits <> '') and (StrToInt64(Digits) = Stream.Size);
finally
Stream.Free;
end;
end;
The /L scan expects a space after the key, as SaveAsLinearized writes it; other producers may need a looser parser. Neither check proves the hint tables are right. For that, serve the file through a range-limited transport and open a late page with TPdfProgressiveDocument, as the guide to streaming large PDFs on demand with PDFium VCL does. If the late page renders after only a small fraction of the file has arrived, the hint offsets are doing their job
Linearization matters only when the server honors HTTP Range requests, and behind a proxy that strips Accept-Ranges a linearized file downloads exactly like any other. The linearizing pass in SaveAsLinearized handles intermediate saves below 2 GB, and its reserved slot holds offsets up to ten digits, the same ceiling that classic cross-reference entries have
TPdf.SaveAsLinearized, TPdf.InspectAvailability and TPdfProgressiveDocument come in the same package, so the writer and the reader that checks its output stay in step. The PDFium Component product page covers the full wrapper for Delphi, C++Builder and Lazarus