PDFium Delphi Component Docs

Componente TPdf

Unidad: PDFium
TPdf
Use el componente TPdf para abrir, navegar, extraer texto y editar documentos PDF

Núcleo de documentos independiente del framework

Use FPdfDocumentCore para una API de documentos sin dependencia de VCL/LCL ni Graphics, o llame a TPdf.CreateCoreSnapshot para tender un puente desde un componente existente hacia una instantánea independiente solo con RTL

Personalidad clásica del componente sin widgets

Defina PDFIUMPAS_CORE_ONLY para compilar la API de documentos de alto nivel sin el framework de widgets VCL/LCL: TPdfView, TPdfReadingSession y los helpers del viewer quedan excluidos, y las unidades de widgets (Forms, Controls, Dialogs, ExtCtrls, Menus, Messages) desaparecen de la lista de uses de la unidad en ambas ramas del compilador; solo Vcl.Graphics o la unidad Graphics de LCL permanece para la API de renderizado de buffers de píxeles

La personalidad predeterminada conserva la API clásica, de modo que los proyectos existentes compilan sin cambios; un consumidor headless agrega el define y usa TPdf directamente para cargar, extraer texto, editar, guardar y renderizar a bitmaps; CreateCoreSnapshot además exporta el documento activo a una instantánea acotada independiente TPdfDocumentCore

Las diferencias headless son explícitas: los timers de formularios con script de PDFium reportan no disponible (sin bomba de mensajes de ventana), los prompts de JavaScript devuelven la respuesta predeterminada con script sin diálogo, las alertas usan el message box Win32 crudo, y las características visuales del control están ausentes; el sustituto inerte TPdfView mantiene compilando el glue de llenado de formularios aunque nunca se cree una instancia

Ejemplo

Pdf.FileName := 'document.pdf';
Pdf.Password := 'password';
Pdf.Active := True; // open PDF document
Pdf.PageNumber := 1; // select page
ShowMessage(Pdf.Text); // extract text

Tipos

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;
  Style: TPdfOutlineStyle;
end;

type TBookmarks = array of TBookmark;

Datos de marcadores

 

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;

Datos de destinos con nombre

 

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

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

Modo de vista del destino y sus parámetros nativos ordenados

 

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;

Datos de anotaciones de vínculo

 

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

type TPdfPermissions = set of TPdfPermission;

Banderas de permisos del documento con tipo, decodificadas a partir de la máscara de permisos nativa

 

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

Una instantánea de los campos del diccionario Info estándar del documento

 

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

Determina el tipo del objeto PDF

 

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

Determina cómo debe mostrarse el documento PDF al abrirse

 

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

Determina el tipo de una acción asociada con un elemento de marcador

 

type TPdfAnnotation = record
  Subtype: TPdfAnnotationSubtype;
  Flags: TPdfAnnotationFlags;
  HasColor: Boolean;
  Color: TColor;
  ColorAlpha: Byte;
  HasInteriorColor: Boolean;
  InteriorColor: TColor;
  InteriorColorAlpha: Byte;
  HasAttachmentPoints: Boolean;
  AttachmentPoints: TQuadrilateralPoint;
  AttachmentPointSets: TQuadrilateralPoints;
  Rectangle: TPdfRectangle;
  HasContents: Boolean;
  ContentsText: WString;
  HasAuthor: Boolean;
  AuthorText: WString;
  HasName: Boolean;
  Name: WString;
  HasSubject: Boolean;
  Subject: WString;
  HasModificationDate: Boolean;
  ModificationDate: WString;
  HasCreationDate: Boolean;
  CreationDate: WString;
  HasIcon: Boolean;
  Icon: WString;
  HasOpacity: Boolean;
  Opacity: Double;
  HasLineEndpoints: Boolean;
  LineStart: TPdfPoint;
  LineEnd: TPdfPoint;
  HasVertices: Boolean;
  Vertices: array of TPdfPoint;
  HasInkList: Boolean;
  InkList: array of TPdfInkGesture;
  HasBorder: Boolean;
  BorderHorizontalRadius: Single;
  BorderVerticalRadius: Single;
  BorderWidth: Single;
  HasAppearanceNormal: Boolean;
  AppearanceNormal: WString;
  HasAppearanceRollover: Boolean;
  AppearanceRollover: WString;
  HasAppearanceDown: Boolean;
  AppearanceDown: WString;
  HasLinkUri: Boolean;
  LinkUri: WString;
end;

Datos de anotaciones

 

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

type TPdfAnnotationFlags = set of TPdfAnnotationFlag;

Banderas de anotación

 

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);

El subtipo de anotación

 

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

Determina cómo se mezclan las capas entre sí

 

type TPdfDisplayMode = (dmSingleContinuous, dmTwoPageContinuous, dmTwoPageContinuousWithCover);

Determina cómo se muestran las páginas del documento PDF

 

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

Función del documento PDF informada por el evento OnUnsupportedFeature

 

type TPdfFillMode = (fmNone, fmAlternate, fmWinding);

Determina cómo se forman las áreas de relleno cuando un trazado se cruza a sí mismo

 

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

type TPdfFormFieldFlags = set of TPdfFormFieldFlag;

Banderas de campos de formulario

 

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;

Información del campo de formulario

 

type TPdfFormFieldType = (fiUnknown, fiPushButton, fiCheckBox, fiRadioButton, fiComboBox, fiListBox, fiTextField, fiSignature, fiXfa, fiXfaCheckBox, fiXfaComboBox, fiXfaImageField, fiXfaListBox, fiXfaPushButton, fiXfaSignature, fiXfaTextField);

Determina el tipo del campo de formulario

 

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

Determina el tipo de formularios en el documento PDF

 

type TPdfImage = record
  Width: Integer;
  Height: Integer;
  Data: TBytes;
  RawData: TBytes;
  Filters: TPdfStringArray;
  HorizontalDpi: Single;
  VerticalDpi: Single;
  BitsPerPixel: LongWord;
  ColorSpace: Integer;
  MarkedContentId: Integer;
  IccProfile: TBytes;
end;

Tamaño en píxeles y datos del objeto de imagen PDF

 

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

La forma que se usa en los extremos de subtrazados abiertos

 

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

La forma que se usa en las esquinas de los trazados delineados

 

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

Punto con coordenadas X e Y

 

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

Área rectangular con coordenadas Left, Top, Right y Bottom

 

type TPdfFileIdentifierType = (fidPermanent, fidChanging);

Selector del identificador de archivo del tráiler. fidPermanent lee la primera entrada /ID y fidChanging lee la segunda entrada /ID

 

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

Selector de cuadro del diccionario de página usado por PageBox, GetPageBox y SetPageBox

 

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

Datos de acciones del árbol de nombres de JavaScript a nivel de documento

 

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

Información de firma digital

 

type TPdfIntegerArray = array of Integer;

Arreglo de Integer usado por las listas de ID de contenido marcado del árbol de estructura

 

type TPdfSingleArray = array of Single;

Arreglo de números de punto flotante de precisión simple usado por los establecedores de posición de caracteres de objetos de texto

 

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

Rangos de páginas de impresión basados en 1 tomados de las preferencias del visor del documento

 

type TPdfStructureElement = record
  Level: Integer;
  ParentIndex: Integer;
  TypeName: WString;
  RawTypeName: 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;
  Attributes: TPdfStructureAttributeValues;
  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;
  AssociatedFileDeclaredInCatalog: Boolean;
  AssociatedFileDeclaredInStructure: Boolean;
  AssociatedFileInEmbeddedFilesNameTree: Boolean;
  AssociatedFileHasReadingOrder: Boolean;
  AssociatedFileReadingOrderIndex: Integer;
  AnnotationSubtype: WString;
  AnnotationContents: WString;
  AnnotationAlternateText: WString;
  IsArtifact: Boolean;
  WidgetCount: Integer;
  HasAppearance: Boolean;
  LabelText: WString;
  FieldAlternateName: WString;
end;

type TPdfStructureElements = array of TPdfStructureElement;

Datos aplanados de elementos de estructura lógica para páginas PDF etiquetadas

 

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

Un rectángulo en el espacio de página que pertenece al llamador, informado por la selección nativa de texto de formulario

 

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

Presupuestos de recursos para el recorrido nativo iterativo del árbol de estructura

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

Detalles de finalización y truncamiento devueltos por los métodos de recorrido de estructura

 

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

La versión de un archivo PDF o un destino explícito de SaveAs. Los valores posibles son: versión desconocida, PDF versión 1.0 a 1.7 y 2.0. Los destinos explícitos de SaveAs desde PDF 1.3 hasta PDF 2.0 se normalizan y validan contra la versión PDF seleccionada

 

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

Opciones de manejo del papel de impresión

 

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

Modo de salida de impresión de Windows PDFium seleccionado por SetPdfPrintMode

 

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

type TRenderOptions = set of TRenderOption;

Banderas de renderizado de página

 

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

La rotación de la página PDF. La rotación de la página se aplica en sentido horario

 

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

Determina cómo se guardará el documento PDF

 

type TSearchOption = (seCaseSensitive, seWholeWord, seConsecutive);

type TSearchOptions = set of TSearchOption;

Banderas de búsqueda

 

type TWebLink = record
  Url: WString;
  Rectangles: TPdfRectangles;
  StartCharIndex: Integer;
  CharCount: Integer;
end;

type TWebLinks = array of TWebLink;

Información de URL y límites del vínculo web

 

type WString = {$IFDEF FPC} WideString {$ELSE} string {$ENDIF};

Cadena ancha

 

Constantes

const PointsPerInch: Integer = 72;

PDF usa puntos con una densidad de 72 puntos por pulgada

 

const FLAT_NORMALDISPLAY = 0;
const FLAT_PRINT = 1;

Perfiles de aplanado pasados a FlattenPage / FlattenAllPages. FLAT_NORMALDISPLAY apunta a la visualización en pantalla; FLAT_PRINT apunta a la salida impresa

 

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

Códigos de resultado devueltos por FlattenPage

 

type TPdfReadingUnit = record
  Text: WString;
  Kind: TPdfContentFragmentKind;
  HeadingLevel: Integer;
  Page: Integer;
  Rects: TPdfRectangles;
  FragmentIndex: Integer;
  SentenceIndex: Integer;
  IsAlternateText: Boolean;
  Language: WString;
  SourceFragment: TPdfContentFragment;
  TableContext: TPdfReaderTableContext;
  ListContext: TPdfReaderListContext;
  TextStartIndex: Integer;
end;

type TPdfReadingUnits = array of TPdfReadingUnit;

Unidades de lectura a nivel de oración usadas por los flujos de trabajo de texto a voz y de escucha asistida

 

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

type TPdfWordBoxes = array of TPdfWordBox;

Rangos de texto a nivel de palabra y rectángulos de página usados por los resaltados de lectura sincronizada

 

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

type TPdfSpokenSpans = array of TPdfSpokenSpan;

Tramos mapeados que traducen desplazamientos del motor de voz de vuelta al texto de la página PDF

 

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

type TPdfSpokenTexts = array of TPdfSpokenText;

Fragmentos de voz y mapeos de origen usados por los flujos de lectura en voz alta y TPdfReadingSession

 

type TPdfReadingSessionState = (pssIdle, pssSpeaking, pssPaused);

Estado de reproducción informado por TPdfReadingSession

 

Variables globales

var LibraryName: string = 'pdfium.dll';

Nombre de la biblioteca PDFium estándar usada cuando EnableV8Engine es False. Se puede cambiar antes de llamar a LoadLibrary

 

var EnableV8Engine: Boolean = False;

Establézcalo en True antes de cargar para seleccionar pdfium.v8.dll desde la carpeta DLLs correspondiente de Win32 o Win64

 

Funciones globales

Propiedades

Métodos

Eventos

Destruir un TPdf vinculado desactiva sus vistas supervivientes y limpia sus referencias Pdf; los handles nativos de documento y página obtenidos antes no deben volver a usarse