PDFiumVCL Docs

PDFium VCL API Reference

TPdf Component Methods

Document Management

MethodDescription
CreateDocumentCreate a new empty PDF document
LoadDocument(Data: TMemoryStream; Buffered: Boolean = True)Load PDF document from memory stream
LoadDocument(Data: Pointer; Size: Integer; Buffered: Boolean = True)Load PDF document from memory buffer
LoadDocumentLoad PDF document from FileName
LoadDocument(const Data: TBytes; Buffered: Boolean = True)Load PDF document from TBytes
SaveAs(Stream: TStream; Option: TSaveOption = saNone; PdfVersion: TPdfVersion = pvUnknown): BooleanSave document to stream. When Compressed is True, ensures all streams are FlateDecode compressed.
SaveAs(const FileName: string; Option: TSaveOption = saNone; PdfVersion: TPdfVersion = pvUnknown): BooleanSave document to file
ImportPages(Pdf: TPdf; const Range: string; PageNumber: Integer = 1): BooleanImport pages from another PDF document. Range format: '1,3,5-7'
ImportPreferences(Pdf: TPdf): BooleanImport viewer preferences from another PDF

Page Operations

MethodDescription
AddPage(PageNumber: Integer; Width, Height: Double)Add a new page at the specified position with given dimensions (in points, 72 points = 1 inch)
DeletePage(PageNumber: Integer)Delete page at specified index
ReloadPageReload the current page
UpdatePageApply pending changes to the current page (calls FPDFPage_GenerateContent)

Text Operations

MethodDescription
Text(StartIndex: Integer = 0; Count: Integer = MaxInt): WStringExtract text from current page
TextInRectangle(Left, Top, Right, Bottom: Double): WStringExtract text from rectangular area (page coordinates)
TextInRectangle(Rectangle: TPdfRectangle): WStringExtract text from rectangle
AddText(const Text, Font: WString; FontSize: Single; X, Y: Double; Color: TColor = clBlack; Alpha: Byte = $FF; Angle: Double = 0.0)Add text at specified position with font, color, transparency, and rotation angle
SetText(ObjectIndex: Integer; const Text: WString)Set text for an existing text object (undocumented PDFium API, may cause formatting issues)
FindFirst(const Text: WString; Options: TSearchOptions = []; StartIndex: Integer = 0; DirectionUp: Boolean = True): IntegerStart text search, returns character index or -1 if not found
FindNext: IntegerContinue text search forward, returns character index or -1
FindPrevious: IntegerContinue text search backward, returns character index or -1
CharacterIndexAtPos(X, Y, ToleranceX, ToleranceY: Double): IntegerGet character index at page position
RectangleCount(StartIndex: Integer = 0; Count: Integer = MaxInt): IntegerGet the number of text rectangles for a character range

Annotation Operations

MethodDescription
CreateAnnotation(const Annotation: TPdfAnnotation)Create a new annotation on the current page
DeleteAnnotation(Index: Integer)Delete annotation at index

Form Flattening

MethodDescription
GenerateFormAppearancesRegenerates /AP appearance streams for every form widget on every page (FPDF_FFLDraw). Call after FormField[] assignments and before SaveAs / FlattenPage / FlattenAllPages.
FlattenPage(nFlag: Integer = FLAT_NORMALDISPLAY): IntegerFlatten annotations and form widgets on the current page into static content. Returns FLATTEN_SUCCESS, FLATTEN_NOTHINGTODO, or FLATTEN_FAIL.
FlattenAllPages(nFlag: Integer = FLAT_NORMALDISPLAY): BooleanFlatten every page in the document. Returns True when all pages succeed.

Attachment Operations

MethodDescription
CreateAttachment(const Name: WString): BooleanCreate a new empty attachment
DeleteAttachment(Index: Integer): BooleanDelete attachment at index

Image Operations

MethodDescription
AddJpegImage(JpegImage: TStream; X, Y, Width, Height: Double): BooleanAdd JPEG image from stream at specified position and size
AddPicture(Picture: TPicture; X, Y: Double)Add picture at position (original size)
AddPicture(Picture: TPicture; X, Y, Width, Height: Double)Add picture at position with specified size

Drawing Operations

MethodDescription
CreatePath(X, Y: Single; FillMode; FillColor; FillAlpha; Stroke; StrokeColor; StrokeAlpha; StrokeWidth; LineCap; LineJoin; BlendMode)Create a path starting at position (X, Y)
CreatePath(X, Y, Width, Height: Single; ...)Create a rectangular path with given bounds
MoveTo(X, Y: Single)Move the current point to (X, Y)
LineTo(X, Y: Single)Draw a line from the current point to (X, Y)
BezierTo(X1, Y1, X2, Y2, X3, Y3: Single)Draw a Bezier curve with two control points and an endpoint
ClosePathClose the current subpath
AddPathAdd the completed path to the current page

Rendering

MethodDescription
RenderPage(DeviceContext: HDC; Left, Top, Width, Height: Integer; Rotation; Options)Render page to a device context (HDC)
RenderPage(Left, Top, Width, Height: Integer; Rotation; Options; Color): TBitmapRender page to a new bitmap
RenderPage(Bitmap: TBitmap; Left, Top, Width, Height: Integer; Rotation; Options; Color)Render page to an existing bitmap
RenderTile(Left, Top, Width, Height, PageWidth, PageHeight: Integer; ...): TBitmapRender a tile (portion) of a page to a new bitmap
RenderTile(Bitmap: TBitmap; Left, Top, Width, Height, PageWidth, PageHeight: Integer; ...)Render a tile to an existing bitmap

Coordinate Conversion

MethodDescription
DeviceToPage(X, Y, Left, Top, Width, Height: Integer; Rotation: TRotation; out PageX, PageY: Double): BooleanConvert device coordinates to page coordinates
PageToDevice(PageX, PageY: Double; Left, Top, Width, Height: Integer; Rotation: TRotation; out X, Y: Integer): BooleanConvert page coordinates to device coordinates

TPdf Component Properties

Published Properties (Design-Time)

PropertyTypeDescription
AboutstringComponent version information (stored False)
ActiveBooleanSet to True to load/activate the document, False to close it
FileNamestringPath to the PDF file to load
FormFillBooleanEnable interactive form filling with JavaScript support (default True)
PageNumberIntegerCurrent page number (1-based, 0 when no document is loaded)
PasswordstringPassword for opening encrypted PDF documents

Document Properties

PropertyTypeR/WDescription
AuthorWStringRDocument author
CompressedBooleanR/WWhen True (default), SaveAs post-processes the output to ensure all streams are FlateDecode compressed
CreationDateWStringRDocument creation date metadata
CreatorWStringRApplication that created the document
DocumentFPDF_DOCUMENTRLow-level PDFium document handle
FormTypeTPdfFormTypeRForm type: ftNone, ftAcroForm, ftXFAFull, ftXFAForeground
IsTaggedBooleanRTrue if document is a tagged PDF
KeywordsWStringRDocument keywords
MetaText[const Tag: string]WStringRArbitrary metadata value by tag name
ModifiedDateWStringRLast modification date metadata
PageCountIntegerRTotal number of pages
PdfVersionTPdfVersionRPDF version (pv10 through pv17)
PermissionsLongWordRDocument permissions flags
PrintCopiesIntegerRNumber of print copies specified
PrintPaperHandlingTPrintPaperHandlingRPaper handling preference
PrintScalingBooleanRWhether print scaling is enabled
ProducerWStringRPDF producer application
SubjectWStringRDocument subject
TitleWStringRDocument title
UserPermissionsLongWordRUser-level permissions
ViewerPreference[const Key: string]WStringRViewer preference value by key
XFABooleanRTrue if document contains XFA forms

Page Properties

PropertyTypeR/WDescription
PageFPDF_PAGERLow-level PDFium page handle
PageBoundsTPdfRectangleRBounding rectangle of the current page
PageHeightDoubleRHeight of current page in points
PageLabel[PageNumber: Integer]WStringRPage label for a given page number
PageModeTPageModeRHow the document should be displayed when opened
PageRotationTRotationR/WRotation of the current page (ro0, ro90, ro180, ro270)
PageWidthDoubleRWidth of current page in points
ThumbnailTBitmapRThumbnail bitmap of the current page
TransparentBooleanRTrue if the current page contains transparent content

Text and Character Properties

PropertyTypeDescription
Character[Index]WideCharUnicode character at index
CharacterAngle[Index]SingleCharacter rotation angle in radians
CharacterCountIntegerNumber of characters on current page
CharacterFontSize[Index]DoubleFont size of character at index; FontSize[Index] remains as a compatible alias
CharacterFontWeight[Index]IntegerFont weight of character at index
CharacterGenerated[Index]BooleanTrue if character was generated (not from original content)
CharacterIsHyphen[Index]BooleanTrue if character is a hyphen
CharacterMapError[Index]BooleanTrue if character has a mapping error
CharacterOrigin[Index]TPdfPointOrigin point of the character
CharacterRectangle[Index]TPdfRectangleBounding rectangle of the character
Charcode[Index]WideCharCharacter code at index
FindFPDF_SCHHANDLELow-level PDFium search handle
Rectangle[Index]TPdfRectangleText rectangle from last RectangleCount call
TextPageFPDF_TEXTPAGELow-level PDFium text page handle

Font Properties

PropertyTypeDescription
FontAscent[Index; FontSize]SingleAscent of the font used by the text object at index
FontBaseName[Index]WStringBase font name for the text object at index
FontData[Index]TBytesRaw font data for the text object at index
FontDescent[Index; FontSize]SingleDescent of the font used by the text object at index
FontFamilyName[Index]WStringFont family name for the text object at index
FontHandle[Index]FPDF_FONTLow-level PDFium font handle for the text object at index
FontIsEmbedded[Index]BooleanTrue if the text object's font is embedded in the PDF
FontItalicAngle[Index]IntegerItalic angle of the text object's font
FontSize[Index]DoubleBackward-compatible alias for CharacterFontSize[Index]
FontWeight[Index]IntegerFont weight of the text object's font (e.g., 400 = normal, 700 = bold)

Object Properties

PropertyTypeDescription
ObjectCountIntegerNumber of page objects
ObjectType[Index]TObjectTypeType: otUnknown, otText, otPath, otImage, otShading, otForm
ObjectBounds[Index]TPdfRectangleBounding rectangle of the object
ObjectBitmap[Index]TBitmapBitmap representation of the object
ObjectHandle[Index]PointerLow-level object handle
ObjectTransparent[Index]BooleanTrue if object is transparent

Image Properties

PropertyTypeDescription
Bitmap[Index]TBitmapBitmap of page object at index
BitmapCountIntegerNumber of bitmap objects on page
Image[Index]TPdfImageImage data (Width, Height, Data) at index
ImageCountIntegerNumber of images on page

Annotation Properties

PropertyTypeR/WDescription
Annotation[Index]TPdfAnnotationR/WGet or set annotation at index
AnnotationCountIntegerRNumber of annotations on current page

Form Properties

PropertyTypeR/WDescription
FormField[Index]WStringR/WForm field value by index
FormFieldAt[X, Y: Single]WStringR/WForm field value at page position
FormFieldCountIntegerRNumber of form fields on current page
FormFieldInfo[Index]TPdfFormFieldInfoRForm field information by index
FormFieldInfoAt[X, Y: Single]TPdfFormFieldInfoRForm field information at page position
FormHandleFPDF_FORMHANDLERLow-level form fill handle
HasFormFieldAt[X, Y: Single]BooleanRTrue if a form field exists at the position

Attachment Properties

PropertyTypeR/WDescription
Attachment[Index]TBytesR/WAttachment data by index
AttachmentCountIntegerRNumber of attachments
AttachmentName[Index]WStringRAttachment filename by index

Navigation Properties

PropertyTypeDescription
Bookmark[const Title: WString]TBookmarkFind bookmark by title
BookmarkChildren[const Bookmark: TBookmark]TBookmarksChild bookmarks of a bookmark
BookmarkFrom[Handle: FPDF_BOOKMARK]TBookmarkBookmark data from a handle
BookmarksTBookmarksTop-level bookmarks array
Destination[Index]TDestinationNamed destination by index
DestinationByName[const Name: WString]TDestinationNamed destination by name
DestinationCountIntegerNumber of named destinations
HasBookmarkChildren[const Bookmark: TBookmark]BooleanTrue if bookmark has children
LinkAnnotation[PageNumber, Index]TLinkAnnotationLink annotation on a given page
LinkAnnotationCount[PageNumber]IntegerNumber of link annotations on a page
WebLink[PageNumber, Index]TWebLinkWeb link (URL) on a given page
WebLinkCount[PageNumber]IntegerNumber of web links on a page

Digital Signature Properties

PropertyTypeDescription
Signature[Index]TPdfSignatureDigital signature information at index
SignatureCountIntegerNumber of digital signatures in the document

TPdf Events

EventTypeDescription
OnFormFieldEnterTPdfFormFieldEnterEventFired when a form field is entered. Parameters: Sender: TObject; const Text: WString
OnFormFieldExitTNotifyEventFired when focus leaves a form field
OnPageChangeTNotifyEventFired when the current page changes
OnUnsupportedFeatureTPdfUnsupportedFeatureEventFired when the PDF contains an unsupported feature

TPdfView Component

TPdfView is a scrollable visual control for displaying and interacting with PDF documents. It requires a Pdf: TPdf reference.

Published Properties (Design-Time)

PropertyTypeDefaultDescription
AboutstringComponent version information
ActiveBooleanFalseActivate/deactivate the viewer
CurrentCharIndexInteger0Application-selected character index retained for compatibility
DisplayModeTPdfDisplayModedmSingleContinuousPage display mode (dmSingleContinuous, dmTwoPageContinuous)
OptionsTRenderOptions[reLcd]Rendering options (LCD text, annotations, grayscale, etc.)
PageNumberInteger1Current page number (1-based)
PdfTPdfnilReference to the TPdf component
RotationTRotationro0Display rotation (ro0, ro90, ro180, ro270)
ZoomDouble1.0Zoom level (1.0 = 100%)

TPdfView-Specific Public Properties

PropertyTypeDescription
ActualSizeZoom[PageNumber]DoubleZoom value to display the page at its actual size
CanvasTCanvasCanvas for custom drawing on the viewer
CharacterAngle[Index]SingleCharacter rotation angle in radians
CharacterFontSize[Index]DoubleFont size of character at index; FontSize[Index] remains as a compatible alias
CharacterFontWeight[Index]IntegerFont weight of character at index
FontAscent[Index; FontSize]SingleAscent of the font used by the text object at index
FontBaseName[Index]WStringBase font name for the text object at index
FontData[Index]TBytesRaw font data for the text object at index
FontDescent[Index; FontSize]SingleDescent of the font used by the text object at index
FontFamilyName[Index]WStringFont family name for the text object at index
FontHandle[Index]FPDF_FONTLow-level PDFium font handle for the text object at index
FontIsEmbedded[Index]BooleanTrue if the text object's font is embedded in the PDF
FontItalicAngle[Index]IntegerItalic angle of the text object's font
FontWeight[Index]IntegerFont weight of the text object's font
PageHeightZoom[PageNumber]DoubleZoom value to fit the page height in the viewer
PageWidthZoom[PageNumber]DoubleZoom value to fit the page width in the viewer
PageZoom[PageNumber]DoubleZoom value to fit the entire page in the viewer
WindowHandleHWNDWindow handle of the viewer control

TPdfView-Specific Methods

MethodDescription
DeviceToPage(X, Y: Integer; out PageX, PageY: Double): BooleanConvert screen coordinates to page coordinates
DeviceToPage(X, Y: Integer; var PageNumber: Integer; var PageX, PageY: Double): BooleanConvert screen coordinates to page coordinates with page detection
DeviceToPage(Rectangle: TRect): TPdfRectangleConvert screen rectangle to page rectangle
PageToDevice(PageX, PageY: Double; out X, Y: Integer): BooleanConvert page coordinates to screen coordinates
PageToDevice(Rectangle: TPdfRectangle): TRectConvert page rectangle to screen rectangle
LinkAnnotationAtPos(X, Y: Integer): IntegerGet link annotation index at screen position
LinkAnnotationAtPos(X, Y: Integer; out PageNumber: Integer): IntegerGet link annotation index with page number
WebLinkAtPos(X, Y: Integer): IntegerGet web link index at screen position
WebLinkAtPos(X, Y: Integer; out PageNumber: Integer): IntegerGet web link index with page number
PaintSelection(SelectionStart, SelectionEnd: Integer; Mask: TColor)Paint text selection highlight
GenerateFormAppearancesRegenerates /AP appearance streams via the associated TPdf component (see TPdf.GenerateFormAppearances)
FlattenPage(nFlag: Integer = FLAT_NORMALDISPLAY): IntegerFlatten annotations and form widgets on the current page into static content

TPdfView Events

EventTypeDescription
OnPageChangeTNotifyEventFired when the displayed page changes during scrolling
OnPageNumberChangedTNotifyEventFired when the PageNumber property is modified
OnPaintTNotifyEventFired during custom painting operations

Data Types and Enumerations

Core Types

TypeDefinition
WStringWide string type for Unicode text
TPdfPointRecord: X, Y: Double
TPdfRectangleRecord: Left, Top, Right, Bottom: Double
TPdfVersionpvUnknown, pv10, pv11, pv12, pv13, pv14, pv15, pv16, pv17
TRotationro0, ro90, ro180, ro270
TSaveOptionsaNone, saIncremental, saNoIncremental, saRemoveSecurity
TObjectTypeotUnknown, otText, otPath, otImage, otShading, otForm
TPageModepmNone, pmOutline, pmThumbs, pmFullScreen, pmOptionalContentGroup, pmAttachments, pmUnknown
TPdfActionacUnsupported, acGoto, acGotoRemote, acUri, acLaunch
TPdfDisplayModedmSingleContinuous, dmTwoPageContinuous

Search and Render Options

TypeValues
TSearchOptionseCaseSensitive, seWholeWord, seConsecutive
TSearchOptionsSet of TSearchOption
TRenderOptionreAnnotations, reLcd, reNoNativeText, reGrayscale, reDebugInfo, reNoCatchException, reLimitCache, reHalftone, rePrinting, reReverseByteOrder, reNoSmoothText, reNoSmoothImage, reNoSmoothPath
TRenderOptionsSet of TRenderOption

Drawing Types

TypeValues
TPdfFillModefmNone, fmAlternate, fmWinding
TPdfLineCaplcDefault, lcButt, lcRound, lcProjectingSquare
TPdfLineJoinljDefault, ljMiter, ljRound, ljBevel
TPdfBlendModebmDefault, bmMultiply, bmScreen, bmOverlay, bmDarken, bmLighten, bmColorDodge, bmColorBurn, bmHardLight, bmSoftLight, bmDifference, bmExclusion, bmHue, bmSaturation, bmColor, bmLuminosity

Annotation Types

TypeDescription
TPdfAnnotationSubtypeAnnotation subtypes: Text, Link, FreeText, Line, Square, Circle, Polygon, PolyLine, Highlight, Underline, Squiggly, StrikeOut, Stamp, Caret, Ink, Popup, FileAttachment, Sound, Movie, Widget, Screen, PrinterMark, TrapNet, Watermark, 3D, RichMedia, XFAWidget
TPdfAnnotationFlagFlags: afInvisible, afHidden, afPrint, afNoZoom, afNoRotate, afNoView, afReadOnly, afLocked, afToggleNoView
TPdfAnnotationRecord containing Subtype, Flags, Color, InteriorColor, Contents, Rectangle, and other properties

Form Types

TypeDescription
TPdfFormTypeftUnknown, ftNone, ftAcroForm, ftXfaFull, ftXfaForeground
TPdfFormFieldTypefiUnknown, fiPushButton, fiCheckBox, fiRadioButton, fiComboBox, fiListBox, fiTextField, fiSignature
TPdfFormFieldFlagffReadOnly, ffRequired, ffNoExport, and type-specific flags
TPdfFormFieldInfoRecord containing FieldType, Flags, Name, Value, AlternateName, and other properties

Record Types

TypeFields
TBookmarkHandle, Title, PageNumber, Action, ActionPageNumber
TDestinationHandle, Name, PageNumber, HasX, X, HasY, Y, HasZoom, Zoom
TLinkAnnotationHandle, Rectangle, PageNumber, Action, ActionPageNumber, ActionPath, Points
TWebLinkUrl: WString, Rectangles: TPdfRectangles
TPdfImageWidth: Integer, Height: Integer, Data: TBytes
TPdfSignatureContent: TBytes, Encoding: WString, Reason: WString, Time: WString, Permission: Integer

Global Functions

FunctionDescription
Loaded: BooleanReturns True if the PDFium library (pdfium.dll) is loaded
LoadLibraryManually load the PDFium library
UnloadLibraryUnload the PDFium library
DecodeDate(const Value: string; out DateTime: TDateTime; out DateTimeOffset: Integer): BooleanParse PDF date string to TDateTime and UTC offset
PointsToInches(Points: Double): DoubleConvert PDF points to inches
PointsToPixels(Points, PixelsPerInch: Double): DoubleConvert PDF points to pixels
PixelsToInches(Pixels, PixelsPerInch: Double): DoubleConvert pixels to inches
PixelsToPoints(Pixels, PixelsPerInch: Double): DoubleConvert pixels to PDF points

Global Variables

VariableTypeDefaultDescription
LibraryNamestring'pdfium.dll'Name of the PDFium DLL to load
EnableV8EngineBooleanFalseSet to True before loading to enable V8 JavaScript engine support

Common Usage Patterns

PDF Viewer Implementation

procedure TMainForm.OpenPDF(const FileName: string);
begin
  Pdf.FileName := FileName;
  Pdf.Active := True;
  PdfView.Pdf := Pdf;
  PdfView.Active := True;
  StatusBar1.SimpleText := Format('Loaded: %s (%d pages)',
    [ExtractFileName(FileName), Pdf.PageCount]);
end;

Create PDF with Compression

Pdf.CreateDocument;
Pdf.Compressed := True;
Pdf.Active := True;
Pdf.AddPage(0, 595, 842);
Pdf.AddText('Hello World!', 'Arial', 24, 100, 700, clBlack, $FF, 0.0);
Pdf.SaveAs('output.pdf');
Pdf.Active := False;

Text Extraction

Pdf.FileName := 'document.pdf';
Pdf.Active := True;
for I := 1 to Pdf.PageCount do
begin
  Pdf.PageNumber := I;
  Memo1.Lines.Add(Format('--- Page %d ---', [I]));
  Memo1.Lines.Add(Pdf.Text);
end;
Pdf.Active := False;

Form Field Processing

Pdf.FileName := 'form.pdf';
Pdf.Active := True;
Pdf.PageNumber := 1;
for I := 0 to Pdf.FormFieldCount - 1 do
begin
  FieldInfo := Pdf.FormFieldInfo[I];
  case FieldInfo.FieldType of
    fiTextField:
      Pdf.FormField[I] := 'New Value';
    fiCheckBox:
      Pdf.FormField[I] := 'Yes';
  end;
end;
Pdf.SaveAs('filled_form.pdf');
Pdf.Active := False;

Flatten a Filled Form

// Bake form values into permanent (non-editable) page content.
Pdf.FileName := 'form.pdf';
Pdf.Active := True;
Pdf.FormField[0] := 'John Smith';
Pdf.FormField[1] := 'Yes';
Pdf.GenerateFormAppearances;          // step 1: refresh /AP from /V
Pdf.FlattenAllPages(FLAT_NORMALDISPLAY); // step 2: flatten all pages
Pdf.SaveAs('flattened.pdf');           // step 3: save
Pdf.Active := False;