PDFium Delphi Component Docs

ExtractAttachmentsToStreams 方法

组件: TPdf  ·  单元: PDFium
解码每个文档级内嵌附件,并把有效负载字节写入调用方提供的流,在明确的大小、分块、取消和错误报告控制之下

语法

function ExtractAttachmentsToStreams(const Destinations: array of TStream; const Options: TPdfAttachmentBatchOptions; out Report: TPdfAttachmentBatchReport; const CancellationToken: IPdfCancellationToken = nil): Boolean;

DestinationsTStream 开放数组。每个附件一个流,按文档顺序。为 nil 的槽位会跳过该附件而不写入任何内容。流仍由调用方拥有
OptionsTPdfAttachmentBatchOptions。批量限制与行为:MaxAttachments、MaxFileBytes、MaxTotalBytes、ChunkBytes 和 StopOnError。从 TPdfAttachmentBatchOptions.Default 开始
ReportTPdfAttachmentBatchReport。返回时携带每个附件一个条目(Metadata、State、BytesWritten、ErrorMessage)以及聚合计数器(AttachmentCount、ExtractedCount、SkippedCount、FailedCount、BytesWritten、PeakBufferBytes、Cancelled、Completed)
CancellationTokenIPdfCancellationToken。可选令牌,在每个附件之前和写入分块之间轮询;nil 表示批量处理不进行取消检查
ResultBoolean。只有当批量处理在没有取消且零个附件失败的情况下完成时才为 True;跳过的条目不计为失败

说明

逐个索引读取 Attachment 的批量对应版本。文档附件只被捕获一次,每个有效负载被解码并推入其目标流,每个附件的结果都记录在 Report.Items 中

目标数组必须为文档中的每个附件恰好包含一个流,否则在读取任何字节之前会引发 EPdfError。数组中的 nil 条目将该附件标记为已跳过(paesSkipped),而不是中止批量处理

选项会预先验证,无效时引发 EPdfError:MaxAttachments 必须大于零,MaxFileBytes 和 MaxTotalBytes 不能为负,ChunkBytes 必须大于零。TPdfAttachmentBatchOptions.Default 提供 10000 个附件、每文件 256 MB 限制、总计 1 GB 限制、1 MB 写入分块以及 StopOnError = True

每个附件最终处于 TPdfAttachmentExtractionState 状态之一:成功为 paesExtracted,目标为 nil 时为 paesSkipped,有效负载无法打开或解码时为 paesUnreadable,超过大小限制时为 paesFileLimit 或 paesAggregateLimit,目标流引发异常时为 paesWriteFailed,令牌触发时为 paesCancelled。设置了 StopOnError 时,第一个失败会停止循环,其余条目保持 paesNotProcessed

只有当 Report.Completed 被设置(无取消、没有未处理的条目)且 FailedCount 为零时,函数才返回 True。取消路径返回 False 并设置 Report.Cancelled,而不是引发异常

备注

示例

var
  Options: TPdfAttachmentBatchOptions;
  Report: TPdfAttachmentBatchReport;
  Streams: array of TStream;
  I: Integer;
begin
  Pdf1.FileName := 'with-attachments.pdf';
  Pdf1.Active := True;
  SetLength(Streams, Pdf1.AttachmentCount);
  for I := 0 to High(Streams) do
    Streams[I] := TFileStream.Create('out\' + Pdf1.AttachmentName[I], fmCreate);
  try
    Options := TPdfAttachmentBatchOptions.Default;
    Options.StopOnError := False;
    if not Pdf1.ExtractAttachmentsToStreams(Streams, Options, Report) then
      ShowMessage(Format('%d extracted, %d failed, %d skipped',
        [Report.ExtractedCount, Report.FailedCount, Report.SkippedCount]));
  finally
    for I := 0 to High(Streams) do
      Streams[I].Free;
  end;
end;

参见

ReadAttachmentMetadata, Attachment, AttachmentCount, AttachmentName