FPdfDocumentCore relies solely on RTL units and FPdfAsync; it does not pull in PDFium, FPdfView, VCL, LCL, Graphics or window controls
TPdfDocumentCore holds its own independent native document together with the input bytes behind it; it covers load/stream snapshots, Unicode extraction, page dimensions, raw BGRA rendering, blank-page insertion, page deletion, rotation and bounded full-save bytes
When integrating with the classic component, go through the existing TPdf.CreateCoreSnapshot adapter; TPdf and viewer source keeps working as before, and edits made through the returned core leave the source wrapper alone
A separate RTL host loads and initialises PDFium, hands a TPdfCoreSymbolResolver and an IInterface lifetime owner to BindPdfDocumentCoreRuntime, and then passes the resulting IPdfDocumentCoreRuntime to core documents
Every required export is bound by the resolver before the first document is opened; the lifetime owner has to keep that same initialised native module and its configuration alive until the final reference goes away
The core never initialises or tears down a caller's native module by itself; several documents may share a single runtime, and every handle/buffer is freed before the runtime's lifetime owner
The classic snapshot adapter keeps the configured wrapper module pinned and turns away explicit UnloadLibrary calls whilst its core runtimes are still alive; free the cores ahead of host or unit shutdown
PDFium calls stay the caller's synchronisation responsibility; neither runtimes nor core documents introduce background work or make the native APIs thread-safe
LoadBytes takes a copy of the source bytes and only accepts the new document once native loading and the page/form checks have passed; invalid input or cancellation leaves the previous active document in place
LoadStream reads the entire stream from offset zero within the input budget and puts the original position back before the replacement document is accepted; LoadFile opens a file with write sharing denied and hands over to LoadStream
Passwords are explicit native UTF-8 byte strings with no embedded nulls; Password and SecurityHandlerRevision inspect the active document's security state, SaveBytes(RemoveSecurity) preserves or strips encryption when saving, and InsertBlankPage, DeletePage and RotatePage keep encryption on password-protected documents whilst rejecting signed ones
XFA initialisation, the JavaScript host UI, form-fill overlays and widget editing stay with the classic component; core rendering draws native page content and ordinary annotations with no form-fill environment
Every page index is zero-based; PageText hands back genuine native UTF-16 text, generated extraction whitespace included, subject to the native-character and UTF-16 output limits alike, GetMetaText reads standard Info dictionary tags (such as Title, Author, Subject, Keywords, Creator, Producer, CreationDate and ModDate) as bounded UTF-16 text, GetPageLabel reads the zero-based page's label string, and GetFileVersion, GetDocPermissions and GetUserPermissions inspect the PDF header version (such as 17 for PDF 1.7) and the permission bitmasks
GetMediaBox, GetCropBox, GetTrimBox, GetBleedBox, GetArtBox and GetPageBoundingBox read page bounding boxes into TPdfCoreBox (Left, Bottom, Right, Top), returning False when a box is absent; SetMediaBox, SetCropBox, SetTrimBox, SetBleedBox and SetArtBox check the box dimensions are finite and positive before updating the target page in the staged edit pipeline, and FlattenPage flattens page annotations or widgets in that same pipeline (returning 1 when something was flattened or 2 when nothing needed flattening)
ImportPages imports all pages or a 1-based PDFium page range string (such as 1,3-5) and ImportPagesByIndex imports an explicit array of zero-based source page indices from another active non-form TPdfDocumentCore at a zero-based insertion index (or appends at -1), all inside the staged edit pipeline and subject to MaxPages and the byte budgets
GetBookmarks walks the document outline hierarchy with cycle protection, returning TPdfCoreBookmarks items with Title, zero-based Depth, ChildCount, IsOpen, zero-based TargetPageIndex (or -1) and ActionUri; GetAttachmentCount, GetAttachmentInfo, AddAttachment and DeleteAttachment inspect and modify embedded file attachments in the staged edit pipeline; GetSignatureCount and GetSignatureInfo inspect digital signature objects (SubFilter, Time, Reason, DocMDPPermission, ByteRange and Contents); GetPageCharCount, GetPageCharUnicode, GetPageCharBox and FindPageText expose per-character codepoints, user-space bounding boxes and substring search matches; and SaveBytesWithVersion, SaveToStream and SaveToFile export nonincremental snapshots with an optional PDF header version override (10..20)
Page edits call for a document with no interactive forms; form-aware editing stays in the classic wrapper
InsertBlankPage, DeletePage and RotatePage run through a private full-save/reopen stage and only swap the active document once the native geometry/count and cancellation checks have all passed
SaveBytes gives back a nonincremental snapshot; the native writer callbacks police the output budget and catch callback exceptions so that Pascal exceptions never cross the C boundary
RenderPage hands back TPdfCorePixels holding tightly packed top-down native BGRA bytes together with Width, Height and Stride; Stride works out as Width times four, and no bitmap/canvas object is ever created
The background is a packed ARGB value, opaque white by default; Rotation takes 0 through 3 quarter turns, and the render profile takes in ordinary annotations
Native operations mask floating-point traps for the duration and clear the native pending exception flags before the caller's original exception mask is put back; that is what lets valid native font operations run under FPC without permanently altering the caller's trap policy
TPdfDocumentCoreOptions.Default permits 128 MiB of input/output, 10,000 pages, 16,777,216 native characters/UTF-16 output units and 16,777,216 render pixels
The hard maxima come to 512 MiB of input/output, 100,000 pages, 16,777,216 characters/UTF-16 output units, 268,435,456 pixels subject to signed buffer size, and 32,768 points/pixels for each inserted page/render dimension
Cooperative cancellation is polled around native calls and inside writer callbacks; the internals of native load, text and render work are not interrupted mid-call
The standalone RTL probe passes on Delphi and FPC Win64 with the declared replacement DLL; the classic wrapper/viewer bridge is qualified separately on Delphi Win64, and other platforms keep their documented qualification limits
uses SysUtils, Classes, FPdfAsync;
type
EPdfDocumentCore=class(Exception);
{$IFDEF MSWINDOWS}
TPdfCoreUnsignedLong=Cardinal;
{$ELSE}
TPdfCoreUnsignedLong=NativeUInt;
{$ENDIF}
TPdfCoreSymbolResolver=function(const Name:AnsiString):Pointer of object;
TPdfCoreLoadMemory=function(Data:Pointer; Size:NativeUInt; Password:PAnsiChar):Pointer; cdecl;
TPdfCoreClose=procedure(Handle:Pointer); cdecl;
TPdfCoreCount=function(Handle:Pointer):Integer; cdecl;
TPdfCoreLoadPage=function(Document:Pointer; Index:Integer):Pointer; cdecl;
TPdfCoreDimension=function(Page:Pointer):Single; cdecl;
TPdfCoreTextPage=function(Page:Pointer):Pointer; cdecl;
TPdfCoreReadText=function(TextPage:Pointer; Start,Count:Integer; Buffer:PWideChar):Integer; cdecl;
TPdfCoreBitmapCreate=function(Width,Height,Format:Integer; Buffer:Pointer; Stride:Integer):Pointer; cdecl;
TPdfCoreBitmapFill=function(Bitmap:Pointer; Left,Top,Width,Height:Integer; Color:TPdfCoreUnsignedLong):Integer; cdecl;
TPdfCoreRender=procedure(Bitmap,Page:Pointer; X,Y,Width,Height,Rotation,Flags:Integer); cdecl;
TPdfCoreLastError=function:TPdfCoreUnsignedLong; cdecl;
PPdfCoreFileWrite=^TPdfCoreFileWrite;
TPdfCoreWriteBlock=function(Self:PPdfCoreFileWrite; Buffer:Pointer; Size:TPdfCoreUnsignedLong):Integer; cdecl;
TPdfCoreFileWrite=record
Version:Integer;
WriteBlock:TPdfCoreWriteBlock;
end;
TPdfCoreSave=function(Document:Pointer; Writer:PPdfCoreFileWrite; Flags:TPdfCoreUnsignedLong):Integer; cdecl;
TPdfCoreNewDocument=function:Pointer; cdecl;
TPdfCoreNewPage=function(Document:Pointer; Index:Integer; Width,Height:Double):Pointer; cdecl;
TPdfCoreDeletePage=procedure(Document:Pointer; Index:Integer); cdecl;
TPdfCoreRotatePage=procedure(Page:Pointer; Rotation:Integer); cdecl;
TPdfCoreMetaText=function(Document:Pointer; Tag:PAnsiChar; Buffer:PWideChar; BufferLen:TPdfCoreUnsignedLong):TPdfCoreUnsignedLong; cdecl;
TPdfCorePageLabel=function(Document:Pointer; PageIndex:Integer; Buffer:PWideChar; BufferLen:TPdfCoreUnsignedLong):TPdfCoreUnsignedLong; cdecl;
TPdfCoreFileVersion=function(Document:Pointer; var FileVersion:Integer):Integer; cdecl;
TPdfCorePermissions=function(Document:Pointer):TPdfCoreUnsignedLong; cdecl;
TPdfCoreGetPageBox=function(Page:Pointer; var Left,Bottom,Right,Top:Single):Integer; cdecl;
TPdfCoreSetPageBox=procedure(Page:Pointer; Left,Bottom,Right,Top:Single); cdecl;
TPdfCoreRectF=record Left,Top,Right,Bottom:Single end;
TPdfCoreGetPageBoundingBox=function(Page:Pointer; var Rect:TPdfCoreRectF):Integer; cdecl;
TPdfCoreFlattenPage=function(Page:Pointer; Flag:Integer):Integer; cdecl;
TPdfCoreImportPages=function(DestDoc,SrcDoc:Pointer; PageRange:PAnsiChar; Index:Integer):Integer; cdecl;
TPdfCoreImportPagesByIndex=function(DestDoc,SrcDoc:Pointer; PageIndices:PInteger; Length:TPdfCoreUnsignedLong; Index:Integer):Integer; cdecl;
TPdfCoreSaveWithVersion=function(Document:Pointer; Writer:PPdfCoreFileWrite; Flags:TPdfCoreUnsignedLong; FileVersion:Integer):Integer; cdecl;
TPdfCoreBookmarkRel=function(Document,Handle:Pointer):Pointer; cdecl;
TPdfCoreBufferRead=function(Handle,Buffer:Pointer; BufferLen:TPdfCoreUnsignedLong):TPdfCoreUnsignedLong; cdecl;
TPdfCoreActionUriPath=function(Document,Action,Buffer:Pointer; BufferLen:TPdfCoreUnsignedLong):TPdfCoreUnsignedLong; cdecl;
TPdfCoreDestPageIndex=function(Document,Dest:Pointer):Integer; cdecl;
TPdfCoreAddAttachment=function(Document:Pointer; Name:PWideChar):Pointer; cdecl;
TPdfCoreDeleteAttachment=function(Document:Pointer; Index:Integer):Integer; cdecl;
TPdfCoreAttachmentSetFile=function(Attachment,Document,Contents:Pointer; Len:TPdfCoreUnsignedLong):Integer; cdecl;
TPdfCoreAttachmentGetFile=function(Attachment,Buffer:Pointer; BufferLen:TPdfCoreUnsignedLong; var OutBufLen:TPdfCoreUnsignedLong):Integer; cdecl;
TPdfCoreTextUnicode=function(TextPage:Pointer; Index:Integer):Cardinal; cdecl;
TPdfCoreTextCharBox=function(TextPage:Pointer; Index:Integer; var Left,Right,Bottom,Top:Double):Integer; cdecl;
TPdfCoreTextFindStart=function(TextPage:Pointer; FindWhat:PWideChar; Flags:TPdfCoreUnsignedLong; StartIndex:Integer):Pointer; cdecl;
TPdfCoreSigByteRange=function(Signature:Pointer; Buffer:PInteger; Length:TPdfCoreUnsignedLong):TPdfCoreUnsignedLong; cdecl;
TPdfCoreSigPermission=function(Signature:Pointer):Cardinal; cdecl;
TPdfCoreApi=record
LoadMemory:TPdfCoreLoadMemory;
CloseDocument,ClosePage,CloseTextPage,DestroyBitmap,TextFindClose:TPdfCoreClose;
PageCount,CharacterCount,FormType,SignatureCount,SecurityRevision,PageRotation,
BookmarkGetCount,AttachmentCount,TextFindNext,TextGetSchResultIndex,TextGetSchCount:TPdfCoreCount;
LoadPage,GetAttachment,GetSignatureObject:TPdfCoreLoadPage;
PageWidth,PageHeight:TPdfCoreDimension;
LoadTextPage,BookmarkGetAction:TPdfCoreTextPage;
ReadText:TPdfCoreReadText;
CreateBitmap:TPdfCoreBitmapCreate;
FillBitmap:TPdfCoreBitmapFill;
Render:TPdfCoreRender;
LastError:TPdfCoreLastError;
Save:TPdfCoreSave;
SaveWithVersion:TPdfCoreSaveWithVersion;
NewDocument:TPdfCoreNewDocument;
NewPage:TPdfCoreNewPage;
DeletePage:TPdfCoreDeletePage;
RotatePage:TPdfCoreRotatePage;
MetaText,AttachmentGetStringValue:TPdfCoreMetaText;
PageLabel:TPdfCorePageLabel;
FileVersion:TPdfCoreFileVersion;
DocPermissions,UserPermissions,ActionGetType:TPdfCorePermissions;
GetMediaBox,GetCropBox,GetTrimBox,GetBleedBox,GetArtBox:TPdfCoreGetPageBox;
SetMediaBox,SetCropBox,SetTrimBox,SetBleedBox,SetArtBox:TPdfCoreSetPageBox;
GetPageBoundingBox:TPdfCoreGetPageBoundingBox;
FlattenPage:TPdfCoreFlattenPage;
ImportPages:TPdfCoreImportPages;
ImportPagesByIndex:TPdfCoreImportPagesByIndex;
BookmarkGetFirstChild,BookmarkGetNextSibling,BookmarkGetDest,ActionGetDest:TPdfCoreBookmarkRel;
BookmarkGetTitle,AttachmentGetName,SigGetContents,SigGetSubFilter,SigGetReason,SigGetTime:TPdfCoreBufferRead;
ActionGetUriPath:TPdfCoreActionUriPath;
DestGetPageIndex:TPdfCoreDestPageIndex;
AddAttachment:TPdfCoreAddAttachment;
DeleteAttachment:TPdfCoreDeleteAttachment;
AttachmentSetFile:TPdfCoreAttachmentSetFile;
AttachmentGetFile:TPdfCoreAttachmentGetFile;
TextGetUnicode:TPdfCoreTextUnicode;
TextGetCharBox:TPdfCoreTextCharBox;
TextFindStart:TPdfCoreTextFindStart;
SigGetByteRange:TPdfCoreSigByteRange;
SigGetDocMDPPermission:TPdfCoreSigPermission;
end;
IPdfDocumentCoreRuntime=interface
['{92C8C1EB-5EE2-437D-A2A1-EF50DBB30A68}']
function Api:TPdfCoreApi;
end;
TPdfDocumentCoreOptions=record
MaxDocumentBytes,MaxOutputBytes,MaxPages,MaxCharacters,MaxRenderPixels:Integer;
CancellationToken:IPdfCancellationToken;
class function Default:TPdfDocumentCoreOptions; static;
end;
TPdfCorePageSize=record Width,Height:Double end;
TPdfCoreBox=record Left,Bottom,Right,Top:Double end;
TPdfCorePixels=record
Width,Height,Stride:Integer;
Samples:TBytes;
end;
TPdfCoreBookmarkInfo=record
Title:WideString;
Depth,ChildCount,TargetPageIndex:Integer;
IsOpen:Boolean;
ActionUri:AnsiString;
end;
TPdfCoreBookmarks=array of TPdfCoreBookmarkInfo;
TPdfCoreAttachmentInfo=record
Name,CreationDate,ModificationDate,Checksum:WideString;
Data:TBytes;
end;
TPdfCoreTextMatch=record
StartIndex,Count:Integer;
end;
TPdfCoreTextMatches=array of TPdfCoreTextMatch;
TPdfCoreSignatureInfo=record
SubFilter,Time:AnsiString;
Reason:WideString;
DocMDPPermission:Cardinal;
ByteRange:array of Integer;
Contents:TBytes;
end;
TPdfDocumentCore=class
private
FRuntime:IPdfDocumentCoreRuntime;
FApi:TPdfCoreApi;
FOptions:TPdfDocumentCoreOptions;
FDocument:Pointer;
FSource:TBytes;
procedure Check;
procedure RequireActive;
function GetActive:Boolean;
function GetPageCount:Integer;
function OpenPage(Index:Integer):Pointer;
procedure AcceptDocument(Document:Pointer; const Source:TBytes);
procedure ChangePage(Kind,Index,QuarterTurns:Integer; Width,Height:Double);
procedure ChangePageBox(IsCrop:Boolean; Index:Integer; const Box:TPdfCoreBox);
public
constructor Create(const Runtime:IPdfDocumentCoreRuntime; const Options:TPdfDocumentCoreOptions);
destructor Destroy; override;
procedure Close;
procedure LoadBytes(const Data:TBytes; const Password:AnsiString='');
procedure LoadStream(Source:TStream; const Password:AnsiString='');
procedure LoadFile(const FileName:string; const Password:AnsiString='');
procedure NewDocument;
function GetMetaText(const Tag:AnsiString):WideString;
function GetPageLabel(Index:Integer):WideString;
function GetFileVersion:Integer;
function GetDocPermissions:Cardinal;
function GetUserPermissions:Cardinal;
function GetBookmarks:TPdfCoreBookmarks;
function GetAttachmentCount:Integer;
function GetAttachmentInfo(Index:Integer):TPdfCoreAttachmentInfo;
procedure AddAttachment(const Name:WideString; const Data:TBytes);
procedure DeleteAttachment(Index:Integer);
function GetSignatureCount:Integer;
function GetSignatureInfo(Index:Integer):TPdfCoreSignatureInfo;
function PageSize(Index:Integer):TPdfCorePageSize;
function GetMediaBox(Index:Integer; out Box:TPdfCoreBox):Boolean;
procedure SetMediaBox(Index:Integer; const Box:TPdfCoreBox);
function GetCropBox(Index:Integer; out Box:TPdfCoreBox):Boolean;
procedure SetCropBox(Index:Integer; const Box:TPdfCoreBox);
function GetTrimBox(Index:Integer; out Box:TPdfCoreBox):Boolean;
procedure SetTrimBox(Index:Integer; const Box:TPdfCoreBox);
function GetBleedBox(Index:Integer; out Box:TPdfCoreBox):Boolean;
procedure SetBleedBox(Index:Integer; const Box:TPdfCoreBox);
function GetArtBox(Index:Integer; out Box:TPdfCoreBox):Boolean;
procedure SetArtBox(Index:Integer; const Box:TPdfCoreBox);
function GetPageBoundingBox(Index:Integer; out Box:TPdfCoreBox):Boolean;
function FlattenPage(Index:Integer; ForPrint:Boolean=False):Integer;
function PageText(Index:Integer):WideString;
function GetPageCharCount(Index:Integer):Integer;
function GetPageCharUnicode(Index,CharIndex:Integer):Cardinal;
function GetPageCharBox(Index,CharIndex:Integer; out Box:TPdfCoreBox):Boolean;
function FindPageText(Index:Integer; const Pattern:WideString;
MatchCase:Boolean=False; MatchWholeWord:Boolean=False):TPdfCoreTextMatches;
function RenderPage(Index,Width,Height:Integer; Rotation:Integer=0;
Background:Cardinal=$FFFFFFFF):TPdfCorePixels;
procedure InsertBlankPage(Index:Integer; Width,Height:Double);
procedure DeletePage(Index:Integer);
procedure RotatePage(Index,QuarterTurns:Integer);
procedure ImportPages(Source:TPdfDocumentCore; const PageRange:AnsiString=''; InsertIndex:Integer=-1);
procedure ImportPagesByIndex(Source:TPdfDocumentCore; const PageIndices:array of Integer; InsertIndex:Integer=-1);
function SaveBytes(RemoveSecurity:Boolean=False):TBytes;
function SaveBytesWithVersion(FileVersion:Integer; RemoveSecurity:Boolean=False):TBytes;
procedure SaveToStream(Dest:TStream; RemoveSecurity:Boolean=False; FileVersion:Integer=0);
procedure SaveToFile(const FileName:string; RemoveSecurity:Boolean=False; FileVersion:Integer=0);
property Active:Boolean read GetActive;
property PageCount:Integer read GetPageCount;
property SecurityHandlerRevision:Integer read GetSecurityHandlerRevision;
property Password:AnsiString read FPassword;
end;
// The lifetime object owns an already initialized native library
// The runtime pins it until every core document releases its reference
function BindPdfDocumentCoreRuntime(Resolver:TPdfCoreSymbolResolver;
const Lifetime:IInterface):IPdfDocumentCoreRuntime;