Technical Article

What a PDF Contains, Page by Page, as JSON

An inventory row that reads characters: 0 looks like a failure until you see the page. It is a scan. One picture runs from margin to margin, every word on it is pixels rather than text, and the count is right. With PDFium Component in Delphi, the inventory records document metadata and attachment names once, then adds per-page counts of text, image objects, annotations, and links. The result is saved as JSON. A second program reads that file to compare pages or route the document, without opening a viewer or rendering a bitmap.

What does each count measure?

A publisher might ask which pages contain selectable text, an import service might need the names of embedded files, and a reviewer might want to know where links and comments appear. Those answers live in different parts of a PDF. Even on one visible page, a sticky note and a line of text are recorded in different places, so a single total called "PDF objects" would tell nobody what changed after a file was reprocessed.

Report fieldWhat it measuresScope
charactersText that can be selected and copied on the page; 0 for a scan with no text layerPage
topLevelImagesPictures placed directly on the page; a picture inside a Form XObject is not countedPage
annotationsEverything in the page's comment and form layer: notes, highlights, links, form fieldsPage
linkAnnotationsClickable regions stored on the page as link annotationsPage
attachmentNamesFile names in the document's attachment list, the panel a viewer shows for embedded filesDocument
topLevelBookmarksEntries at the top of the bookmark tree; the levels below them are not countedDocument

Each field has a blind spot, and the two link fields leave out a third kind of link:

  • Scans are the classic case for characters: a page covered with printed words reports 0, and it reports a positive count once OCR has added a text layer. The count is not a string length. A page that stacks Invoice 1042 over Total due 90 holds 24 characters, and CharacterCount reports 26, because the line break between the two lines is stored as two generated entries. CharacterGenerated[Index] tells those entries from real glyphs.
  • Images count only as direct page objects. A scan placed on the page reports topLevelImages: 1. Wrapped in a Form XObject, the scan is still visible and reports 0, because the page now holds one object of type otForm instead of an image. The field is deliberately that narrow, so its meaning survives from one report to the next. An export that must reach nested images needs a path with that coverage; the walkthrough on extracting images from PDFs works from BitmapCount and Bitmap[Index] and spells out what that count includes.
  • Every kind of annotation counts toward annotations: highlights, notes, links, and the widgets of a form alike. One link and one file-attachment annotation on a page give annotations: 2 and linkAnnotations: 1. The two should never be summed. Each link annotation is part of both numbers, so the sum overstates the annotations on any page that carries links.
  • Addresses printed as text are a third category. LinkAnnotationCount[PageNumber] walks the annotations of a page. WebLinkCount[PageNumber] scans the text layer instead and finds addresses such as https://example.com, whether or not a link was placed around them. WebLink[PageNumber, Index] returns one of them in Url, together with the character range and the rectangles it covers. Body text that prints an address without a link annotation gives linkAnnotations: 0 and a WebLinkCount of 1. A link whose target never appears in the text gives the reverse, 1 and 0. I would not merge the two into one field, because the page that prints an address without a link is the one a reviewer needs to see.
  • attachmentNames belongs to the document and lists the files in its attachment list, such as the XML that rides along inside an invoice PDF. A file attached through a file-attachment annotation is a different thing: it counts toward annotations on its page and is absent from this list.
  • topLevelBookmarks counts only the entries directly below the outline root. An outline with Chapter 1, which contains Section 1.1, and Chapter 2 reports 2 rather than 3, and the walkthrough that reads bookmarks and their destination pages walks the levels below the top.

Page counts follow the current page

CharacterCount, ObjectCount, and AnnotationCount describe the current page, and the current page is whatever PageNumber holds. A loop that reads them without assigning PageNumber still produces tidy JSON, but every row repeats the counts of the page that was current when the loop began. The helper below assigns PageNumber first. It also rejects 0, a legal value for the component that unloads the current page, and any number above PageCount. Page numbers start at 1. Object indexes start at 0, so the loop over ObjectType runs from 0 to ObjectCount - 1. The routines in this article need System.SysUtils, System.JSON, System.IOUtils, and PDFium in the uses clause.

function InventoryPage(Pdf: TPdf; PageNumber: Integer): TJSONObject;
var
  ObjectIndex, ImageCount: Integer;
begin
  if (PageNumber < 1) or (PageNumber > Pdf.PageCount) then
    raise EArgumentOutOfRangeException.Create('Page number out of range');

  Pdf.PageNumber := PageNumber;
  ImageCount := 0;
  for ObjectIndex := 0 to Pdf.ObjectCount - 1 do
    if Pdf.ObjectType[ObjectIndex] = otImage then
      Inc(ImageCount);

  Result := TJSONObject.Create;
  try
    Result.AddPair('page', TJSONNumber.Create(PageNumber));
    Result.AddPair('characters', TJSONNumber.Create(Pdf.CharacterCount));
    Result.AddPair('topLevelImages', TJSONNumber.Create(ImageCount));
    Result.AddPair('annotations', TJSONNumber.Create(Pdf.AnnotationCount));
    Result.AddPair('linkAnnotations',
      TJSONNumber.Create(Pdf.LinkAnnotationCount[PageNumber]));
  except
    Result.Free;
    raise;
  end;
end;

No bitmap is rendered along the way. The counts come from the page's object list, its text page, and its annotation list. The two link counts take the page number as an argument, so they work for any page and leave PageNumber untouched. A loop over WebLink in a console program prints what the scan of the text layer found:

procedure ListTextUrls(Pdf: TPdf; PageNumber: Integer);
var
  LinkIndex: Integer;
  Link: TWebLink;
begin
  for LinkIndex := 0 to Pdf.WebLinkCount[PageNumber] - 1 do
  begin
    Link := Pdf.WebLink[PageNumber, LinkIndex];
    Writeln(string(Link.Url), ' starts at character ', Link.StartCharIndex,
      ' and covers ', Link.CharCount);
  end;
end;

For a page whose text is Pay at https://example.com today and that carries no link annotation, StartCharIndex is 7, the index of the first h in the text page that CharacterCount also counts, and CharCount is 19, the length of the address. Expected output:

https://example.com starts at character 7 and covers 19

One JSON file for the whole document

The report routine reads the document-level fields once, before the loop touches a page, because none of them depends on PageNumber, and it then calls the page helper for every page. It opens its own TPdf instance for the job. The loop changes the current page as it goes, so running it on the document that an interactive viewer is displaying would move the page under the user or disturb a selection in progress. FormFill is False. The inventory reads no form data, so it can skip the form environment. The routine also refuses an output path that equals the input path or names an existing file, so one run never replaces earlier results.

PDFium Component content inventory combines TPdf document fields with a pages array populated from CharacterCount, ObjectCount, AnnotationCount, and LinkAnnotationCount
A PDF content inventory reads the document properties once and repeats the current-page counts for every page in the JSON report
procedure WritePdfInventory(const PdfFile, OutputFile: string);
var
  Pdf: TPdf;
  Report: TJSONObject;
  Pages, Names: TJSONArray;
  PageNumber, AttachmentIndex: Integer;
begin
  if SameText(ExpandFileName(PdfFile), ExpandFileName(OutputFile)) then
    raise EArgumentException.Create('Choose a separate file for the report');
  if FileExists(OutputFile) then
    raise EArgumentException.Create('Choose a new report filename');

  Pdf := TPdf.Create(nil);
  try
    Pdf.FormFill := False;
    Pdf.FileName := PdfFile;
    Pdf.Active := True;
    if not Pdf.Active then
      raise EInOutError.Create('Unable to open the source PDF: ' +
        Pdf.LastLoadReport.ErrorMessage);

    Report := TJSONObject.Create;
    try
      Report.AddPair('title', string(Pdf.Title));
      Report.AddPair('author', string(Pdf.Author));
      Report.AddPair('pageCount', TJSONNumber.Create(Pdf.PageCount));
      Report.AddPair('topLevelBookmarks',
        TJSONNumber.Create(Length(Pdf.Bookmarks)));

      Names := TJSONArray.Create;
      Report.AddPair('attachmentNames', Names);
      for AttachmentIndex := 0 to Pdf.AttachmentCount - 1 do
        Names.AddElement(TJSONString.Create(string(Pdf.AttachmentName[AttachmentIndex])));

      Pages := TJSONArray.Create;
      Report.AddPair('pages', Pages);
      for PageNumber := 1 to Pdf.PageCount do
        Pages.AddElement(InventoryPage(Pdf, PageNumber));

      TFile.WriteAllText(OutputFile, Report.ToJSON, TEncoding.UTF8);
    finally
      Report.Free;
    end;
  finally
    Pdf.Free;
  end;
end;

A small file shows which values are fixed by structure. Page 1 holds the single line Invoice 1042, and a link annotation over it points to an address that appears nowhere in the text. Page 2 is one scanned picture placed directly on the page. The document carries one embedded file named notes.txt, no outline, and document properties with the title Scan batch 42 and the author Accounts. Any authoring tool can build it: type the line, make it a link to some address, paste a picture on a second page, and attach a small text file. Expected content of the report for that file, shown with line breaks added for readability:

{
  "title": "Scan batch 42",
  "author": "Accounts",
  "pageCount": 2,
  "topLevelBookmarks": 0,
  "attachmentNames": ["notes.txt"],
  "pages": [
    {"page": 1, "characters": 12, "topLevelImages": 0, "annotations": 1, "linkAnnotations": 1},
    {"page": 2, "characters": 0, "topLevelImages": 1, "annotations": 0, "linkAnnotations": 0}
  ]
}

Most of those values follow from the structure of the file and not from the tool that produced it. pageCount, the attachment name, and the three zeros on the scan page are fixed. characters: 12 holds as long as the line is written the way it reads. A producer that splits it into several text runs can add a generated space, and nothing else on the page should move the figure. A file without embedded files gives "attachmentNames": [], and one without an outline gives "topLevelBookmarks": 0. Empty title and author values mean that the file carries no such document property. The third kind of input is a path that does not exist. With PDFium Component, Active := True does not raise when the file cannot be opened: the component stays inactive, LastLoadReport records the reason, and the routine raises before any report is written. For a batch consumer the three outcomes must stay distinct, a feature that is present, a feature that is absent, and a file that could not be read, particularly when a zero count is used for routing.

The JSON arrays belong to the report once they are added, and each page object belongs to the pages array, so freeing Report at the end releases everything. Only attachment names are read. AttachmentName returns the name registered for the file, and Attachment[Index], which decompresses the payload, is never touched, so the inventory never loads an embedded archive just to learn whether one exists. The article on reading, adding, and deleting PDF attachments shows how to write each file to disk once the inventory has found it.

Why page-level rows survive a rewrite

Two reports compare page for page or not at all. If a rewrite inserts a cover, page 4 is still the fourth page of each file and may hold different content. The page number is not an identity. PageLabel[PageNumber] returns the label the document defines for a page, such as iv or A-3, without changing the current page. One more pair puts that label into each row: Result.AddPair('label', TJSONString.Create(string(Pdf.PageLabel[PageNumber]))). A file that defines no labels contributes an empty string. Where the label moves too, store an identifier from your own workflow next to it. Page-level rows also catch what a total hides: a loss on one page and a gain on another leave the sum unchanged. Three more rules keep the rest of the report comparable:

  • A field name should carry its unit. A character count and the length of a Unicode string are different measurements, as the 24 characters that report as 26 show. A text preview has a third length, its own display limit. A report that adds previews keeps the count in a field of its own, and the consumer can tell the measurement from the limit.
  • The inspection scope belongs in the schema too. A later version of the inventory might walk into Form XObjects and count nested images. That number goes into a new field, or the schema gets a version, so that an old report and a new one still compare number for number.
  • The example builds the whole report in memory and writes the file once at the end, so a failure while the PDF is being read leaves no report behind. Very large PDFs suit a streamed variant that appends page rows to a private file and publishes it only after the last row is written, which also gives a retry a clean boundary after a disk or encoding error.

Which extraction path follows from the inventory?

A positive character count on every page routes a file to full-text export, and the walkthrough on extracting text from PDF files covers both the Character[] array and the structured ReadablePageContent route. The count says nothing about how the text will read. A PDF with scrambled coordinates or an unusual character map can have many parsed entries and still need a reading-order review or OCR. Text previews in a routine inventory should stay short, above all when the PDFs may contain customer data. A scan with zero characters goes to OCR first. After that, the counts are routing hints: a file that carries its source XML goes to the process that consumes it, and a file with nested bookmarks goes to the traversal code. The PDFium Component product page links to the API reference for the underlying counts and accessors.