PDFium Delphi Component Docs

Компонент TPdf

Модуль: PDFium
TPdf
Используйте компонент TPdf для открытия, навигации, извлечения текста и редактирования PDF-документов

Пример

Pdf.FileName := 'document.pdf';
Pdf.Password := 'password';
Pdf.Active := True; // открыть PDF-документ
Pdf.PageNumber := 1; // выбрать страницу
ShowMessage(Pdf.Text); // извлечь текст

Типы

type TBookmark = record
  Handle: FPDF_BOOKMARK;
  Title: WString;
  PageNumber: Integer;
  Destination: TDestination;
  DescendantCount: Integer;
  IsOpen: Boolean;
  Action: TPdfAction;
  ActionPageNumber: Integer;
  ActionDestination: TDestination;
  ActionPath: WString;
  HasColor: Boolean;
  Color: TColor;
end;

type TBookmarks = array of TBookmark;

Данные закладки

 

type TDestination = record
  Handle: FPDF_DEST;
  Name: WString;
  PageNumber: Integer;
  ViewMode: TPdfDestinationViewMode;
  ViewParameterCount: Integer;
  ViewParameters: TPdfDestinationViewParameters;
  HasX: Boolean;
  X: Single;
  HasY: Boolean;
  Y: Single;
  HasZoom: Boolean;
  Zoom: Single;
end;

Данные именованного адреса назначения

 

type TPdfDestinationViewMode = (dvmUnknown, dvmXYZ, dvmFit, dvmFitHorizontal, dvmFitVertical, dvmFitRectangle, dvmFitBoundingBox, dvmFitBoundingBoxHorizontal, dvmFitBoundingBoxVertical);

type TPdfDestinationViewParameters = array [0..3] of Single;

Режим просмотра адреса назначения и его упорядоченные нативные параметры

 

type TLinkAnnotation = record
  Handle: FPDF_LINK;
  Rectangle: TPdfRectangle;
  PageNumber: Integer;
  Action: TPdfAction;
  ActionPageNumber: Integer;
  ActionPath: WString;
  Points: array of TQuadrilateralPoint;
end;

type TLinkAnnotations = array of TLinkAnnotation;

type TQuadrilateralPoint = array [1..4] of TPdfPoint;

Данные аннотации-ссылки

 

type TPdfPermission = (permPrint, permModify, permCopy, permAnnotate, permFillForms, permAccessibility, permAssemble, permPrintHighQuality);

type TPdfPermissions = set of TPdfPermission;

Типизированные флаги разрешений документа, декодированные из нативной маски разрешений

 

type TPdfDocumentMetadata = record
  Title: WString;
  Author: WString;
  Subject: WString;
  Keywords: WString;
  Creator: WString;
  Producer: WString;
  CreationDate: WString;
  ModifiedDate: WString;
end;

Один снимок стандартных полей информационного словаря документа

 

type TObjectType = (otUnknown, otText, otPath, otImage, otShading, otForm);

Определяет тип объекта PDF

 

type TPageMode = (pmNone, pmOutline, pmThumbs, pmFullScreen, pmOptionalContentGroup, pmAttachments, pmUnknown);

Определяет, как документ PDF должен отображаться при открытии

 

type TPdfAction = (acUnsupported, acGoto, acGotoRemote, acUri, acLaunch);

Определяет тип действия, связанного с элементом закладки

 

type TPdfAnnotation = record
  Subtype: TPdfAnnotationSubtype;
  Flags: TPdfAnnotationFlags;
  HasColor: Boolean;
  Color: TColor;
  ColorAlpha: Byte;
  HasInteriorColor: Boolean;
  InteriorColor: TColor;
  InteriorColorAlpha: Byte;
  HasAttachmentPoints: Boolean;
  AttachmentPoints: TQuadrilateralPoint;
  Rectangle: TPdfRectangle;
  ContentsText: WString;
  AuthorText: WString;
end;

Данные аннотации

 

type TPdfAnnotationFlag = (afInvisible, afHidden, afPrint, afNoZoom, afNoRotate, afNoView, afReadOnly, afLocked, afToggleNoView);

type TPdfAnnotationFlags = set of TPdfAnnotationFlag;

Флаги аннотаций

 

type TPdfAnnotationSubtype = (anUnknown, anText, anLink, anFreeText, anLine, anSquare, anCircle, anPolygon, anPolyLine, anHighlight, anUnderline, anSquiggly, anStrikeout, anStamp, anCaret, anInk, anPopup, anFileAttachment, anSound, anMovie, anWidget, anScreen, anPrinterMark, anTrapNet, anWaterMark, anThreed, anRichMedia, anXfaWidget, anRedact);

Подтип аннотации

 

type TPdfBlendMode = (bmDefault, bmColor, bmColorBurn, bmColorDodge, bmDarken, bmDifference, bmExclusion, bmHardLight, bmHue, bmLighten, bmLuminosity, bmMultiply, bmNormal, bmOverlay, bmSaturation, bmScreen, bmSoftLight);

Определяет, как слои смешиваются друг с другом

 

type TPdfDisplayMode = (dmSingleContinuous, dmTwoPageContinuous, dmTwoPageContinuousWithCover);

Определяет, как отображаются страницы PDF-документа

 

type TPdfFeature = (feUnknown, feXfaForm, fePortableCollection, feAttachment, feSecurity, feSharedReview, feSharedFormAcrobat, feSharedFormFilesystem, feSharedFormEmail, fe3dAnnotation, feMovieAnnotation, feSoundAnnotation, feScreenMediaAnnotation, feScreenRichMediaAnnotation, feAttachmentAnnotation, feSignatureAnnotation);

Возможность PDF-документа, о которой сообщает событие OnUnsupportedFeature

 

type TPdfFillMode = (fmNone, fmAlternate, fmWinding);

Определяет, как образуются области заливки при самопересечении пути

 

type TPdfFormFieldFlag = (ffReadOnly, ffRequired, ffNoExport, ffMultiline, ffChoiceCombo, ffChoiceEdit, ffPassword, ffChoiceMultiSelect);

type TPdfFormFieldFlags = set of TPdfFormFieldFlag;

Флаги полей форм

 

type TPdfFormFieldInfo = record
  Name: WString;
  AlternateName: WString;
  FieldType: TPdfFormFieldType;
  Flags: TPdfFormFieldFlags;
  OptionLabels: array of WString;
  OptionSelected: array of Boolean;
  FontSize: Single;
  Checked: Boolean;
  ExportValue: WString;
  GroupCount: Integer;
  GroupIndex: Integer;
end;

Сведения о поле формы

 

type TPdfFormFieldType = (fiUnknown, fiPushButton, fiCheckBox, fiRadioButton, fiComboBox, fiListBox, fiTextField, fiSignature);

Определяет тип поля формы

 

type TPdfFormType = (ftUnknown, ftNone, ftAcroForm, ftXfaFull, ftXfaForeground);

Определяет тип форм в PDF-документе

 

type TPdfImage = record
  Width: Integer;
  Height: Integer;
  Data: TBytes;
end;

Размер в пикселях и данные объекта изображения PDF

 

type TPdfLineCap = (lcDefault, lcButt, lcRound, lcProjectingSquare);

Форма концов открытых подпутей

 

type TPdfLineJoin = (ljDefault, ljMiter, ljRound, ljBevel);

Форма углов путей с обводкой

 

type TPdfPoint = record
  X, Y: Double;
end;

Точка с координатами X и Y

 

type TPdfRectangle = record
  Left, Top, Right, Bottom: Double;
end;
type TPdfRectangles = array of TPdfRectangle;

Прямоугольная область с координатами Left, Top, Right и Bottom

 

type TPdfFileIdentifierType = (fidPermanent, fidChanging);

Селектор идентификатора файла в трейлере. fidPermanent читает первую запись /ID, а fidChanging — вторую запись /ID

 

type TPdfPageBox = (pbMedia, pbCrop, pbBleed, pbTrim, pbArt);

Селектор бокса в словаре страницы, используемый PageBox, GetPageBox и SetPageBox

 

type TPdfJavaScriptAction = record
  Name: WString;
  Script: WString;
end;
type TPdfJavaScriptActions = array of TPdfJavaScriptAction;

Данные действий дерева имён JavaScript уровня документа

 

type TPdfSignature = record
  Content: TBytes;
  Encoding: WString;
  Reason: WString;
  Time: WString;
  Permission: Integer;
end;

Сведения о цифровой подписи

 

type TPdfIntegerArray = array of Integer;

Массив целых чисел, используемый списками ID маркированного содержимого дерева структуры

 

type TPdfSingleArray = array of Single;

Массив чисел одинарной точности, используемый методами задания позиций символов текстовых объектов

 

type TPdfPrintPageRange = record
  StartPage: Integer;
  EndPage: Integer;
end;
type TPdfPrintPageRanges = array of TPdfPrintPageRange;

Диапазоны печатаемых страниц с нумерацией с единицы из настроек просмотрщика документа

 

type TPdfStructureElement = record
  Level: Integer;
  ParentIndex: Integer;
  TypeName: WString;
  ObjectType: WString;
  Title: WString;
  AlternateText: WString;
  ActualText: WString;
  Expansion: WString;
  ID: WString;
  Language: WString;
  MarkedContentID: Integer;
  MarkedContentIDs: TPdfIntegerArray;
  ChildCount: Integer;
  ChildMarkedContentIDs: TPdfIntegerArray;
  AttributeCount: Integer;
  ListNumbering: WString;
  Scope: WString;
  HasHeaders: Boolean;
  HeadersIds: array of WString;
  ColSpan: Integer;
  RowSpan: Integer;
  HasPrintField: Boolean;
  NamespaceUri: WString;
  RoleMappedNamespaceUri: WString;
  RoleMappedTypeName: WString;
  HasReference: Boolean;
  HasAssociatedFile: Boolean;
  AssociatedFileRelationship: WString;
  AssociatedFileDescription: WString;
  AnnotationSubtype: WString;
  AnnotationContents: WString;
  AnnotationAlternateText: WString;
  IsArtifact: Boolean;
  WidgetCount: Integer;
  HasAppearance: Boolean;
  LabelText: WString;
  FieldAlternateName: WString;
end;

type TPdfStructureElements = array of TPdfStructureElement;

Плоские данные элементов логической структуры для страниц tagged PDF

 

type TPdfFormSelectionRect = record
  PageNumber: Integer;
  Bounds: TPdfRectangle;
end;

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

 

type TPdfStructureReadOptions = record
  MaxDepth: Integer;
  MaxElements: Integer;
  MaxAttributeValues: Integer;
  DeadlineMilliseconds: Cardinal;
  IncludeAttributes: Boolean;
  class function Default: TPdfStructureReadOptions; static;
end;

Бюджеты ресурсов для итеративного нативного обхода дерева структуры

type TPdfStructureReadStatus = record
  Completed: Boolean;
  ElementsVisited: Integer;
  AttributeValuesVisited: Integer;
  DepthLimitReached: Boolean;
  ElementLimitReached: Boolean;
  AttributeLimitReached: Boolean;
  DeadlineReached: Boolean;
  VisitorStopped: Boolean;
end;

Сведения о завершении и усечении, возвращаемые методами обхода структуры

 

type TPdfVersion = (pvUnknown, pv10, pv11, pv12, pv13, pv14, pv15, pv16, pv17);

Версия PDF-файла или явная цель SaveAs. Возможные значения: неизвестная версия, версии PDF от 1.0 до 1.7. Явные цели SaveAs от PDF 1.3 до PDF 1.7 нормализуются и проверяются на соответствие выбранной версии PDF

 

type TPrintPaperHandling = (phUndefined, phSimplex, phDuplexFlipShortEdge, phDuplexFlipLongEdge);

Параметры обработки бумаги при печати

 

type TPdfPrintMode = (prEmf, prTextOnly, prPostScript2, prPostScript3, prPostScript2PassThrough, prPostScript3PassThrough, prEmfImageMasks, prPostScript3Type42, prPostScript3Type42PassThrough);

Режим вывода печати PDFium для Windows, выбираемый SetPdfPrintMode

 

type TRenderOption = (reAnnotations, reLcd, reNoNativeText, reGrayscale, reDebugInfo, reNoCatchException, reLimitCache, reHalftone, rePrinting, reReverseByteOrder, reNoSmoothText, reNoSmoothImage, reNoSmoothPath, reInvert, reNightDuotone);

type TRenderOptions = set of TRenderOption;

Флаги отрисовки страниц

 

type TRotation = (ro0, ro90, ro180, ro270);

Поворот страницы PDF. Поворот выполняется по часовой стрелке

 

type TSaveOption = (saNone, saIncremental, saNoIncremental, saRemoveSecurity);

Определяет, как будет сохранён PDF-документ

 

type TSearchOption = (seCaseSensitive, seWholeWord, seConsecutive);

type TSearchOptions = set of TSearchOption;

Флаги поиска

 

type TWebLink = record
  Url: WString;
  Rectangles: TPdfRectangles;
end;

type TWebLinks = array of TWebLink;

Сведения об URL и границы веб-ссылки

 

type WString = {$ifdef D2009PLUS} string {$else} WideString {$endif D2009PLUS};

Широкая строка

 

Константы

const PointsPerInch: Integer = 72;

PDF использует пункты с плотностью 72 пункта на дюйм

 

const FLAT_NORMALDISPLAY = 0;
const FLAT_PRINT = 1;

Профили сплющивания, передаваемые в FlattenPage / FlattenAllPages. FLAT_NORMALDISPLAY нацелен на показ на экране; FLAT_PRINT — на печатный вывод

 

const FLATTEN_FAIL = 0;
const FLATTEN_SUCCESS = 1;
const FLATTEN_NOTHINGTODO = 2;

Коды результатов, возвращаемые FlattenPage

 

type TPdfReadingUnit = record
  Text: WString;
  Kind: TPdfContentFragmentKind;
  HeadingLevel: Integer;
  Page: Integer;
  Rects: TPdfRectangles;
  FragmentIndex: Integer;
  SentenceIndex: Integer;
  IsAlternateText: Boolean;
  Language: WString;
end

type TPdfReadingUnits = array of TPdfReadingUnit;

Единицы чтения на уровне предложения для сценариев text-to-speech и вспомогательного прослушивания с чтением

 

type TPdfWordBox = record
  Text: WString;
  StartIndex: Integer;
  Count: Integer;
  Rect: TPdfRectangle;
  Page: Integer;
end

type TPdfWordBoxes = array of TPdfWordBox;

Диапазоны текста на уровне слова и прямоугольники страниц, используемые синхронизированной подсветкой чтения

 

type TPdfSpokenSpan = record
  SpokenStart: Integer;
  SpokenCount: Integer;
  Page: Integer;
  StartIndex: Integer;
  Count: Integer;
end

type TPdfSpokenSpans = array of TPdfSpokenSpan;

Сопоставленные проходы, переводящие смещения речевого движка обратно в текст страниц PDF

 

type TPdfSpokenText = record
  Text: WString;
  Spans: TPdfSpokenSpans;
end

type TPdfSpokenTexts = array of TPdfSpokenText;

Фрагменты речи и сопоставления с исходным текстом, используемые сценариями чтения вслух и TPdfReadingSession

 

type TPdfReadingSessionState = (pssIdle, pssSpeaking, pssPaused);

Состояние воспроизведения, сообщаемое TPdfReadingSession

 

Глобальные переменные

var LibraryName: string = 'pdfium.dll';

Имя стандартной библиотеки PDFium, используемой, когда EnableV8Engine равно False. Можно изменить до вызова LoadLibrary

 

var EnableV8Engine: Boolean = False;

Установите в True перед загрузкой, чтобы выбрать pdfium.v8.dll из соответствующей папки DLLs Win32 или Win64

 

Глобальные функции

Свойства

Методы

События