PDFium Delphi Component Docs

Core documentale indipendente dal framework

FPdfDocumentCore dipende solo da unit RTL e da FPdfAsync; non importa PDFium, FPdfView, VCL, LCL, Graphics né controlli finestra

TPdfDocumentCore possiede un documento nativo indipendente e i suoi byte di input; supporta snapshot da load/stream, estrazione Unicode, dimensioni di pagina, rendering BGRA raw, inserimento di pagine vuote, eliminazione di pagine, rotazione e byte di full-save limitati

Per integrarti con il componente classico usa l'adattatore esistente TPdf.CreateCoreSnapshot; le sorgenti TPdf e viewer esistenti restano compatibili, e modificare il core restituito non cambia il wrapper di origine

Host nativo e lifetime

Un host RTL indipendente carica e inizializza PDFium, fornisce un TPdfCoreSymbolResolver e un proprietario di lifetime IInterface a BindPdfDocumentCoreRuntime, quindi passa l'IPdfDocumentCoreRuntime restituito ai documenti core

Il resolver collega ogni export richiesto prima che venga aperto un qualsiasi documento; il proprietario del lifetime deve mantenere in vita quello stesso modulo nativo inizializzato e la sua configurazione finché l'ultimo riferimento non viene rilasciato

Il core non inizializza né distrugge mai da sé il modulo nativo del chiamante; più documenti possono condividere uno stesso runtime, e tutti gli handle/buffer vengono rilasciati prima del proprietario del lifetime del runtime

L'adattatore di snapshot classico aggancia il modulo wrapper configurato e rifiuta un UnloadLibrary esplicito finché i suoi runtime core restano in vita; rilascia i core prima dello shutdown di host/unit

Le chiamate PDFium restano sincronizzate dal chiamante; runtime e documenti core non introducono lavoro in background né rendono thread-safe le API native

Operazioni sul documento

LoadBytes copia i byte sorgente e accetta il nuovo documento solo dopo i controlli nativi di caricamento e di pagina/form; input non valido o annullamento preservano il documento attivo precedente

LoadStream legge l'intero stream dall'offset zero entro il budget di input e ripristina la posizione originale prima di accettare il documento sostitutivo; LoadFile apre un file negando la condivisione in scrittura e delega a LoadStream

Le password sono stringhe di byte UTF-8 native esplicite senza null incorporati; Password e SecurityHandlerRevision ispezionano lo stato di sicurezza del documento attivo, SaveBytes(RemoveSecurity) conserva o rimuove la cifratura al salvataggio, e InsertBlankPage, DeletePage e RotatePage preservano la cifratura sui documenti protetti da password rifiutando i documenti firmati

L'inizializzazione XFA, la UI host JavaScript, gli overlay di form-fill e la modifica dei widget restano responsabilità del componente classico; il rendering core disegna il contenuto nativo di pagina e le annotazioni regolari senza un ambiente di form-fill

Tutti gli indici di pagina sono a base zero; PageText restituisce testo UTF-16 nativo reale, inclusi gli spazi generati dall'estrazione, entro i limiti sia di caratteri nativi sia di unità di output UTF-16, GetMetaText legge i tag standard del dizionario Info (come Title, Author, Subject, Keywords, Creator, Producer, CreationDate e ModDate) come testo UTF-16 limitato, GetPageLabel legge la stringa di etichetta della pagina a base zero, e GetFileVersion, GetDocPermissions e GetUserPermissions ispezionano la versione dell'header PDF (come 17 per PDF 1.7) e le maschere di bit dei permessi

GetMediaBox, GetCropBox, GetTrimBox, GetBleedBox, GetArtBox e GetPageBoundingBox leggono i box di pagina in TPdfCoreBox (Left, Bottom, Right, Top), restituendo False quando un box è assente; SetMediaBox, SetCropBox, SetTrimBox, SetBleedBox e SetArtBox validano dimensioni di box finite e positive e aggiornano la pagina obiettivo nella pipeline di modifica in staging, e FlattenPage appiattisce le annotazioni o i widget di pagina nella pipeline di modifica in staging (restituendo 1 quando appiattisce o 2 quando nulla richiedeva appiattimento)

ImportPages importa tutte le pagine o un intervallo di pagine PDFium 1-based (come 1,3-5) e ImportPagesByIndex importa un array esplicito di indici di pagine sorgente zero-based da un altro TPdfDocumentCore attivo senza form, a un indice di inserimento zero-based (o accoda con -1) dentro la pipeline di modifica in staging, rispettando MaxPages e i budget di byte

GetBookmarks attraversa la gerarchia dell'outline del documento con protezione dai cicli, restituendo voci TPdfCoreBookmarks con Title, Depth a base zero, ChildCount, IsOpen, TargetPageIndex a base zero (o -1) e ActionUri; GetAttachmentCount, GetAttachmentInfo, AddAttachment e DeleteAttachment ispezionano e modificano gli allegati file incorporati nella pipeline di modifica in staging; GetSignatureCount e GetSignatureInfo ispezionano gli oggetti di firma digitale (SubFilter, Time, Reason, DocMDPPermission, ByteRange e Contents); GetPageCharCount, GetPageCharUnicode, GetPageCharBox e FindPageText espongono codepoint per carattere, box in spazio utente e corrispondenze di ricerca di sottostringhe; e SaveBytesWithVersion, SaveToStream e SaveToFile esportano snapshot non incrementali con override opzionale della versione dell'header PDF (10..20)

Le modifiche di pagina richiedono un documento senza form interattivi; la modifica consapevole dei form resta nel wrapper classico

InsertBlankPage, DeletePage e RotatePage lavorano in una fase privata di full-save/reopen e sostituiscono il documento attivo solo dopo che passano i controlli nativi di geometria/conteggio e i controlli di annullamento

SaveBytes restituisce uno snapshot non incrementale; le callback native di scrittura fanno rispettare il budget di output e catturano le eccezioni delle callback invece di lasciare che eccezioni Pascal attraversino il confine C

Pixel raw e stato floating-point

RenderPage restituisce TPdfCorePixels con byte BGRA nativi compattati dall'alto verso il basso, Width, Height e Stride; Stride è Width per quattro e non viene creato alcun oggetto bitmap/canvas

Background è un valore ARGB compattato, bianco opaco per impostazione predefinita; Rotation va da 0 a 3 quarti di giro, e il profilo di rendering include le annotazioni regolari

Le operazioni native mascherano temporaneamente i trap floating-point e azzerano i flag nativi di eccezione pendente prima di ripristinare la maschera di eccezione originale del chiamante; questo consente operazioni native sui font valide sotto FPC senza cambiare in modo permanente la politica di trap del chiamante

Limiti finiti e qualifica

TPdfDocumentCoreOptions.Default consente 128 MiB di input/output, 10,000 pagine, 16,777,216 caratteri nativi/unità di output UTF-16 e 16,777,216 pixel di rendering

I massimi assoluti sono 512 MiB di input/output, 100,000 pagine, 16,777,216 caratteri/unità di output UTF-16, 268,435,456 pixel entro la dimensione con segno del buffer, e 32,768 punti/pixel per dimensione di pagina inserita e di rendering

L'annullamento cooperativo viene verificato attorno alle chiamate native e dentro le callback di scrittura; gli interni nativi di load, testo e rendering non vengono interrotti a metà chiamata

La probe RTL standalone passa su Delphi e FPC Win64 con la DLL di sostituzione dichiarata; il bridge classico wrapper/viewer viene qualificato separatamente su Delphi Win64, e le altre piattaforme conservano i loro limiti di qualifica documentati

Dichiarazioni pubbliche

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;