PDFium Delphi Component Docs

Ядро документов, не зависящее от фреймворка

FPdfDocumentCore зависит только от модулей RTL и FPdfAsync; он не подключает PDFium, FPdfView, VCL, LCL, Graphics или оконные элементы управления

TPdfDocumentCore владеет независимым нативным документом и его входными байтами; он поддерживает снимки load/stream, извлечение Unicode, размеры страниц, сырой рендеринг BGRA, вставку пустых страниц, удаление страниц, поворот и ограниченные по объёму байты полной записи

Для интеграции с классическим компонентом используйте существующий адаптер TPdf.CreateCoreSnapshot; существующий исходный код TPdf и просмотрщика остаётся совместимым, а редактирование возвращённого core не меняет исходную обёртку

Нативный хост и время жизни

Независимый RTL-хост загружает и инициализирует PDFium, передаёт TPdfCoreSymbolResolver и владельца времени жизни IInterface в BindPdfDocumentCoreRuntime, затем передаёт возвращённый IPdfDocumentCoreRuntime core-документам

Резолвер привязывает каждый требуемый экспорт до открытия любого документа; владелец времени жизни должен удерживать тот же инициализированный нативный модуль вместе с его конфигурацией, пока не освободится последняя ссылка

Core сам никогда не инициализирует и не уничтожает нативный модуль вызывающего; несколько документов могут разделять один runtime, а все handles/буферы освобождаются до владельца времени жизни runtime

Классический snapshot-адаптер удерживает настроенный модуль обёртки и отклоняет явный UnloadLibrary, пока живы его core-runtime; освобождайте core до завершения хоста или модуля

Вызовы PDFium остаются синхронизируемыми вызывающим; runtime и core-документы не вводят фоновую работу и не делают нативные API потокобезопасными

Операции с документом

LoadBytes копирует исходные байты и принимает новый документ только после нативной загрузки и проверок страниц/Form; некорректный ввод или отмена сохраняют предыдущий активный документ

LoadStream читает весь поток с нулевого смещения в рамках входного бюджета и восстанавливает исходную позицию перед принятием замещающего документа; LoadFile открывает файл с запретом совместной записи и делегирует LoadStream

Пароли — явные нативные байтовые строки UTF-8 без встроенных нулей; Password и SecurityHandlerRevision инспектируют состояние защиты активного документа, SaveBytes(RemoveSecurity) при записи сохраняет или снимает шифрование, а InsertBlankPage, DeletePage и RotatePage сохраняют шифрование на документах с паролем и отклоняют подписанные документы

Инициализация XFA, host UI JavaScript, наложения заполнения форм и редактирование виджетов остаются зоной ответственности классического компонента; рендеринг core рисует нативное содержимое страниц и обычные аннотации без окружения заполнения форм

Все индексы страниц нуль-базированные; PageText возвращает фактический нативный текст UTF-16, включая сгенерированные извлечением пробелы, в рамках лимитов как по нативным символам, так и по единицам вывода UTF-16, GetMetaText читает стандартные теги Info-словаря (такие как Title, Author, Subject, Keywords, Creator, Producer, CreationDate и ModDate) как ограниченный текст UTF-16, GetPageLabel читает строку метки страницы с отсчётом от нуля, а GetFileVersion, GetDocPermissions и GetUserPermissions инспектируют версию заголовка PDF (например, 17 для PDF 1.7) и битовые маски разрешений

GetMediaBox, GetCropBox, GetTrimBox, GetBleedBox, GetArtBox и GetPageBoundingBox читают bounding box страницы в TPdfCoreBox (Left, Bottom, Right, Top) и возвращают False, когда блока нет; SetMediaBox, SetCropBox, SetTrimBox, SetBleedBox и SetArtBox проверяют конечные положительные размеры блока и обновляют целевую страницу в поэтапном конвейере правок, а FlattenPage разворачивает аннотации или виджеты страницы в том же конвейере (возвращая 1, если развернуто, или 2, если разворачивать было нечего)

ImportPages импортирует все страницы или строку диапазона страниц PDFium с отсчётом от единицы (например, 1,3-5), а ImportPagesByIndex импортирует явный массив нулевых индексов страниц источника из другого активного безформенного TPdfDocumentCore по нулевому индексу вставки (или дописывает в конец при -1) внутри поэтапного конвейера правок, соблюдая MaxPages и байтовые бюджеты

GetBookmarks обходит иерархию оглавления документа с защитой от циклов и возвращает элементы TPdfCoreBookmarks с Title, нулевым Depth, ChildCount, IsOpen, нулевым TargetPageIndex (или -1) и ActionUri; GetAttachmentCount, GetAttachmentInfo, AddAttachment и DeleteAttachment инспектируют и меняют встроенные вложения файлов в поэтапном конвейере правок; GetSignatureCount и GetSignatureInfo инспектируют объекты цифровых подписей (SubFilter, Time, Reason, DocMDPPermission, ByteRange и Contents); GetPageCharCount, GetPageCharUnicode, GetPageCharBox и FindPageText открывают посимвольные коды, bounding box в пользовательском пространстве и поиск подстрок; а SaveBytesWithVersion, SaveToStream и SaveToFile экспортируют неинкрементальные снимки с опциональным переопределением версии заголовка PDF (10..20)

Правки страниц требуют документа без интерактивных форм; редактирование с учётом форм остаётся в классической обёртке

InsertBlankPage, DeletePage и RotatePage работают в приватной стадии полной записи/переоткрытия и заменяют активный документ только после успешных нативных проверок геометрии/количества и проверок отмены

SaveBytes возвращает неинкрементальный снимок; нативные колбэки записи соблюдают бюджет вывода и перехватывают исключения колбэков, не допуская перехода исключений Pascal через границу C

Сырые пиксели и состояние плавающей запятой

RenderPage возвращает TPdfCorePixels с плотно упакованными сверху вниз нативными байтами BGRA, Width, Height и Stride; Stride равен Width, умноженному на четыре, а объект bitmap/canvas не создаётся

Background — упакованное значение ARGB, по умолчанию непрозрачный белый; Rotation задаёт четверти оборотов от 0 до 3, а профиль рендеринга включает обычные аннотации

Нативные операции временно маскируют ловушки плавающей запятой и сбрасывают флаги отложенных нативных исключений перед восстановлением исходной маски исключений вызывающего; это позволяет выполнять корректные нативные операции со шрифтами под FPC, не меняя навсегда политику ловушек вызывающего

Конечные лимиты и квалификация

TPdfDocumentCoreOptions.Default допускает 128 МиБ ввода/вывода, 10 000 страниц, 16 777 216 нативных символов/единиц вывода UTF-16 и 16 777 216 пикселей рендеринга

Жёсткие максимумы: 512 МиБ ввода/вывода, 100 000 страниц, 16 777 216 символов/единиц вывода UTF-16, 268 435 456 пикселей с учётом знакового размера буфера и 32 768 пунктов/пикселей на вставляемую страницу/измерение рендеринга

Кооперативная отмена проверяется вокруг нативных вызовов и внутри колбэков записи; нативные внутренности загрузки, текста и рендеринга не прерываются посреди вызова

Автономный RTL-пробник проходит на Delphi и FPC Win64 с заявленной замещающей DLL; мост классической обёртки/просмотрщика квалифицирован отдельно на Delphi Win64, а другие платформы сохраняют свои документированные пределы квалификации

Публичные объявления

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;