Skip to content
GDKsoftwarePublic

About

PDF library for Delphi

Resources

Stars

3 stars

Watchers

1 watching

Forks

Latest commit

 

History

1 Commit

Folders and files

Repository files navigation

Pdf4D

Pdf4D is a native Delphi port of the reading side of Apache PDFBox 3.0.8: document structure, pages, outlines, form fields, attachments and text extraction. It renders pages to bitmaps with the same rules as PDFBox's PDFRenderer. It does not write PDF files. The core has no dependencies besides the Delphi RTL; rendering with the Skia backend also needs the Skia library that ships with RAD Studio.

Platforms

  • Delphi 12 or newer. Built and tested on Delphi 13 (Studio 37.0); not yet verified on Delphi 12.
  • Win32, Win64 and Linux64
  • RTL only for the core, the renderer and the viewer core: no Winapi.*, Vcl.* or FMX.* units and no inline assembler. Only the Skia backend (and its VCL component) uses System.Skia. The VCL components are for Win32 and Win64.

Features

  • Document structure: loading, decryption, pages, document information, outlines, form fields, attachments, digital signatures (read only) and a public interface API.
  • Text extraction: ExtractText on a document or a page, with the options of PDFBox's PDFTextStripper. All 188 files of the test corpus give the same text as PDFBox 3.0.8, except 6 with documented differences (five with right-to-left text, one where Pdf4D is more lenient than PDFBox).
  • Rendering: TPdfRenderer draws a page into a bitmap through a device interface, with two backends. TPdfNativeBackend, a Delphi port of tiny-skia, needs no library next to the program and is the default of the viewers; it reproduces the 108 reference images of tiny-skia byte for byte. TPdfSkiaBackend draws with the Skia library of RAD Studio. Both are compared with the renders of PDFBox 3.0.8: of the 617 corpus pages at 72 DPI, 612 are equal within the tolerances of docs/golden-format.md with Skia and 613 with the native backend, and the rest have a documented difference. Annotations without an appearance stream are not drawn (constructAppearances is not ported). See "Rendering".
  • Viewer: a viewer core without a framework (Pdf4D.Viewer) with VCL and FMX components on top of it, see "Viewer (VCL)" and "Viewer (FMX)".
  • Content model and JSON export: the package Pdf4D.Extract, see "Content and JSON export".

Limits on hostile input and the deviations from PDFBox and tiny-skia are in docs/porting.md. It is built and tested with Delphi 13 on Win32, Win64 and Linux64 (the VCL and FMX components on Windows only). Not yet verified: Delphi 12, the Debug configuration of every package, both design-time packages installed in one IDE, and printing on a physical printer; docs/building.md has the checklists.

Usage

uses
  Pdf4D.Api.Document,
  Pdf4D.Api.Document.Interfaces,
  Pdf4D.Api.Page.Interfaces;

begin
  const Document = TPdfDocument.Load('invoice.pdf');
  Writeln(Document.Info.Title, ', ', Document.PageCount, ' pages');

  for var Page in Document.Pages do
  begin
    Writeln(Page.Index, ': ', Page.MediaBox.Width:0:0, ' x ', Page.MediaBox.Height:0:0);
  end;

  for var Attachment in Document.Attachments do
  begin
    Writeln(Attachment.FileName, ': ', Length(Attachment.Data), ' bytes');
  end;
end;

The interfaces keep the document alive: a page, an outline item, a field or an attachment stays valid after the IPdfDocument reference is released, and the file is closed when the last reference is gone. A file that cannot be opened or parsed raises an EPdfException descendant. CosDocument and the CosObject functions give access to the inner layer; what they return is valid only while an interface of the document is alive.

Signatures

uses
  Pdf4D.Api.Document,
  Pdf4D.Api.Document.Interfaces,
  Pdf4D.Api.Signature.Interfaces;

begin
  const Document = TPdfDocument.Load('contract.pdf');
  const Signatures = Document.Signatures;
  Writeln('Signed: ', Length(Signatures) > 0);

  for var Signature in Signatures do
  begin
    Write(Signature.Name, ', ', Signature.Reason, ', ', Signature.SubFilter);
    if Signature.HasSignDate then
      Write(', ', DateTimeToStr(Signature.SignDate));
    // False when the file was changed (an incremental update) after this signature
    Writeln(', covers the whole file: ', Signature.CoversWholeDocument);
  end;
end;

Signatures gives the signature dictionary (/V) of every signature field of the form that has one, in the order of the field tree, like PDDocument.getSignatureDictionaries of PDFBox; IPdfField.Signature gives the one of a single field and is nil for a field of another kind and for a signature field that is not signed. A document is signed when Signatures is not empty. This works the same for encrypted files, files with object streams and xref streams and files with incremental updates. A signature dictionary that is not the value of a field (for example the usage rights signature of /Perms) is not listed, as in PDFBox.

Contents gives the bytes of /Contents as the file holds them (an encrypted document does not encrypt them), ByteRange the signed ranges of the file, and CoversWholeDocument whether these ranges start at 0 and end at the end of the file. Nothing is verified: there is no check of the certificate, the hash or the CMS object, as in PDFBox core. Broken signature data is logged and gives empty values, it does not raise.

Extracting text

uses
  Pdf4D.Api.Document,
  Pdf4D.Api.Document.Interfaces,
  Pdf4D.Api.TextOptions,
  System.RegularExpressions;

begin
  const Document = TPdfDocument.Load('invoice.pdf');
  const Text = Document.ExtractText;
  Writeln(Text);

  // The options are those of PDFBox's PDFTextStripper, with the same defaults
  var Options := TPdfTextOptions.Default;
  Options.SortByPosition := True;
  Options.StartPage := 2;
  Options.EndPage := 3;
  Writeln(Document.ExtractText(Options));

  // One page only
  Writeln(Document.Page(0).ExtractText);

  // The same text with the place of every character. Text.Locate takes a 1-based range, like Match.Index.
  const Positioned = Document.Page(0).ExtractTextWithPositions;
  const Match = TRegEx.Match(Positioned.Text, '\d{4}-\d{4}');
  if Match.Success then
  begin
    for var Fragment in Positioned.Locate(Match.Index, Match.Length) do
      Writeln(Fragment.PageIndex, ': ', Fragment.Quads[0].Bounds.Left:0:2);
  end;
end;

ExtractTextWithPositions (on a document or a page) returns the same text and, per range, the quads of its characters, one per line, in PDF user space. Page(n).TextLayout gives the words, segments and lines of a page, with TryFindSegmentAt and TryFindWordAt for hover.

The text is what PDFBox's PDFTextStripper writes, with one deviation: right-to-left text (Hebrew, Arabic) comes in the order of the file, because there is no bidi pass. See docs/porting.md.

Fonts that are not embedded are looked up among the standard 14 fonts (their metrics are part of the library), then among the fonts installed on the system (the font folders are scanned once, headers only, and nothing is written to disk). When no font matches, Pdf4D falls back to LiberationSans, which is part of the library, as PDFBox does.

One page has a budget of operators and glyphs, so that a hostile file ends in bounded time. The defaults are large (10 million operators and 2 million glyphs); a caller who wants a shorter worst case lowers MaxOperatorsPerPage and MaxGlyphsPerPage in TPdfLoadOptions and passes it to TPdfDocument.Load. See docs/porting.md for all limits.

Content and JSON export

TPdfContent.Open (package Pdf4D.Extract) reads a document into a model that a program can walk page by page: the text as blocks, lines, segments and words with their boxes, the fonts, the image placements, links, form widgets, simple graphics (lines and rectangles), and for the document as a whole its Info, outline, form fields and attachments. TPdfJsonExporter.Export writes the same model as JSON, following docs/json-schema.md (with a JSON Schema in docs/pdf4d-content.schema.json).

uses
  Pdf4D.Api.Document,
  Pdf4D.Api.Document.Interfaces,
  Pdf4D.Extract.Content,
  Pdf4D.Extract.Content.Interfaces,
  Pdf4D.Extract.Json,
  System.Classes;

begin
  const Document = TPdfDocument.Load('invoice.pdf');

  // The model, one page at a time (a page does not depend on the document and is freed when the loop moves on)
  var Options := TPdfContentOptions.Default;
  Options.TextDetail := TPdfTextDetail.Words;
  Options.IncludeGraphics := True;
  const Reader = TPdfContent.Open(Document, Options);
  for var Page in Reader do
  begin
    Writeln(Page.Index, ': ', Length(Page.Blocks), ' blocks, ', Length(Page.Images), ' images');
  end;

  // The same as JSON, to a string or to a stream
  var JsonOptions := TPdfJsonOptions.Default;
  JsonOptions.Content := Options;
  JsonOptions.Indented := True;
  Writeln(TPdfJsonExporter.Export(Document, JsonOptions));

  const Output = TFileStream.Create('invoice.json', fmCreate);
  try
    TPdfJsonExporter.Export(Document, Output, JsonOptions);
  finally
    Output.Free;
  end;
end;

The JSON has "producer": "Pdf4D 1.0.0" (the constant Pdf4DVersion of Pdf4D.Common.Defines) and begins like this (this is the real output of pdf2json tests\corpus\generated\invoices\skia-draw.pdf --indent --pages 1-1, shortened: ... marks what is left out):

{
    "schemaVersion": "1.0",
    "producer": "Pdf4D 1.0.0",
    "options": {
        "textDetail": "words",
        "includeFonts": true,
        "includeQuads": false,
        "includeImages": false,
        "includeImageData": false,
        ...
    },
    "document": {
        "version": 1.4,
        "encrypted": false,
        "permissions": { ... },
        "info": {
            "title": "Invoice INV-2031-0417",
            "creator": "Pdf4D.InvoiceGen",
            "producer": "Skia/PDF",
            ...
        },
        "pageCount": 1
    },
    "pages": [
        {
            "index": 0,
            "width": 595,
            "height": 842,
            "rotation": 0,
            "text": "INVOICE Invoice number INV-2031-0417\nInvoice date 2031-03-14\n...",
            "fonts": [ ... ],
            "blocks": [ ... ]
        }
    ]
}

Things to know:

  • Every line break in a text value is a line feed (\n), on every platform, also in an indented file. Numbers are rounded to 2 decimals. A date without an offset in the file is written with Z.
  • The export is written one page at a time. A page that cannot be read gets an entry with an error and the export goes on. When the export fails in another way (a write error, say), the exception reaches the caller and the stream holds an incomplete document that is not closed, so it does not parse: write to a temporary file and rename it afterwards, as the demo does.
  • The graphics are off by default (IncludeGraphics). A shape is a straight line or a rectangle; curves and Type 3 glyph paths are not listed. The quads are off by default as well (IncludeQuads, in PDF user space).
  • A link lists the indexes of the words whose centre lies in the link (at text detail words).
  • A form widget without /P is placed through the /Annots of the pages; a widget that no page lists is left out.
  • Image data (IncludeImageData) is base64, written on the first placement of an objectKey whose data could be read, and on every inline image; later placements of the same image have no data. PNG data is straight (not premultiplied) alpha. A placement whose data cannot be read has a dataError, and a later placement of the same image tries again, so a heavily reused image that cannot be decoded is decoded again for every page. IPdfPageImages.GetAllData decodes the images; Images only lists the placements.

The demo demos\Console\pdf2json.dproj is the command line version:

pdf2json <input.pdf> [<output.json>] [--password <pw>] [--detail none|text|lines|words] [--images] [--image-data]
         [--graphics] [--attachments] [--xmp] [--quads] [--indent] [--pages <from>-<to>]

Without an output file the JSON goes to standard output as UTF-8 bytes, so redirect or pipe it (a console may show accents wrongly). The page numbers are 1-based. The exit code is 0 when done, 1 for a wrong command line and 2 when the PDF cannot be read (the message is on standard error); a file is written under a temporary name and renamed when the export is complete. tools\json\export-corpus.ps1 runs the demo over the test corpus and validates every result against the schema (docs/building.md).

Rendering

uses
  Pdf4D.Api.Document,
  Pdf4D.Api.Document.Interfaces,
  Pdf4D.Render.Bitmap,
  Pdf4D.Render.Renderer,
  Pdf4D.Render.Renderer.Interfaces,
  Pdf4D.Render.Skia.Backend;

begin
  const Document = TPdfDocument.Load('invoice.pdf');
  const Renderer: IPdfRenderer = TPdfRenderer.Create(Document, TPdfSkiaBackend.Create);

  var Bitmap: TPdfBitmap;
  if Renderer.RenderToBitmap(0, TPdfRenderParams.FromDpi(96), Bitmap) = TPdfRenderStatus.Completed then
  try
    // Bitmap.Pixels: premultiplied RGBA, 8 bits per channel, rows from top to bottom, Bitmap.Stride bytes per row
    Writeln(Bitmap.Width, ' x ', Bitmap.Height);
  finally
    Bitmap.Free;
  end;
end;

The own rasterizer, a Delphi port of tiny-skia, needs no library next to the program; it is also what the viewers use when the application sets no backend:

uses
  Pdf4D.Render.Native.Backend;

const Renderer: IPdfRenderer = TPdfRenderer.Create(Document, TPdfNativeBackend.Create);

RenderToBitmap draws the whole page with a white background and anti-aliasing, like PDFRenderer.renderImage of PDFBox with ImageType.RGB. The other fields of TPdfRenderParams choose a region of the page, an extra rotation, a cancel token (the only thing that may be used from another thread) and the options (destination, background, annotations and the limits of docs/porting.md). A renderer is used by one thread at a time, the one that uses the document.

A backend is reference counted. Pass it straight to the renderer or keep it in an interface variable, and never call a method on a bare TPdfNativeBackend.Create (a call such as TPdfNativeBackend.Create.CreateRasterDevice(...) never releases the object). The same holds for TPdfSkiaBackend.

The native backend has two limits, in TPdfNativeLimits (start from TPdfNativeLimits.Default and pass the record to TPdfNativeBackend.Create; a value below 1 raises EArgumentOutOfRangeException):

Limit Default Meaning
MaxPathVerbs 4,194,304 (1,048,576 on Win32) verbs of one fill, stroke or clip path
MaxEdgeWork 800,000,000 the work for the edges of one path; depends on the DPI and on anti-aliasing

A fill, a stroke or a clip path over a limit raises EPdfLimitExceededException before a pixel changes, and the renderer logs it and goes on with the next operator. A clip path over a limit raises at the next draw, not when the clip is set. The peak memory is about 350 bytes per verb, so about 1.5 GB at the default MaxPathVerbs of Win64 and Linux64. The default on Win32 is 1,048,576 verbs (a peak of about 150 MB measured), so a Win32 host needs no change; lower it further when memory is tight. docs/porting.md has the reasoning and the other places where the native backend differs from tiny-skia. The switches that the tests use (DeferMode, ForceMaskClip, the counters) exist only in the test projects and are not part of the API.

The renderer is split over four packages next to the core package Pdf4D:

Package Contents Needs
Pdf4D document, pages, text extraction RTL
Pdf4D.Render the renderer, the colour spaces, images, shadings and patterns, the JPEG and CCITT decoders, the device interface Pdf4D
Pdf4D.Render.Native TPdfNativeBackend, the own rasterizer (a port of tiny-skia) Pdf4D, Pdf4D.Render
Pdf4D.Render.Skia TPdfSkiaBackend, built on System.Skia Pdf4D, Pdf4D.Render, Skia.Package.RTL

The core does not need Skia, and neither does the native backend. The Skia backend needs the Skia library next to the program: sk4d.dll on Windows (Redist\win32 or Redist\win64 of RAD Studio) and libsk4d.so on Linux64. An application that brings its own backend (anything that implements IPdfRenderBackend) uses Pdf4D.Render without Pdf4D.Render.Skia and without Skia. See docs/building.md.

Viewer (VCL)

The viewer shows a PDF in a VCL form: continuous or single-page scrolling, zoom and rotation, thumbnails and outline, hover and text selection, links, search, copy to the clipboard and printing. Everything that is not VCL (layout, tiles and their cache, hit testing, search, the rules of the commands, the print plan) is in the viewer core Pdf4D.Viewer, which a later FMX version shares. A document is rendered on a worker thread; the UI thread only paints bitmaps.

Package Contents Needs
Pdf4D.Viewer the viewer core: types, view transform, layout, tiles, controllers, search, print plan, the document session Pdf4D, Pdf4D.Render
Pdf4D.Vcl TPdf4DDocument, TPdf4DPageView, TPdf4DThumbnails, TPdf4DOutlineView, TPdf4DSearchBar, TPdf4DToolbar, TPdf4DViewer, TPdf4DPrintDialog and the standard actions vcl, Pdf4D.Viewer
Pdf4D.Vcl.Skia the component TPdf4DSkiaBackend Pdf4D.Vcl, Pdf4D.Render.Skia
dclPdf4D.Vcl design time: the Pdf4D palette page, the actions in the action list editor, a file dialog for FileName designide, Pdf4D.Vcl, Pdf4D.Vcl.Skia

TPdf4DViewer is the whole viewer in one component (toolbar, search bar, side panel, page view); the parts can also be used on their own, all following one TPdf4DDocument. Without a backend the viewers render with the own rasterizer (TPdfNativeBackend), which needs no DLL. Skia is a choice for those who ship the library: drop a TPdf4DSkiaBackend on the form and link it to the Backend property of the document, or set RenderBackend of the document in code to any IPdfRenderBackend; an explicit backend is always used as it is. The Skia backend needs sk4d.dll next to the program (Redist\win32 or Redist\win64 of RAD Studio); Pdf4D.Vcl itself does not link Skia.

Pdf4DDocument1.Backend := Pdf4DSkiaBackend1;
Pdf4DViewer1.Document := Pdf4DDocument1;
Pdf4DDocument1.FileName := 'invoice.pdf';
Pdf4DDocument1.Open;

// In OnOpened or when a field gets focus. FDocument is the application's own IPdfDocument of the same file
// (TPdfDocument.Load); the viewer's document lives on its worker and is never used from the UI thread.
const Text = FDocument.Page(0).ExtractTextWithPositions;
const Match = TRegEx.Match(Text.Text, '\d{4}-\d{4}');
if Match.Success then
begin
  for var Fragment in Text.Locate(Match.Index, Match.Length) do
  begin
    // The ellipse is filled: use a translucent colour to keep the text under it readable
    Pdf4DDocument1.Overlays.Add(Fragment.PageIndex, Fragment.Quads, TPdfOverlayStyle.Ellipse, TAlphaColor($66FF0000));
    Pdf4DViewer1.PageView.ScrollIntoView(Fragment.PageIndex, Fragment.Quads);
  end;
end;

demos\Vcl\Pdf4DInvoiceDemo.dproj is a complete example: an invoice form on the left and the viewer on the right. A field that gets the focus is looked up in the text of the PDF and marked there, a click on a word in the PDF fills the field that has the focus. It runs Per-Monitor v2 and opens the file given on the command line (Pdf4DInvoiceDemo.exe invoice.pdf) or through the Open button. tests\corpus\generated\invoices\skia-draw.pdf is an invoice with invented data that fits the default values of the form.

What the viewer does not do (yet): selection across pages, searching across a page boundary or with regular expressions, hit testing on annotations other than links, filling in forms, saving markings, screen readers and right-to-left text, vector printing (it prints raster) and a visible focus frame and keys in the thumbnails. A document that is opened from a file and needs a password gets a question for it (three tries); a document that is opened from a stream does not, because the document does not keep the data: OnOpenError reports InvalidPassword and the application sets Password and opens the stream again. The events that the viewer forwards (OnTextSelected, OnHoverChanged, OnLinkClick) have its page view as Sender.

Viewer (FMX)

The FMX viewer has the same components, properties and behaviour as the VCL viewer (continuous or single-page scrolling, zoom and rotation, thumbnails and outline, hover and text selection, links, search, copy and printing), on the same viewer core Pdf4D.Viewer. It is for Windows (Win32 and Win64; so far built and tested on Win64); other FMX platforms and touch gestures are not part of this phase. The scale of the screen is the scale of the form: a page is rendered at the pixels of the device, so it stays sharp on a 150 % screen and after a move to another screen.

Package Contents Needs
Pdf4D.FMX TPdf4DDocument, TPdf4DPageView, TPdf4DThumbnails, TPdf4DOutlineView, TPdf4DSearchBar, TPdf4DToolbar, TPdf4DViewer, TPdf4DPrintDialog and the standard actions fmx, Pdf4D.Viewer
Pdf4D.FMX.Skia the component TPdf4DSkiaBackend Pdf4D.FMX, Pdf4D.Render.Skia
dclPdf4D.FMX design time: the Pdf4D palette page, the actions in the action list editor, a file dialog for FileName designide, Pdf4D.FMX, Pdf4D.FMX.Skia

Install dclPdf4D.Vcl and dclPdf4D.FMX together if you use both: each is meant to show its components on the Pdf4D page of its own kind of project (this has not been checked in the IDE yet). The backend is chosen like in VCL: without one the own rasterizer is used, and a TPdf4DSkiaBackend linked to Backend (or RenderBackend in code) selects Skia, which needs sk4d.dll next to the program. The example is that of the VCL viewer, with the colours of FMX:

Pdf4DDocument1.Backend := Pdf4DSkiaBackend1;
Pdf4DViewer1.Document := Pdf4DDocument1;
Pdf4DDocument1.FileName := 'invoice.pdf';
Pdf4DDocument1.Open;

// In OnOpened or when a field gets focus. FDocument is the application's own IPdfDocument of the same file
// (TPdfDocument.Load); the viewer's document lives on its worker and is never used from the UI thread.
const Text = FDocument.Page(0).ExtractTextWithPositions;
const Match = TRegEx.Match(Text.Text, '\d{4}-\d{4}');
if Match.Success then
begin
  for var Fragment in Text.Locate(Match.Index, Match.Length) do
  begin
    // The ellipse is filled: use a translucent colour to keep the text under it readable
    Pdf4DDocument1.Overlays.Add(Fragment.PageIndex, Fragment.Quads, TPdfOverlayStyle.Ellipse, TAlphaColors.Red and $66FFFFFF);
    Pdf4DViewer1.PageView.ScrollIntoView(Fragment.PageIndex, Fragment.Quads);
  end;
end;

demos\FMX\Pdf4DInvoiceDemoFmx.dproj is the invoice demo as an FMX form.

What the resources add

The glyph lists, the AFM metrics of the standard 14 fonts, the predefined CMaps and LiberationSans-Regular are linked into the binary as compressed resources, so nothing has to be installed next to the program. Together they add about 1.6 MB (compressed) to an executable. Licences and sources are in NOTICE, licenses/ and src/Resources/resources.csv.

A document is not thread-safe, but different documents can be used in different threads. Input problems (the file or its content) raise EPdfException descendants; invalid arguments raise EArgument* exceptions. A bookmark option (StartBookmark, EndBookmark) that belongs to another document, or that this library did not make, raises EArgumentException. An exception of the TTextWriter that you give to WriteText is raised as it was, with its own class and message.

Building and testing

./build.ps1 -Platform All

The script builds the packages, compiles the demos (the console demo pdf2json on every platform, the VCL and FMX demos on Windows only) and builds and runs the three test projects (tests/Pdf4D.Tests.dproj without Skia, tests/Skia/Pdf4D.Skia.Tests.dproj with it, tests/Vcl/Pdf4D.Vcl.Tests.dproj for the VCL components on Windows); see docs/building.md.

License

Apache License 2.0, see LICENSE and NOTICE. Pdf4D is a derived work of Apache PDFBox. The native rasterizer (src\Render\Native) is a port of tiny-skia, which is licensed under the BSD 3-Clause License (licenses\tiny-skia-BSD-3-Clause.txt, named in NOTICE).

About

PDF library for Delphi

Resources

Stars

3 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages