PDFiumPas 文档

PDFium VCL 编程示例

基本文档操作

加载并显示 PDF 文档

Pdf1.FileName := 'C:\MyDocument.pdf';
Pdf1.Active := True;
ShowMessage('Pages: ' + IntToStr(Pdf1.PageCount));
ShowMessage('Title: ' + Pdf1.Title);
ShowMessage('Author: ' + Pdf1.Author);

var
  Stream: TMemoryStream;
begin
  Stream := TMemoryStream.Create;
  try
    Stream.LoadFromFile('C:\MyDocument.pdf');
    Pdf1.LoadDocument(Stream, True);
    Pdf1.Active := True;
    ShowMessage('PDF loaded from stream');
  finally
    Stream.Free;
  end;
end;

创建新 PDF 文档

Pdf1.CreateDocument;
Pdf1.Active := True;
Pdf1.AddPage(0, 612, 792);
Pdf1.PageNumber := 1;
Pdf1.AddText('Hello World!', 'Arial', 12, 100, 700, clBlack, $FF, 0.0);
Pdf1.UpdatePage;
Pdf1.SaveAs('C:\NewDocument.pdf');
Pdf1.Active := False;

文本操作

从 PDF 提取文本

var
  PageText: WString;
  RectText: WString;
begin
  Pdf1.PageNumber := 1;
  PageText := Pdf1.Text;
  Memo1.Text := PageText;
  RectText := Pdf1.TextInRectangle(100, 100, 500, 200);
  ShowMessage('Text in rectangle: ' + RectText);
end;

搜索文本

var
  Position: Integer;
begin
  Position := Pdf1.FindFirst('Hello', [seCaseSensitive]);
  while Position >= 0 do
  begin
    ShowMessage('Found at character: ' + IntToStr(Position));
    Position := Pdf1.FindNext;
  end;
end;

添加带格式的文本

Pdf1.PageNumber := 1;
Pdf1.AddText('Document Title', 'Times New Roman', 16, 100, 750, clBlue);
Pdf1.AddText('This is the document content.', 'Arial', 12, 100, 700, clBlack);
Pdf1.UpdatePage;

检查字符与字体元数据

var
  I: Integer;
  MetricSize: Single;
  FontBytes: TBytes;
begin
  Pdf1.PageNumber := 1;
  for I := 0 to Pdf1.ObjectCount - 1 do
    if Pdf1.ObjectType[I] = otText then
    begin
      MetricSize := 12.0;
      FontBytes := Pdf1.FontData[I];
      Memo1.Lines.Add('Object ' + IntToStr(I));
      Memo1.Lines.Add('Base name: ' + Pdf1.FontBaseName[I]);
      Memo1.Lines.Add('Family: ' + Pdf1.FontFamilyName[I]);
      Memo1.Lines.Add('Embedded: ' + BoolToStr(Pdf1.FontIsEmbedded[I], True));
      Memo1.Lines.Add('Weight: ' + IntToStr(Pdf1.FontWeight[I]));
      Memo1.Lines.Add('Italic angle: ' + IntToStr(Pdf1.FontItalicAngle[I]));
      Memo1.Lines.Add('Ascent: ' + FloatToStr(Pdf1.FontAscent[I, MetricSize]));
      Memo1.Lines.Add('Descent: ' + FloatToStr(Pdf1.FontDescent[I, MetricSize]));
      Memo1.Lines.Add('Font data bytes: ' + IntToStr(Length(FontBytes)));
    end;

  if Pdf1.CharacterCount > 0 then
  begin
    Memo1.Lines.Add('First character size: ' + FloatToStr(Pdf1.CharacterFontSize[0]));
    Memo1.Lines.Add('First character weight: ' + IntToStr(Pdf1.CharacterFontWeight[0]));
    Memo1.Lines.Add('First character angle: ' + FloatToStr(Pdf1.CharacterAngle[0]));
  end;
end;

Demo\Delphi\FontPropertiesDemo\CBuilder\FontPropertiesDemo\Lazarus\FontProperties 工程演示了同一组元数据如何通过 TPdfTPdfView 同时获取。

用 ContentExtractionLab 构建多分类内容提取报告

Demo\Delphi\ContentExtractionLabDemo\CBuilder\ContentExtractionLabDemo\Lazarus\ContentExtractionLab 工程把内容提取整合为一条工作流:打开或新建一份 PDF,让用户勾选元数据、页面文本、页面对象、图像、附件、链接、注释、书签与字体/字符指标,然后生成汇总以及详细的 TXT 或 JSON 报告。Lab 还提供全选/全清类别选择、报告复制到剪贴板、源 PDF 保存等动作,方便用户把生成的示例 PDF 与提取报告并排保留。较早的 ExtractTextExtractImagesAttachmentFontProperties demo 仍保留为聚焦型示例;ExtractText 在 Delphi、C++Builder 和 Lazarus 中支持页范围与页分隔符选项来逐页输出文本,而 ContentExtractionLab 则是跨类别的清点样例。

表单操作

使用表单字段

var
  I: Integer;
  FieldInfo: TPdfFormFieldInfo;
begin
  Pdf1.FormField[0] := 'John';
  for I := 0 to Pdf1.FormFieldCount - 1 do
  begin
    FieldInfo := Pdf1.FormFieldInfo[I];
    ShowMessage(FieldInfo.Name + ': ' + Pdf1.FormField[I]);
  end;
end;

把已填写的表单值扁平化进页面

// 不做扁平化时,FormField[i] := value 仅写入 /V 条目 ——
// 实际可见外观来自 /AP 流,可能不会刷新。
// GenerateFormAppearances 为每个控件重新生成 /AP,
// FlattenAllPages 再把每页的注释和控件烘焙成永久、不可编辑的内容。
Pdf1.FileName := 'C:\Application.pdf';
Pdf1.Active := True;
Pdf1.FormField[0] := 'John Smith';
Pdf1.FormField[1] := 'john@example.com';
Pdf1.GenerateFormAppearances;
if Pdf1.FlattenAllPages then
  Pdf1.SaveAs('C:\Application.flat.pdf');
Pdf1.Active := False;

图像操作

提取图像

var
  I: Integer;
  Bitmap: TBitmap;
begin
  for I := 0 to Pdf1.BitmapCount - 1 do
  begin
    Bitmap := Pdf1.Bitmap[I];
    try
      Bitmap.SaveToFile('C:\ExtractedImage' + IntToStr(I) + '.bmp');
    finally
      Bitmap.Free;
    end;
  end;
end;

添加图像

var
  JpegStream: TFileStream;
begin
  JpegStream := TFileStream.Create('C:\MyImage.jpg', fmOpenRead or fmShareDenyWrite);
  try
    Pdf1.AddJpegImage(JpegStream, 100, 500, 200, 150);
  finally
    JpegStream.Free;
  end;
  Pdf1.AddPicture(Image1.Picture, 100, 300, 150, 100);
  Pdf1.UpdatePage;
end;

注释操作

使用注释

var
  I: Integer;
  Annotation: TPdfAnnotation;
begin
  for I := 0 to Pdf1.AnnotationCount - 1 do
  begin
    Annotation := Pdf1.Annotation[I];
    ShowMessage('Annotation ' + IntToStr(I) + ': ' + Annotation.ContentsText);
  end;
end;

绘制操作

绘制图形

Pdf1.CreatePath(100, 100, 200, 150, fmAlternate, clYellow, $FF, True, clBlack, $FF, 2.0);
Pdf1.AddPath;

Pdf1.CreatePath(100, 100, fmNone, clBlack, $FF, True, clRed, $FF, 3.0);
Pdf1.LineTo(200, 100);
Pdf1.LineTo(150, 200);
Pdf1.ClosePath;
Pdf1.AddPath;
Pdf1.UpdatePage;

导航与书签

使用书签

var
  I: Integer;
  Bookmarks: TBookmarks;
begin
  Bookmarks := Pdf1.Bookmarks;
  for I := 0 to Length(Bookmarks) - 1 do
    ShowMessage(Bookmarks[I].Title + ' -> Page ' + IntToStr(Bookmarks[I].PageNumber));
end;

使用命名目标

var
  I: Integer;
  Destination: TDestination;
begin
  for I := 0 to Pdf1.DestinationCount - 1 do
  begin
    Destination := Pdf1.Destination[I];
    if Destination.Name = 'Chapter1' then
    begin
      Pdf1.PageNumber := Destination.PageNumber;
      Break;
    end;
  end;
end;

附件操作

使用附件

var
  I: Integer;
  AttachmentData: TBytes;
  AttachmentName: WString;
  FileStream: TFileStream;
begin
  for I := 0 to Pdf1.AttachmentCount - 1 do
  begin
    AttachmentName := Pdf1.AttachmentName[I];
    AttachmentData := Pdf1.Attachment[I];
    FileStream := TFileStream.Create('C:\Extracted_' + string(AttachmentName), fmCreate);
    try
      if Length(AttachmentData) > 0 then
        FileStream.WriteBuffer(AttachmentData[0], Length(AttachmentData));
    finally
      FileStream.Free;
    end;
  end;
  if Pdf1.CreateAttachment('MyFile.txt') then
    Pdf1.Attachment[Pdf1.AttachmentCount - 1] := TFile.ReadAllBytes('C:\MyFile.txt');
end;

页面管理

页面操作

Pdf1.AddPage(Pdf1.PageCount + 1, 612, 792);
Pdf1.AddPage(Pdf1.PageCount + 1, 595, 842);
Pdf1.AddPage(Pdf1.PageCount + 1, 400, 600);

var
  SourcePdf: TPdf;
begin
  SourcePdf := TPdf.Create(nil);
  try
    SourcePdf.FileName := 'C:\SourceDocument.pdf';
    SourcePdf.Active := True;
    Pdf1.ImportPages(SourcePdf, '1', Pdf1.PageCount + 1);
  finally
    SourcePdf.Free;
  end;
end;

if Pdf1.PageCount > 1 then
  Pdf1.DeletePage(Pdf1.PageCount);

保存与压缩

保存并压缩

// 创建一份压缩后的 PDF 文档
Pdf1.CreateDocument;
Pdf1.Compressed := True; // 确保所有流都做 FlateDecode 压缩(默认)
Pdf1.Active := True;
Pdf1.AddPage(0, 595, 842); // A4 尺寸
Pdf1.AddText('Hello World!', 'Arial', 24, 100, 700, clBlack, $FF, 0.0);
Pdf1.SaveAs('C:\Compressed.pdf');
Pdf1.Active := False;

// 带选项保存
Pdf1.SaveAs('C:\Output.pdf', saIncremental); // 增量保存
Pdf1.SaveAs('C:\NoSecurity.pdf', saRemoveSecurity); // 移除安全

// 保存到指定 PDF 版本目标。PDF 版本校验器会拒绝
// 任何在所选目标之后才引入的特性(JBIG2Decode、MarkInfo、
// AES 加密、Polygon / Caret / Watermark / Redact 注释等)。
if not Pdf1.SaveAs('C:\Legacy15.pdf', saNone, pv15) then
  ShowMessage('Save rejected: document contains features newer than PDF 1.5');

创建 PDF/A-1b 归档输出

// SaveAsPdfA 会在基础保存之上做后处理,追加一个增量更新:
// 注入 XMP 元数据流、sRGB ICC OutputIntent 和更新后的
// 文档 catalog,使结果符合 PDF/A-1b。当未提供自定义
// ICC 配置文件时,会自动使用随附的 sRGB IEC61966-2.1 配置文件。
Pdf1.FileName := 'C:\Report.pdf';
Pdf1.Active := True;
if Pdf1.SaveAsPdfA('C:\Report.pdfa.pdf', pac1b) then
  ShowMessage('Saved PDF/A-1b archive');

// 带自定义 ICC 的 PDF/A(例如 CMYK 印刷流水线)
var
  Opts: TPdfASaveOptions;
begin
  Opts := Default(TPdfASaveOptions);
  Opts.Conformance    := pac1b;
  Opts.IccProfileData := TFile.ReadAllBytes('C:\Profiles\Coated_GRACoL_2006.icc');
  Pdf1.SaveAsPdfA('C:\Report.cmyk.pdfa.pdf', Opts);
end;

// 内存中 PDF/A 输出
var
  Stream: TMemoryStream;
begin
  Stream := TMemoryStream.Create;
  try
    Opts := Default(TPdfASaveOptions);
    Opts.Conformance := pac1b;
    if Pdf1.SaveAsPdfAToStream(Stream, Opts) then
      UploadToArchive(Stream);
  finally
    Stream.Free;
  end;
end;

校验 PDF/A 合规性

var
  Validation: TPdfAValidationResult;
  Issue: TPdfAValidationIssue;
begin
  Pdf1.FileName := 'C:\Incoming\report.pdf';
  Pdf1.Active   := True;

  // 轻量级 header 风格的探测 —— 读取合规级别,
  // 不会迭代完整校验器。结果:pacNone、pac1a、pac1b、pac2b、pac3b 或 pacUnknown。
  case Pdf1.PdfAConformance of
    pac1b: Status.Caption := 'PDF/A-1b';
    pac2b: Status.Caption := 'PDF/A-2b';
    pacNone: Status.Caption := 'Not PDF/A';
  else
    Status.Caption := 'Unknown conformance';
  end;

  // 带逐问题诊断的完整校验器
  Validation := Pdf1.ValidatePdfA;
  Memo1.Lines.Add('Conformance: ' + GetEnumName(TypeInfo(TPdfAConformance),
    Ord(Validation.Conformance)));
  for Issue in Validation.Issues do
    Memo1.Lines.Add('- ' + Issue.Description);
end;

在 StandardsLab 中检查多种 PDF 标准

Demo\Delphi\StandardsLabDemo\CBuilder\StandardsLabDemo\Lazarus\StandardsLab 工程会加载或新建一份 PDF,依次运行 ValidatePdfAValidatePdfUaValidatePdfEValidatePdfXValidatePdfRValidatePdfVT,并在一个网格里展示每项检测到的合规级别与问题数。它们的 Save 按钮会分别调用 SaveAsPdfASaveAsPdfUaSaveAsPdfESaveAsPdfXSaveAsPdfRSaveAsPdfVT,使你无需自写 harness 就能看清标识符输出工作流。

生成 Preflight 报告

FPdfPreflightReport 单元把 ValidatePdfAValidatePdfUaValidatePdfEValidatePdfXValidatePdfRValidatePdfVT 封装成一个统一的报告对象。Demo\Delphi\PreflightReportDemo\Lazarus\PreflightReportDemo\CBuilder\PreflightReport 让用户挑选标准、生成汇总、查看状态、优先级、问题分类、分类计数、下一步动作、问题代码与建议动作,在 text、Markdown、JSON 与 CSV 之间切换预览,并导出 TXT、HTML、Markdown、JSON 或 CSV 报告。跨三平台的控制台工作流把同一条报告路径暴露为脚本化流程:含输入/输出参数、可选密码、输出格式选择中新增 plan / actionplan、标准过滤、可选的单文件 attach=output.pdf 报告嵌入、failon= CI 闸口退出码、batch=list.txt 处理、batchdir=folder 目录扫描(含可选递归及稳定的路径排序处理)、outdir=reports 报告路由、对重名输入做冲突安全的报告命名、含汇总与标准状态计数的 TXT / JSON / HTML 汇总、按每项重复运行设置的 CSV 行清单,以及面向脚本与 CI 任务的无参数示例模式。报告会注明内置校验器覆盖标识符级和部分文件级检查,而完整内容级 preflight 仍可委托给专用校验引擎。并新增 Delphi GUI 预览功能,在 Action Plan 视图中将未通过的标准、优先级、问题代码与建议动作汇总为整改清单。Demo\Delphi\PreflightReportCliDemo\Lazarus\PreflightReportCliDemo\CBuilder\PreflightReportCli 把同一条报告路径暴露为跨三平台的控制台工作流

流式加载与大型文档

使用 LoadCustomDocument 按需加载 PDF

// LoadCustomDocument 让 PDFium 从任何可 seek 的 TStream 按需
// 读取数据块。流不会被复制到内存里,因此多 GB PDF、远程
// HTTP body 流以及数据库支持的来源都无需预先缓冲就能使用。
var
  FileStream: TFileStream;
begin
  // 从文件流式读取(不在内存中复制)
  FileStream := TFileStream.Create('C:\Huge.pdf',
    fmOpenRead or fmShareDenyWrite);
  Pdf1.LoadCustomDocument(FileStream, True{AOwnsStream});
  // ^^ 所有权已转交 —— Pdf1 在 UnloadDocument 时释放 FileStream
  Pdf1.Active := True;
  ShowMessage('Pages: ' + IntToStr(Pdf1.PageCount));
end;

// 外部拥有的流(调用方在 UnloadDocument 之后释放)
var
  Stream: TFileStream;
begin
  Stream := TFileStream.Create('C:\Live.pdf',
    fmOpenRead or fmShareDenyNone);
  try
    Pdf1.LoadCustomDocument(Stream, False);
    Pdf1.Active := True;
    DoWork;
    Pdf1.Active := False;
  finally
    Stream.Free;
  end;
end;

异步取消与渐进式渲染

协作式取消令牌

// FPdfAsync 暴露 IPdfCancellationToken /
// IPdfCancellationTokenSource,提供从 UI 取消的语义,
// 适用于长耗时的导出与渲染路径。
uses FPdfAsync;

var
  CancelSource: IPdfCancellationTokenSource;
  CancelToken:  IPdfCancellationToken;
begin
  CancelSource := PdfCancellationTokenSource;
  CancelToken  := CancelSource.Token;

  // ... 用户点击 Cancel ...
  CancelSource.Cancel;

  // worker 周期性检查 CancelToken.IsCancelled,
  // 渲染路径则通过 PDFium 的 IFSDK_PAUSE 回调进行轮询。
  if CancelToken.IsCancelled then
    Memo1.Lines.Add('Cancelled by user');
end;

可取消的渐进式页面渲染

// RenderPageProgressive 让高 DPI 的长耗时渲染在用户点击 Cancel 时
// 可以中途取消,而不是阻塞调用方直到完成。
var
  Status: TPdfProgressiveStatus;
  Bitmap: TBitmap;
begin
  Bitmap := TBitmap.Create;
  try
    Bitmap.PixelFormat := pf32bit;
    Bitmap.SetSize(2480, 3508); // A4 @ 300 DPI

    Status := Pdf1.RenderPageProgressive(Bitmap, 0, 0, Bitmap.Width,
      Bitmap.Height, CancelToken, ro0, [reAnnotations], clWhite);

    case Status of
      prsDone:      SaveBitmap(Bitmap);
      prsCancelled: Memo1.Lines.Add('Render cancelled — partial result available');
      prsFailed:    Memo1.Lines.Add('PDFium reported FPDF_RENDER_FAILED');
    end;
  finally
    Bitmap.Free;
  end;
end;

用 TPdfFuture 在后台线程执行渲染

// TPdfFuture<T> 在后台线程上启动 worker,并把
// TPdfFutureResult<T> 信封投递回主线程。
//
// 重要:TPdf 会对单个实例的渲染调用做序列化,但 worker
// 仍负责调度和文档生命周期。渲染进行中不要改动 TPdf;
// 批量导出通常每个文件用独立的 TPdf。
type
  TRenderResult = record
    Bitmap : TBitmap;
    PageNo : Integer;
  end;

var
  Future: TPdfFuture<TRenderResult>;
begin
  Future := TPdfFuture<TRenderResult>.Create(
    function (const ACancelToken: IPdfCancellationToken): TRenderResult
    var
      LocalPdf: TPdf;
    begin
      LocalPdf := TPdf.Create(nil);
      try
        LocalPdf.FileName := 'C:\Huge.pdf';
        LocalPdf.Active   := True;
        LocalPdf.PageNumber := 1;
        Result.Bitmap := LocalPdf.RenderPage(0, 0, 2480, 3508);
        Result.PageNo := 1;
      finally
        LocalPdf.Free;
      end;
    end,
    procedure (const AResult: TPdfFutureResult<TRenderResult>)
    begin
      case AResult.State of
        pfsSuccess:   PaintBitmapToView(AResult.Value.Bitmap);
        pfsCancelled: Log.Add('Cancelled');
        pfsFailed:    Log.Add('Worker failed: ' + AResult.ErrorMessage);
      end;
    end);
end;

变换矩阵

组合 Translate / Scale / Rotate / Skew

// FPdfMatrix 封装 PDFium 的 FS_MATRIX,让调用方
// 声明式地构建变换并传给 FPDFPageObj_SetMatrix。
uses FPdfMatrix, FPdfView;

var
  M: TPdfMatrix;
  RawMatrix: FS_MATRIX;
  PageObj: FPDF_PAGEOBJECT;
begin
  M := TPdfMatrix.Create;
  try
    M.Translate(72, 200);       // 右移 1 英寸,上移约 2.8 英寸
    M.Scale(0.5, 0.5);          // 半尺寸印章
    M.Rotate(15);               // 逆时针旋转 15 度
    // M.HorizontalFlip;
    // M.VerticalFlip;
    // M.CentralFlip;
    // M.Skew(10, 5);
    // M.Multiply(Other);       // 与另一个矩阵后乘

    // 应用到任何 PDFium 页面对象(文本/路径/图像/Form XObject)
    RawMatrix := M.Handle;
    FPDFPageObj_SetMatrix(PageObj, RawMatrix);
  finally
    M.Free;
  end;
end;

页面组装

按索引导入页面子集

// ImportPagesByIndex 按显式零基索引数组从源 PDF 拷贝页面到本文档。
// InsertAt = 0 在第 1 页之前插入;PageCount 则追加到末尾。
var
  Source: TPdf;
begin
  Source := TPdf.Create(nil);
  try
    Source.FileName := 'C:\Report.pdf';
    Source.Active   := True;

    // 从 Source 导入第 0、2、4 页(一基:第 1、3、5 页)
    // 并追加到 Pdf1 末尾。
    Pdf1.ImportPagesByIndex(Source, [0, 2, 4], Pdf1.PageCount);

    // 空数组表示导入全部源页面
    // Pdf1.ImportPagesByIndex(Source, [], 0);
  finally
    Source.Free;
  end;
end;

N-up 拼版输出

// ImportNPagesToOne 返回一份新的 TPdf,其页面是
// 本文档若干页按 NumX*NumY 的复合页。OutputWidth/Height
// 单位为 PDF 用户单位(1 单位 = 1/72 in)。
var
  Composite: TPdf;
begin
  Pdf1.FileName := 'C:\Slides.pdf';
  Pdf1.Active   := True;
  // 4-up A4 横向:842 x 595 pt,2 列 x 2 行
  Composite := Pdf1.ImportNPagesToOne(842, 595, 2, 2);
  try
    if Composite <> nil then
      Composite.SaveAs('C:\Slides_4up.pdf');
  finally
    Composite.Free;
  end;
end;

原地重排页面

// MovePages 接收要移动的页面零基索引,以及移动完成后
// 第一个被移动页面的目标索引。其他页面会在被移动块周围
// 移位,使文档长度保持不变。
//
// 例:在页面编号为 [0,1,2,3,4] 的 5 页文档中,
// MovePages([2, 3], 0) 会重排为 [2, 3, 0, 1, 4]。
if not Pdf1.MovePages([2, 3], 0) then
  ShowMessage('Invalid indices passed to MovePages');

通过 Form XObject 页面复用做水印

// CreateXObjectFromPage 从任何 TPdf 的任意页面生成可复用的
// Form XObject 句柄。把该句柄盖到本文档你想要的任意多页上 ——
// 每个印章都是单个 PDFium 页面对象,可通过矩阵 API 定位、
// 缩放和旋转。
uses FPdfMatrix, FPdfView;

var
  WatermarkSource: TPdf;
  XObj:            TPdfXObject;
  PageObj:         FPDF_PAGEOBJECT;
  M:               TPdfMatrix;
  RawMatrix:       FS_MATRIX;
  I:               Integer;
begin
  WatermarkSource := TPdf.Create(nil);
  try
    WatermarkSource.FileName := 'C:\Watermarks\Confidential.pdf';
    WatermarkSource.Active   := True;

    // 把 WatermarkSource 的第 0 页封装为可复用的 XObject
    XObj := Pdf1.CreateXObjectFromPage(WatermarkSource, 0);
    try
      for I := 1 to Pdf1.PageCount do
      begin
        Pdf1.PageNumber := I;
        PageObj := Pdf1.InsertFormObjectFromXObject(XObj);
        if PageObj = nil then Continue;

        // 将水印居中放置
        M := TPdfMatrix.Create;
        try
          M.Scale(0.5, 0.5);
          M.Translate(0.25 * Pdf1.PageWidth, 0.5 * Pdf1.PageHeight);
          RawMatrix := M.Handle;
          FPDFPageObj_SetMatrix(PageObj, RawMatrix);
        finally
          M.Free;
        end;

        Pdf1.UpdatePage;
      end;
    finally
      XObj.Free; // 关闭 FPDF_XOBJECT 句柄
    end;

    Pdf1.SaveAs('C:\Watermarked.pdf');
  finally
    WatermarkSource.Free;
  end;
end;

Demo\Delphi\WatermarkStampDemo\Lazarus\WatermarkStampDemo\CBuilder\WatermarkStamp 工程把这一模式封装为可运行工作流:创建目标 PDF 与可复用印章 PDF,用 CreateXObjectFromPage 封装印章页,把同一个 Form XObject 插入到每一个目标页面,并通过 TPdfMatrix 变换应用居中水印和右上印章,可选地加上页码标签后保存结果。

图像插入(直接 AddImage 重载)

添加已注册的图像文件或 TBitmap

// AddImage(FileName) 接收 VCL 或 LCL 图形单元中注册的任何格式
// (BMP、PNG via PngImage、JPG 等)。
Pdf1.AddImage('C:\Photo.png', 100, 500, 200, 150);

// AddImage(TBitmap) 跳过 TPicture 中间层,
// 适合调用方已经手握来自渲染或批量生成的 TBitmap。
var
  Bitmap: TBitmap;
begin
  Bitmap := Pdf1.RenderPage(0, 0, 595, 842);
  try
    Pdf1.PageNumber := 2;
    Pdf1.AddImage(Bitmap, 50, 50, 250, 350);
    Pdf1.UpdatePage;
  finally
    Bitmap.Free;
  end;
end;

Demo\Delphi\ImageToPDFDemo\CBuilder\ImageToPDFDemo\Lazarus\ImageToPDF 工程把这一思路扩展为完整的批量工作流:选中多张图像文件、预览所选项、每张图像创建一页 PDF、把每张图像缩放到 A4 纵向或横向页面,保存结果并打开生成的 PDF。

查看器搜索高亮

对当前页高亮每一个匹配

var
  MatchCount: Integer;
begin
  // 在视图当前页的每个匹配上绘制一层 clYellow 蒙版。
  // 切换到其他页面时高亮会自动清除。
  PdfView1.HighlightColor := clYellow;
  MatchCount := PdfView1.HighlightSearchText('invoice', False{Case}, True{Word});
  Status.Caption := Format('%d match(es) on this page', [MatchCount]);

  // 在翻页前以编程方式移除高亮
  PdfView1.ClearHighlight;
end;

查看器布局与页面颜色

Fit 模式与页面背景

// FitMode 让长文档在 Resize 或翻页时保持合适的框定。
// 直接设置 Zoom 会取消 FitMode(它回退到 pfmNone)。
PdfView1.FitMode := pfmFitPage;       // 整页适应视口
// PdfView1.FitMode := pfmFitWidth;   // 页面宽度对齐视口宽度
// PdfView1.FitMode := pfmActualSize; // 100%

// PageColor 把渲染的 PDF 页与宿主控件的 Color 解耦 ——
// 典型的深色模式查看器配置:滚动区保持深色,PDF 页保持纸白色。
PdfView1.Color     := clBlack;        // 滚动区
PdfView1.PageColor := clWhite;        // PDF 页面背景

// 可选的投影阴影与页面边框,让页面从深色背景中浮起
PdfView1.PageShadowSize  := 6;
PdfView1.PageShadowColor := $00404040;
PdfView1.PageBorderColor := clGray;

在 ViewerInteractionLab 中探索查看器交互

Demo\Delphi\ViewerInteractionLabDemo\CBuilder\ViewerInteractionLabDemo\Lazarus\ViewerInteractionLab 工程把现代 TPdfView 的交互面板集成到一个紧凑表单中:打开或新建示例 PDF,切换 DisplayMode,应用 FitMode,更改 PageColor,旋转页面,用 HighlightSearchText 高亮当前页搜索命中,启用或关闭用户文本选择,查看 SelectedText,调用 SelectAllCopySelectionToClipboardClearSelection,并在鼠标在页面上移动时在状态栏看到 DeviceToPage 坐标实时更新。

在 SearchAndSelect 中搜索与选择文本

Demo\Delphi\SearchAndSelectDemo\CBuilder\SearchAndSelectDemo\Lazarus\SearchAndSelect 工程把搜索与选择查看器工作流单独抽出为样例:打开或新建 PDF,列出所有页面的搜索结果(含页码、字符索引和预览文本),支持上/下一项导航与双击结果跳转,用 HighlightSearchText 高亮当前页匹配,提供区分大小写与整词选项,切换 AllowUserTextSelection,预览 SelectedText,通过按钮驱动 SelectAllCopySelectionToClipboardClearSelection,并允许用户在单页和跨页显示模式间切换。

在 PrintPreferences 中读取 PDF 打印首选项

Demo\Delphi\PrintPreferencesDemo\CBuilder\PrintPreferencesDemo\Lazarus\PrintPreferences 工程在打印之前读取作者的打印首选项。它们显示 PrintCopiesPrintPageRangesPrintScalingPrintPaperHandling,可将作者提供的份数与范围复制到打印输入框,并演示 SetPdfPrintPaperHandlingDevMode 如何把 PDF 双面意图映射进 Windows DEVMODE

在 PrintPDF 中执行标准 PDF 打印

Demo\Delphi\PrintPDFDemo\CBuilder\PrintPDFDemo\Lazarus\PrintPDF 工程展示标准打印工作流:打开 PDF、预览页面、在平台打印对话框中选择页面范围与份数、尊重 collate 模式、通过 TPdf.RenderPage 渲染每一页,并以可取消的方式展示打印进度。Delphi 样例还支持拖放 PDF 文件以便快速加载。

在 MultiPageViewer 中实现多页快速查看

Demo\Delphi\MultiPageViewerDemo\CBuilder\MultiPageViewerDemo\Lazarus\MultiPageViewer 工程演示连续视图、跨页视图、封面感知布局,以及常规翻页和缩放工作流。它们也适合测试非常大 PDF 的首屏速度与渲染响应:在大文件测试中,对于 Acrobat 或 Foxit 可能需要 20-30 秒才能显示首屏的 2.x GB 文档,通过 PDFiumPas 查看器路径可以几乎立即进入可用状态。

在 SplitView 中并排审阅

Demo\Delphi\SplitViewDemo\CBuilder\SplitViewDemo\Lazarus\SplitView 工程展示并排 PDF 审阅。C++Builder 与 Lazarus 样例聚焦于二/三面板对比、活动视图选择、可选的同步导航命令、共享缩放预设以及对所选视图或全部已加载视图的旋转。可用它们对比大型文档,同时保持首屏可用视图和后续翻页渲染的响应;同样的 2.x GB PDF 文件在 Acrobat 或 Foxit 中可能需要 20-30 秒才能打开,但通过 PDFiumPas 查看器路径几乎立即可用。

在 SecurityAudit 中审计 PDF 风险面

Demo\Delphi\SecurityAuditDemo\CBuilder\SecurityAuditDemo\Lazarus\SecurityAudit 工程以只读方式打开 PDF,并列出权限状态、嵌入附件、文档级 JavaScript 动作、URI 与 Launch 链接注释、Web 链接、签名汇总、XFA 状态、V8 辅助可用性以及不支持特性的回调。同一组汇总与发现行可以保存或复制为 TXT 审计报告,也可以保存为结构化 JSON。这些样例旨在作为宿主应用的风险面板,而非恶意软件检测。

查看器链接处理

带按动作白名单的安全点击-跟随

// LinkOptions 控制四种 PDF 链接动作的自动处理。
// 默认仅启用 goto 和 URI;launch(运行程序)与
// embedded GotoR(跳转到另一份文件)默认关闭,
// 避免误点击触发任意代码。
PdfView1.LinkOptions :=
  [loAutoGoto, loAutoOpenURI];  // 安全默认

// OnAnnotationLinkClick 对文档内目标(页面跳转、命名目标、
// 动作链)触发。把 Handled = True 设上可阻止视图自动跟随链接。
procedure TForm1.PdfView1AnnotationLinkClick(Sender: TObject;
  LinkIndex: Integer; const Action: TPdfAction;
  var Handled: Boolean);
begin
  if Action.Kind = paUri then
  begin
    if MessageDlg('Open ' + Action.Uri + '?', mtConfirmation, [mbYes, mbNo], 0)
      <> mrYes then
      Handled := True;  // 抑制自动处理
  end;
end;

// OnWebLinkClick 对 PDFium 的 Web 链接扫描器
// 发现的 URI 字符串触发(即便没有 /A <</S/URI...>> 注释,
// 也能自动检出文本流中的 URL)。
procedure TForm1.PdfView1WebLinkClick(Sender: TObject;
  WebLinkIndex: Integer; const Url: WString;
  var Handled: Boolean);
begin
  Log.Add('Web link clicked: ' + string(Url));
end;

查看器表单控件编辑

选择与撤销/重做

// 在当前聚焦的 AcroForm 控件上,六个新方法驱动 PDFium 的
// 表单编辑历史。在无控件聚焦或文档不含 AcroForm 时,
// 这六个方法都会安全地短路。
procedure TForm1.btnSelectAllClick(Sender: TObject);
begin
  PdfView1.SelectAllFormText;
  EditMenuCopy.Caption := 'Copy: ' + string(PdfView1.GetSelectedFormText);
end;

procedure TForm1.btnUndoClick(Sender: TObject);
begin
  btnUndo.Enabled := PdfView1.FormCanUndo;
  btnRedo.Enabled := PdfView1.FormCanRedo;
  if PdfView1.FormCanUndo then
    PdfView1.FormUndo;
end;

procedure TForm1.btnRedoClick(Sender: TObject);
begin
  if PdfView1.FormCanRedo then
    PdfView1.FormRedo;
end;

为自助终端锁定查看器

禁用翻页手势

// 三个属性默认都是 True,因此现有应用升级后行为不变。
// 把它们翻成 False 可锁定自助终端、预览面板或只读嵌入,
// 而无需子类化 TPdfView。
PdfView1.AllowUserPageChange       := False;  // PgUp/PgDn/Ctrl+Home/End
PdfView1.ChangePageOnMouseScrolling := False; // 滚轮上下翻页
PdfView1.AllowUserTextSelection    := False;  // 鼠标/键盘文本选择

// Ctrl+滚轮保留给缩放,无论 ChangePageOnMouseScrolling 如何,
// 都会被导航处理器跳过。

缩略图侧栏

把 TPdfThumbnailView 与 TPdfView 绑定

// TPdfThumbnailView(单元 FPdfThumbnail)在可滚动侧栏内
// 每行渲染一个页面缩略图。
uses FPdfThumbnail;

procedure TForm1.FormCreate(Sender: TObject);
begin
  ThumbView.Pdf              := Pdf1;
  ThumbView.ThumbnailWidth   := 120;
  ThumbView.ThumbnailHeight  := 160;
  ThumbView.SelectionColor   := $00CFA85F;  // 暖色高亮
  ThumbView.OnPageClick      := ThumbViewPageClick;
end;

procedure TForm1.ThumbViewPageClick(Sender: TObject; PageIndex: Integer);
begin
  PdfView1.PageNumber := PageIndex + 1; // PageIndex 是零基
end;

procedure TForm1.PdfView1PageNumber变更(Sender: TObject);
begin
  ThumbView.CurrentPageIndex := PdfView1.PageNumber - 1;
end;

协作式可取消批量导出

多文件 PDF 到 JPG,含逐文件与逐页进度

// Demo\Delphi\BatchExport、Demo\CBuilder\BatchExport 和
// Demo\Lazarus\BatchExport 使用的模式:每个文件一份 TPdf,
// IPdfCancellationToken 用于从 UI 取消,TPdfStreamAdapter 用于缓冲文件加载。
uses FPdfAsync;

procedure ExportBatch(const Files: TArray<string>;
  const OutDir: string; DPI: Integer; Quality: Integer;
  const ACancelToken: IPdfCancellationToken);
var
  I, J: Integer;
  Job:  TPdf;
  Bmp:  TBitmap;
  Jpeg: TJPEGImage;
begin
  for I := 0 to High(Files) do
  begin
    if ACancelToken.IsCancelled then Break;
    OverallProgress.Position := I;

    Job := TPdf.Create(nil);
    try
      Job.FileName := Files[I];
      Job.Active   := True;
      PageProgress.Max := Job.PageCount;

      for J := 1 to Job.PageCount do
      begin
        if ACancelToken.IsCancelled then Break;
        PageProgress.Position := J;

        Job.PageNumber := J;
        Bmp := Job.RenderPage(
          0, 0,
          Round(Job.PageWidth  * DPI / 72),
          Round(Job.PageHeight * DPI / 72));
        try
          Jpeg := TJPEGImage.Create;
          try
            Jpeg.CompressionQuality := Quality;
            Jpeg.Assign(Bmp);
            Jpeg.SaveToFile(Format('%s\%s.p%.3d.jpg',
              [OutDir, ExtractFileName(Files[I]), J]));
          finally
            Jpeg.Free;
          end;
        finally
          Bmp.Free;
        end;
      end;
    finally
      Job.Free;
    end;
  end;
end;

查看器坐标与命中测试

适配当前页并检查鼠标下方文本

procedure FitCurrentPage;
begin
  PdfView1.Zoom := PdfView1.PageZoom[PdfView1.PageNumber];
end;

procedure InspectViewerPoint(X, Y: Integer);
var
  PageNo: Integer;
  PageX, PageY: Double;
  CharIndex: Integer;
  Ch: WString;
begin
  PageNo := PdfView1.PageNumber;
  if not PdfView1.DeviceToPage(X, Y, PageNo, PageX, PageY) then
    Exit;

  CharIndex := PdfView1.CharacterIndexAtPos(X, Y, 8, 8);
  if CharIndex >= 0 then
  begin
    Ch := PdfView1.Text(CharIndex, 1);
    ShowMessage(Format('Page %d, X %.2f, Y %.2f, character %s',
      [PageNo, PageX, PageY, string(Ch)]));
  end;
end;

错误处理

稳健的 PDF 操作

function LoadPdfSafely(const FileName: string): Boolean;
begin
  Result := False;
  if not FileExists(FileName) then
    Exit;
  try
    Pdf1.FileName := FileName;
    Pdf1.Active := True;
    Result := Pdf1.Active;
  except
    Result := False;
  end;
end;

function ExtractTextSafely(PageNo: Integer): WString;
begin
  Result := '';
  if not Pdf1.Active then
    Exit;
  if (PageNo < 1) or (PageNo > Pdf1.PageCount) then
    Exit;
  Pdf1.PageNumber := PageNo;
  Result := Pdf1.Text;
end;

Tagged PDF 与无障碍

检测 Tagged PDF 并遍历结构树

// IsTagged 是一个轻量级 catalog 探测 —— 当 /StructTreeRoot 存在时为 True。
// StructureElements 把树物化为 TPdfStructureElement 记录的扁平数组,
// 含 type、title、alternate text、actual text、expansion text、language、
// level、parent index 以及 child / marked content / attribute 计数。
var
  Elements: TPdfStructureElements;
  I: Integer;
begin
  if not Pdf1.IsTagged then
  begin
    Log.Add('Document is NOT tagged — accessibility tools may struggle.');
    Exit;
  end;
  if Pdf1.Language = '' then
    Log.Add('Tagged PDF without /Lang — fails PDF/UA.');

  Elements := Pdf1.StructureElements;
  for I := 0 to High(Elements) do
    Log.Add(StringOfChar(' ', Elements[I].Level * 2)
      + Elements[I].StructType + ' "' + Elements[I].Title + '"');
end;

打印模式选择

设置 EMF / PostScript / Image-Mask 打印模式

// SetPdfPrintMode 是一个全局函数,映射到 PDFium 的
// FPDF_SetPrintMode。请按所用打印机驱动选择匹配的 TPdfPrintMode 值。
SetPdfPrintMode(pmEmf);                   // GDI EMF(默认)
// SetPdfPrintMode(pmTextOnly);           // 纯文本渲染
// SetPdfPrintMode(pmPostScript2);        // PostScript Level 2
// SetPdfPrintMode(pmPostScript3);        // PostScript Level 3
// SetPdfPrintMode(pmPostScript2PassThrough);
// SetPdfPrintMode(pmPostScript3PassThrough);
// SetPdfPrintMode(pmEmfImageMasks);      // EMF + image masks
// SetPdfPrintMode(pmPostScript3Type42);  // PostScript 3 + Type 42 字体

读取作者意图的打印设置

// PrintCopies、PrintPageRanges、PrintScaling 和 PrintPaperHandling
// 是查看器首选项字典中的条目 —— 它们编码文档作者希望 PDF 阅读器默认采用的值。
var
  Ranges: TPrintPageRanges;
  Range: TPrintPageRange;
begin
  ShowMessage('Suggested copies: ' + IntToStr(Pdf1.PrintCopies));
  ShowMessage('Print scaling: ' + GetEnumName(TypeInfo(TPrintScaling),
    Ord(Pdf1.PrintScaling)));

  Ranges := Pdf1.PrintPageRanges; // 一基范围
  for Range in Ranges do
    Log.Add(Format('Pages %d..%d', [Range.First, Range.Last]));

  if SetPdfPrintPaperHandlingDevMode(PrinterDevMode, Pdf1.PrintPaperHandling) then
    ApplyPrinterDevMode(PrinterDevMode);
end;

文档级 JavaScript 动作

枚举名树中的 JavaScript

// 文档级 JavaScript 存储在 /Names /JavaScript 名树中。
// JavaScriptAction[i] 返回一项;JavaScriptActions 返回完整数组。
var
  I: Integer;
  Action: TPdfJavaScriptAction;
begin
  for I := 0 to Pdf1.JavaScriptActionCount - 1 do
  begin
    Action := Pdf1.JavaScriptAction[I];
    Memo1.Lines.Add('Name:   ' + string(Action.Name));
    Memo1.Lines.Add('Script: ' + string(Action.Script));
    Memo1.Lines.Add('---');
  end;
end;

性能提示

优化 PDF 操作

procedure ProcessMultiplePages;
var
  I: Integer;
  PageText: WString;
begin
  for I := 1 to Pdf1.PageCount do
  begin
    Pdf1.PageNumber := I;
    PageText := Pdf1.Text;
    ProcessPageText(PageText);
  end;
end;

procedure SetOptimalRenderOptions;
begin
  PdfView1.Options := [reAnnotations, reLcd];
end;

// 零拷贝渲染路径(自 v1.21.0 起为默认):当调用方传入预分配的位图时,
// RenderPage 直接写入目标 TBitmap 的 DIB 缓冲区,避免一次 width * height * 4 字节拷贝。
procedure RenderIntoCallerBitmap(Bitmap: TBitmap);
begin
  Bitmap.PixelFormat := pf32bit;
  Bitmap.SetSize(2480, 3508); // A4 @ 300 DPI
  Pdf1.RenderPage(Bitmap, 0, 0, Bitmap.Width, Bitmap.Height);
end;