PDFium Delphi Component Docs

Núcleo de documento independiente del framework

FPdfDocumentCore depende solo de units RTL y de FPdfAsync; no importa PDFium, FPdfView, VCL, LCL, Graphics ni controles de ventana

TPdfDocumentCore es propietario de un documento nativo independiente y de sus bytes de entrada; soporta snapshots de carga/stream, extracción Unicode, dimensiones de página, renderizado BGRA crudo, inserción de páginas en blanco, borrado de páginas, rotación y bytes de guardado completo acotados

Usa el adaptador existente TPdf.CreateCoreSnapshot para integrarte con el componente clásico; el código fuente TPdf y de visores existentes sigue siendo compatible, y editar el core devuelto no cambia el wrapper de origen

Host nativo y ciclo de vida

Un host RTL independiente carga e inicializa PDFium, suministra un TPdfCoreSymbolResolver y un propietario de ciclo de vida IInterface a BindPdfDocumentCoreRuntime, y luego pasa el IPdfDocumentCoreRuntime devuelto a los documentos core

El resolver vincula cada exportación requerida antes de abrir cualquier documento; el propietario del ciclo 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 del llamador; varios documentos pueden compartir un runtime, y todos los handles/buffers se liberan antes que el propietario del ciclo de vida del runtime

El adaptador de snapshot clásico fija el módulo del wrapper configurado y rechaza un UnloadLibrary explícito mientras sus runtimes core sigan vivos; libera los cores antes del apagado del host/unit

Las llamadas a PDFium siguen sincronizadas por el llamador; los runtimes y los documentos core no introducen trabajo en segundo plano ni hacen thread-safe las API nativas

Operaciones de documento

LoadBytes copia los bytes de origen y acepta el documento nuevo solo tras las comprobaciones nativas de carga y de página/formulario; una entrada inválida o una cancelación preserva el documento activo anterior

LoadStream lee el stream completo desde la posición cero dentro del presupuesto de entrada y restaura la posición original antes de aceptar el documento de reemplazo; LoadFile abre un fichero denegando el uso compartido de escritura y delega en LoadStream

Las contraseñas son cadenas de bytes UTF-8 nativas explícitas, sin null incrustados; Password y SecurityHandlerRevision inspeccionan el estado de seguridad del documento activo, SaveBytes(RemoveSecurity) conserva 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 de host de JavaScript, las capas de form-fill y la edición de widgets siguen siendo responsabilidad del componente clásico; el renderizado del core dibuja el contenido nativo de página y las anotaciones regulares sin un entorno de form-fill

Todos los índices de página son de base cero; PageText devuelve texto nativo UTF-16 real, incluido el whitespace de extracción generado, bajo los límites de caracteres nativos y de unidades de salida UTF-16, GetMetaText lee las etiquetas estándar del diccionario Info (como Title, Author, Subject, Keywords, Creator, Producer, CreationDate y ModDate) como texto UTF-16 acotado, GetPageLabel lee la cadena de etiqueta de la página de base cero, y GetFileVersion, GetDocPermissions y GetUserPermissions inspeccionan la versión de la cabecera 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) y devuelven False cuando la caja no existe; 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 o widgets de página en el pipeline de edición por etapas (devolviendo 1 cuando aplanó o 2 cuando no hizo falta aplanar nada)

ImportPages importa todas las páginas o un rango de páginas PDFium con base uno (como 1,3-5) y ImportPagesByIndex importa un array explícito de índices de páginas de origen con base cero desde otro TPdfDocumentCore activo sin formularios, en un índice de inserción de base cero (o añade al final con -1) dentro del pipeline de edición por etapas, respetando MaxPages y los presupuestos de bytes

GetBookmarks recorre la jerarquía de marcadores del documento con protección contra ciclos y devuelve elementos TPdfCoreBookmarks con Title, Depth de base cero, ChildCount, IsOpen, TargetPageIndex de base cero (o -1) y ActionUri; GetAttachmentCount, GetAttachmentInfo, AddAttachment y DeleteAttachment inspeccionan y modifican los archivos adjuntos incrustados en el pipeline de edición por etapas; GetSignatureCount y GetSignatureInfo inspeccionan los 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 búsquedas de subcadenas; y SaveBytesWithVersion, SaveToStream y SaveToFile exportan snapshots no incrementales con sustitución opcional de la versión de la cabecera PDF (10..20)

Las ediciones de página requieren un documento sin formularios interactivos; la edición consciente de formularios sigue en el wrapper clásico

InsertBlankPage, DeletePage y RotatePage trabajan en una etapa privada de full-save/reapertura y reemplazan el documento activo solo tras pasar las comprobaciones nativas de geometría/conteo y las comprobaciones de cancelación

SaveBytes devuelve un snapshot no incremental; los callbacks nativos de escritura aplican el presupuesto de salida y capturan las excepciones de los callbacks en lugar de dejar que excepciones Pascal crucen la frontera C

Píxeles crudos y estado de coma flotante

RenderPage devuelve TPdfCorePixels con bytes BGRA nativos empaquetados de arriba abajo sin huecos, 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 por defecto; Rotation va de 0 a 3 cuartos de vuelta, y el perfil de renderizado incluye las anotaciones regulares

Las operaciones nativas enmascaran temporalmente las trampas de coma flotante y limpian los flags nativos de excepción pendiente antes de restaurar la máscara de excepciones original del llamador; esto permite operaciones nativas válidas de fuentes bajo FPC sin cambiar de forma permanente la política de trampas del llamador

Límites finitos y cualificación

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 absolutos 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 comprueba alrededor de las llamadas nativas y dentro de los callbacks de escritura; los internos nativos de carga, texto y renderizado no se interrumpen a mitad de llamada

La sonda RTL independiente pasa en Delphi y FPC Win64 con la DLL de reemplazo declarada; el puente wrapper/visor clásico se cualifica por separado en Delphi Win64, y las demás plataformas conservan sus límites documentados de cualificación

Declaraciones públicas

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;