FPdfDocumentCore depende solo de unidades RTL y de FPdfAsync; no importa PDFium, FPdfView, VCL, LCL, Graphics ni controles de ventana
TPdfDocumentCore es dueño de un documento nativo independiente y de sus bytes de entrada; soporta instantáneas de carga/stream, extracción Unicode, dimensiones de página, renderizado BGRA directo, inserción de páginas en blanco, borrado de páginas, rotación y guardado completo de bytes acotado
Use el adaptador existente TPdf.CreateCoreSnapshot para integrarse con el componente clásico; el código fuente existente de TPdf y del viewer sigue siendo compatible, y editar el core devuelto no cambia el wrapper de origen
Un host RTL independiente carga e inicializa PDFium, suministra un TPdfCoreSymbolResolver y un dueño de tiempo de vida IInterface a BindPdfDocumentCoreRuntime, y luego pasa el IPdfDocumentCoreRuntime devuelto a los documentos core
El resolver vincula cada export requerido antes de abrir cualquier documento; el dueño del tiempo de vida debe mantener vivo ese mismo módulo nativo inicializado y su configuración hasta que se libere su última referencia
El core nunca inicializa ni destruye por sí mismo el módulo nativo de quien llama; varios documentos pueden compartir un runtime, y todos los handles/buffers se liberan antes que el dueño del tiempo de vida del runtime
El adaptador clásico de instantáneas fija el módulo wrapper configurado y rechaza un UnloadLibrary explícito mientras sus runtimes core sigan vivos; libere los cores antes del shutdown del host o de la unidad
Las llamadas a PDFium siguen sincronizadas por quien llama; los runtimes y los documentos core no introducen trabajo en segundo plano ni hacen thread-safe las API nativas
LoadBytes copia los bytes de origen y acepta el nuevo documento solo después de las verificaciones nativas de carga y de página/formulario; una entrada inválida o una cancelación conservan el documento activo anterior
LoadStream lee el stream completo desde el offset cero bajo el presupuesto de entrada y restaura la posición original antes de aceptar el documento de reemplazo; LoadFile abre un archivo con la compartición de escritura denegada y delega en LoadStream
Las contraseñas son cadenas de bytes UTF-8 nativas explícitas sin nulls incrustados; Password y SecurityHandlerRevision inspeccionan el estado de seguridad del documento activo, SaveBytes(RemoveSecurity) preserva o elimina el cifrado al guardar, y InsertBlankPage, DeletePage y RotatePage preservan el cifrado en documentos protegidos por contraseña mientras rechazan los documentos firmados
La inicialización de XFA, la UI del host de JavaScript, los overlays de llenado de formularios y la edición de widgets siguen siendo responsabilidad del componente clásico; el renderizado del core dibuja el contenido nativo de la página y las anotaciones regulares sin un entorno de llenado de formularios
Todos los índices de página son base cero; PageText devuelve texto UTF-16 nativo real, incluidos los espacios de extracción generados, bajo los límites tanto de caracteres nativos como de unidades de salida UTF-16, GetMetaText lee los tags estándar del diccionario Info (como Title, Author, Subject, Keywords, Creator, Producer, CreationDate y ModDate) como texto UTF-16 acotado, GetPageLabel lee el string de etiqueta de la página contada desde cero, y GetFileVersion, GetDocPermissions y GetUserPermissions inspeccionan la versión del header PDF (como 17 para PDF 1.7) y las máscaras de bits de permisos
GetMediaBox, GetCropBox, GetTrimBox, GetBleedBox, GetArtBox y GetPageBoundingBox leen los bounding boxes de página en TPdfCoreBox (Left, Bottom, Right, Top), devolviendo False cuando una caja está ausente; SetMediaBox, SetCropBox, SetTrimBox, SetBleedBox y SetArtBox validan dimensiones de caja finitas y positivas y actualizan la página destino en el pipeline de edición por etapas, y FlattenPage aplana anotaciones de página o widgets en el pipeline de edición por etapas (devolviendo 1 cuando aplanó o 2 cuando nada necesitó aplanado)
ImportPages importa todas las páginas o un string de rango de páginas PDFium contado desde uno (como 1,3-5) y ImportPagesByIndex importa un arreglo explícito de índices de páginas de origen base cero desde otro TPdfDocumentCore activo sin formularios, en un índice de inserción base cero (o agrega al final con -1) dentro del pipeline de edición por etapas mientras aplica MaxPages y los presupuestos de bytes
GetBookmarks recorre la jerarquía de outlines del documento con protección contra ciclos, devolviendo elementos TPdfCoreBookmarks con Title, Depth base cero, ChildCount, IsOpen, TargetPageIndex base cero (o -1) y ActionUri; GetAttachmentCount, GetAttachmentInfo, AddAttachment y DeleteAttachment inspeccionan y modifican adjuntos de archivos incrustados en el pipeline de edición por etapas; GetSignatureCount y GetSignatureInfo inspeccionan objetos de firma digital (SubFilter, Time, Reason, DocMDPPermission, ByteRange y Contents); GetPageCharCount, GetPageCharUnicode, GetPageCharBox y FindPageText exponen codepoints por carácter, bounding boxes en espacio de usuario y coincidencias de búsqueda de subcadenas; y SaveBytesWithVersion, SaveToStream y SaveToFile exportan instantáneas no incrementales con override opcional de la versión del header PDF (10..20)
Las ediciones de página requieren un documento sin formularios interactivos; la edición consciente de formularios permanece en el wrapper clásico
InsertBlankPage, DeletePage y RotatePage trabajan en una etapa privada de guardado completo/reapertura y reemplazan el documento activo solo después de pasar las verificaciones nativas de geometría/conteo y las verificaciones de cancelación
SaveBytes devuelve una instantánea no incremental; los callbacks nativos del writer aplican el presupuesto de salida y capturan las excepciones de los callbacks en lugar de dejar que excepciones Pascal crucen la frontera de C
RenderPage devuelve TPdfCorePixels con bytes BGRA nativos compactos de arriba hacia abajo, Width, Height y Stride; Stride es Width por cuatro y no se crea ningún objeto bitmap/canvas
El fondo es un valor ARGB empaquetado, blanco opaco de forma predeterminada; Rotation va de 0 a 3 giros de cuarto, y el perfil de renderizado incluye las anotaciones regulares
Las operaciones nativas enmascaran temporalmente los traps de punto flotante y limpian los flags nativos de excepción pendiente antes de restaurar la máscara de excepciones original de quien llama; esto permite operaciones nativas válidas de fuentes bajo FPC sin cambiar de forma permanente la política de traps de quien llama
TPdfDocumentCoreOptions.Default permite 128 MiB de entrada/salida, 10,000 páginas, 16,777,216 caracteres nativos/unidades de salida UTF-16 y 16,777,216 píxeles de renderizado
Los máximos duros son 512 MiB de entrada/salida, 100,000 páginas, 16,777,216 caracteres/unidades de salida UTF-16, 268,435,456 píxeles sujetos al tamaño de buffer con signo, y 32,768 puntos/píxeles por dimensión de página insertada/renderizada
La cancelación cooperativa se verifica alrededor de las llamadas nativas y dentro de los callbacks del writer; los internos nativos de carga, texto y renderizado no se interrumpen a mitad de llamada
La prueba standalone RTL pasa en Delphi y FPC Win64 con la DLL de reemplazo declarada; el puente clásico wrapper/viewer se califica por separado en Delphi Win64, y las demás plataformas conservan sus límites de calificación documentados
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;