PDFium Delphi Component Docs

Core dokumentu niezależny od frameworku

FPdfDocumentCore zależy wyłącznie od unitów RTL i FPdfAsync; nie importuje PDFium, FPdfView, VCL, LCL, Graphics ani kontrolek okienkowych

TPdfDocumentCore posiada niezależny natywny dokument i jego bajty wejściowe; obsługuje migawki load/stream, ekstrakcję Unicode, wymiary stron, surowe renderowanie BGRA, wstawianie pustych stron, usuwanie stron, rotację oraz ograniczony zapis pełnych bajtów

Do integracji z klasycznym komponentem użyj istniejącego adaptera TPdf.CreateCoreSnapshot; istniejące źródła TPdf i przeglądarki pozostają kompatybilne, a edycja zwróconego core nie zmienia źródłowego wrappera

Natywny host i czas życia

Niezależny host RTL wczytuje i inicjalizuje PDFium, przekazuje TPdfCoreSymbolResolver oraz właściciela czasu życia IInterface do BindPdfDocumentCoreRuntime, a następnie podaje zwrócony IPdfDocumentCoreRuntime dokumentom core

Resolver wiąże każdy wymagany eksport, zanim jakikolwiek dokument zostanie otwarty; właściciel czasu życia musi utrzymać przy życiu ten sam zainicjalizowany moduł natywny i jego konfigurację do zwolnienia ostatniej referencji

Core sam nie inicjalizuje ani nie niszczy natywnego modułu wywołującego; wiele dokumentów może współdzielić jeden runtime, a wszystkie uchwyty/bufory są zwalniane przed właścicielem czasu życia runtime'u

Klasyczny adapter migawki przypina skonfigurowany moduł wrappera i odrzuca jawne UnloadLibrary, dopóki jego runtime'y core pozostają żywe; zwalniaj core przed zamknięciem hosta lub unitu

Wywołania PDFium pozostają synchronizowane po stronie wywołującego; runtime'y i dokumenty core nie wprowadzają pracy w tle ani nie czynią natywnych API thread-safe

Operacje na dokumencie

LoadBytes kopiuje bajty źródłowe i przyjmuje nowy dokument dopiero po natywnym wczytaniu i sprawdzeniu stron/formularzy; nieprawidłowe wejście lub anulowanie zachowuje poprzedni aktywny dokument

LoadStream czyta cały strumień od offsetu zero w ramach budżetu wejściowego i przywraca pierwotną pozycję przed przyjęciem dokumentu zamiennego; LoadFile otwiera plik z zablokowanym współdzieleniem zapisu i deleguje do LoadStream

Hasła to jawne natywne napisy bajtów UTF-8 bez wbudowanych znaków null; Password i SecurityHandlerRevision pozwalają obejrzeć stan zabezpieczeń aktywnego dokumentu, SaveBytes(RemoveSecurity) zachowuje albo zdejmuje szyfrowanie przy zapisie, a InsertBlankPage, DeletePage i RotatePage zachowują szyfrowanie dokumentów chronionych hasłem, odrzucając dokumenty podpisane

Inicjalizacja XFA, UI hosta JavaScript, nakładki wypełniania formularzy i edycja widgetów pozostają odpowiedzialnością klasycznego komponentu; renderowanie core rysuje natywną zawartość stron i zwykłe adnotacje bez środowiska wypełniania formularzy

Wszystkie indeksy stron liczą się od zera; PageText zwraca rzeczywisty natywny tekst UTF-16, łącznie z generowaną białą ekstrakcją, w ramach limitów znaków natywnych i wyjścia UTF-16, GetMetaText czyta standardowe tagi słownika Info (jak Title, Author, Subject, Keywords, Creator, Producer, CreationDate i ModDate) jako ograniczony tekst UTF-16, GetPageLabel czyta etykietę strony o podanym indeksie od zera, a GetFileVersion, GetDocPermissions i GetUserPermissions pozwalają obejrzeć wersję z nagłówka PDF (jak 17 dla PDF 1.7) i maski bitowe uprawnień

GetMediaBox, GetCropBox, GetTrimBox, GetBleedBox, GetArtBox i GetPageBoundingBox czytają pola ograniczające strony do TPdfCoreBox (Left, Bottom, Right, Top) i zwracają False, gdy pola brak; SetMediaBox, SetCropBox, SetTrimBox, SetBleedBox i SetArtBox walidują skończone, dodatnie wymiary pól i aktualizują docelową stronę w etapowanym potoku edycji, a FlattenPage spłaszcza adnotacje lub widgety strony w etapowanym potoku edycji (zwracając 1 po spłaszczeniu albo 2, gdy nic nie wymagało spłaszczenia)

ImportPages importuje wszystkie strony albo zakres w postaci ciągu z numeracją stron od 1 (jak 1,3-5), a ImportPagesByIndex importuje jawną tablicę indeksów stron źródłowych liczonych od zera z innego aktywnego TPdfDocumentCore bez formularzy, wstawiając pod indeksem liczonym od zera (albo dopisując przy -1), wszystko w etapowanym potoku edycji i z egzekwowaniem MaxPages oraz budżetów bajtowych

GetBookmarks przechodzi hierarchię zakładek dokumentu z ochroną przed cyklami i zwraca elementy TPdfCoreBookmarks z Title, liczoną od zera Depth, ChildCount, IsOpen, liczonym od zera TargetPageIndex (albo -1) i ActionUri; GetAttachmentCount, GetAttachmentInfo, AddAttachment i DeleteAttachment pozwalają obejrzeć i modyfikować osadzone załączniki w etapowanym potoku edycji; GetSignatureCount i GetSignatureInfo oglądają obiekty podpisów cyfrowych (SubFilter, Time, Reason, DocMDPPermission, ByteRange i Contents); GetPageCharCount, GetPageCharUnicode, GetPageCharBox i FindPageText udostępniają punkty kodowe per znak, pola ograniczające w przestrzeni użytkownika i wyniki wyszukiwania podciągów; a SaveBytesWithVersion, SaveToStream i SaveToFile eksportują nieprzyrostowe migawki z opcjonalnym nadpisaniem wersji nagłówka PDF (10..20)

Edycje stron wymagają dokumentu bez interaktywnych formularzy; edycja świadoma formularzy pozostaje w klasycznym wrapperze

InsertBlankPage, DeletePage i RotatePage działają w prywatnym etapie pełnego zapisu/ponownego otwarcia i podmieniają aktywny dokument dopiero po przejściu natywnych sprawdzeń geometrii/liczności oraz kontroli anulowania

SaveBytes zwraca nieprzyrostową migawkę; natywne callbacki pisarza egzekwują budżet wyjścia i łapią wyjątki callbacków, zamiast przepuszczać wyjątki Pascala przez granicę C

Surowe piksele i stan zmiennoprzecinkowy

RenderPage zwraca TPdfCorePixels z ciasno spakowanymi natywnymi bajtami BGRA od góry do dołu oraz Width, Height i Stride; Stride to Width razy cztery i nie powstaje żaden obiekt bitmapy/canvas

Background to spakowana wartość ARGB, domyślnie nieprzezroczysta biel; Rotation przyjmuje 0–3 ćwiartkowe obroty, a profil renderowania obejmuje zwykłe adnotacje

Natywne operacje czasowo maskują pułapki zmiennoprzecinkowe i czyszczą natywne flagi oczekujących wyjątków, zanim przywrócą pierwotną maskę wyjątków wywołującego; dzięki temu poprawne natywne operacje czcionek działają pod FPC bez trwałej zmiany polityki pułapek wywołującego

Skończone limity i kwalifikacja

TPdfDocumentCoreOptions.Default dopuszcza 128 MiB wejścia/wyjścia, 10,000 stron, 16,777,216 natywnych znaków/jednostek wyjścia UTF-16 i 16,777,216 pikseli renderowania

Twarde maksima to 512 MiB wejścia/wyjścia, 100,000 stron, 16,777,216 znaków/jednostek wyjścia UTF-16, 268,435,456 pikseli w ramach rozmiaru bufora ze znakiem oraz 32,768 punktów/pikseli na wymiar wstawianej strony/renderowania

Kooperacyjne anulowanie jest sprawdzane wokół wywołań natywnych i wewnątrz callbacków pisarza; natywne wewnętrzności ładowania, tekstu i renderowania nie są przerywane w połowie wywołania

Samodzielna próba RTL przechodzi na Delphi i FPC Win64 z zadeklarowaną zastępczą biblioteką DLL; klasyczny most wrapper/przeglądarka jest kwalifikowany osobno na Delphi Win64, a pozostałe platformy zachowują swoje udokumentowane limity kwalifikacji

Deklaracje publiczne

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;