FPdfDocumentCore ne dépend que des unités RTL et de FPdfAsync ; il n’importe ni PDFium, ni FPdfView, ni VCL, LCL, Graphics ni les contrôles fenêtrés
TPdfDocumentCore possède un document natif indépendant et ses octets d’entrée ; il prend en charge les instantanés par chargement/flux, l’extraction Unicode, les dimensions de page, le rendu BGRA brut, l’insertion de pages blanches, la suppression de pages, la rotation et des octets de sauvegarde complète bornés
Utilisez l’adaptateur TPdf.CreateCoreSnapshot existant pour l’intégration avec le composant classique ; les sources TPdf et viewer existantes restent compatibles, et modifier le core renvoyé ne change pas le wrapper source
Un hôte RTL indépendant charge et initialise PDFium, fournit un TPdfCoreSymbolResolver et un propriétaire de durée de vie IInterface à BindPdfDocumentCoreRuntime, puis transmet l’IPdfDocumentCoreRuntime renvoyé aux documents du core
Le resolver lie chaque export requis avant l’ouverture du moindre document ; le propriétaire de la durée de vie doit maintenir en vie ce même module natif initialisé et sa configuration jusqu’à la libération de sa dernière référence
Le core n’initialise ni ne détruit jamais lui-même le module natif de l’appelant ; plusieurs documents peuvent partager un même runtime, et tous les handles/buffers sont libérés avant le propriétaire de la durée de vie du runtime
L’adaptateur d’instantanés du composant classique épingle le module wrapper configuré et refuse un UnloadLibrary explicite tant que ses runtimes core restent en vie ; libérez les cores avant l’arrêt de l’hôte ou de l’unité
Les appels PDFium restent synchronisés par l’appelant ; les runtimes et les documents du core n’introduisent aucun travail en arrière-plan et ne rendent pas les API natives thread-safe
LoadBytes copie les octets sources et n’accepte le nouveau document qu’après les contrôles natifs de chargement et de pages/formulaires ; une entrée invalide ou une annulation conserve le document actif précédent
LoadStream lit l’intégralité du flux depuis la position zéro dans la limite du budget d’entrée et restaure la position d’origine avant d’accepter le document de remplacement ; LoadFile ouvre un fichier en refusant le partage en écriture et délègue à LoadStream
Les mots de passe sont des chaînes d’octets UTF-8 natives explicites sans null incorporé ; Password et SecurityHandlerRevision inspectent l’état de sécurité du document actif, SaveBytes(RemoveSecurity) préserve ou retire le chiffrement à la sauvegarde, et InsertBlankPage, DeletePage et RotatePage préservent le chiffrement des documents protégés par mot de passe tout en rejetant les documents signés
L’initialisation XFA, l’UI hôte JavaScript, les superpositions de remplissage de formulaires et l’édition des widgets restent à la charge du composant classique ; le rendu du core dessine le contenu natif des pages et les annotations ordinaires sans environnement de remplissage de formulaires
Tous les indices de page commencent à zéro ; PageText renvoie le texte UTF-16 natif réel, espaces générés par l’extraction compris, sous les limites à la fois de caractères natifs et d’unités de sortie UTF-16, GetMetaText lit les balises standard du dictionnaire Info (Title, Author, Subject, Keywords, Creator, Producer, CreationDate ou ModDate par exemple) comme texte UTF-16 borné, GetPageLabel lit la chaîne d’étiquette de la page (indice base zéro), et GetFileVersion, GetDocPermissions et GetUserPermissions inspectent la version d’en-tête PDF (17 pour PDF 1.7 par exemple) et les masques de bits de permissions
GetMediaBox, GetCropBox, GetTrimBox, GetBleedBox, GetArtBox et GetPageBoundingBox lisent les boîtes englobantes de page dans un TPdfCoreBox (Left, Bottom, Right, Top), en renvoyant False quand une boîte est absente ; SetMediaBox, SetCropBox, SetTrimBox, SetBleedBox et SetArtBox valident des dimensions finies et positives puis mettent à jour la page cible dans le pipeline d’édition par étapes, et FlattenPage aplanit les annotations ou widgets de page dans ce pipeline (en renvoyant 1 si aplanissement ou 2 si rien à aplanir)
ImportPages importe toutes les pages ou une plage de pages PDFium en base 1 (1,3-5 par exemple) et ImportPagesByIndex importe un tableau explicite d’indices de pages sources en base zéro depuis un autre TPdfDocumentCore actif sans formulaires, à un indice d’insertion en base zéro (ou en appendice à -1), dans le pipeline d’édition par étapes et sous les budgets MaxPages et d’octets
GetBookmarks parcourt la hiérarchie des signets du document avec protection contre les cycles, en renvoyant des éléments TPdfCoreBookmarks avec Title, Depth en base zéro, ChildCount, IsOpen, TargetPageIndex en base zéro (ou -1) et ActionUri ; GetAttachmentCount, GetAttachmentInfo, AddAttachment et DeleteAttachment inspectent et modifient les pièces jointes incorporées dans le pipeline d’édition par étapes ; GetSignatureCount et GetSignatureInfo inspectent les objets de signature numérique (SubFilter, Time, Reason, DocMDPPermission, ByteRange et Contents) ; GetPageCharCount, GetPageCharUnicode, GetPageCharBox et FindPageText exposent les points de code par caractère, les boîtes englobantes en espace utilisateur et les correspondances de recherche de sous-chaînes ; et SaveBytesWithVersion, SaveToStream et SaveToFile exportent des instantanés non incrémentaux avec substitution optionnelle de la version d’en-tête PDF (10..20)
L’édition de pages exige un document sans formulaires interactifs ; l’édition consciente des formulaires reste dans le wrapper classique
InsertBlankPage, DeletePage et RotatePage opèrent dans une étape privée de sauvegarde complète/réouverture et ne remplacent le document actif qu’une fois les contrôles natifs de géométrie et de comptage ainsi que les vérifications d’annulation passés
SaveBytes renvoie un instantané non incrémental ; les callbacks natifs d’écriture appliquent le budget de sortie et interceptent les exceptions des callbacks au lieu de laisser des exceptions Pascal franchir la frontière C
RenderPage renvoie un TPdfCorePixels avec des octets BGRA natifs bord à bord de haut en bas, Width, Height et Stride ; Stride vaut Width fois quatre et aucun objet bitmap/canvas n’est créé
L’arrière-plan est une valeur ARGB compacte, blanc opaque par défaut ; Rotation vaut 0 à 3 quarts de tour, et le profil de rendu inclut les annotations ordinaires
Les opérations natives masquent temporairement les traps en virgule flottante et effacent les indicateurs d’exception natifs en attente avant de restaurer le masque d’exceptions d’origine de l’appelant ; cela permet des opérations de polices natives valides sous FPC sans modifier durablement la politique de traps de l’appelant
TPdfDocumentCoreOptions.Default autorise 128 MiB d’entrée/sortie, 10 000 pages, 16 777 216 caractères natifs/unités de sortie UTF-16 et 16 777 216 pixels de rendu
Les maximums absolus sont 512 MiB d’entrée/sortie, 100 000 pages, 16 777 216 caractères/unités de sortie UTF-16, 268 435 456 pixels sous réserve de la taille de buffer signée, et 32 768 points/pixels par page insérée/dimension de rendu
L’annulation coopérative est vérifiée autour des appels natifs et dans les callbacks d’écriture ; les internals natifs de chargement, de texte et de rendu ne sont pas interrompus en plein appel
La sonde RTL autonome passe sur Delphi et FPC Win64 avec la DLL de remplacement déclarée ; le pont wrapper/viewer du composant classique est qualifié séparément sur Delphi Win64, les autres plateformes conservant leurs limites de qualification documentées
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;