function ExtractAttachmentsToStreams(const Destinations: array of TStream; const Options: TPdfAttachmentBatchOptions; out Report: TPdfAttachmentBatchReport; const CancellationToken: IPdfCancellationToken = nil): Boolean;
| Destinations | TStream 开放数组。每个附件一个流,按文档顺序。为 nil 的槽位会跳过该附件而不写入任何内容。流仍由调用方拥有 |
| Options | TPdfAttachmentBatchOptions。批量限制与行为:MaxAttachments、MaxFileBytes、MaxTotalBytes、ChunkBytes 和 StopOnError。从 TPdfAttachmentBatchOptions.Default 开始 |
| Report | TPdfAttachmentBatchReport。返回时携带每个附件一个条目(Metadata、State、BytesWritten、ErrorMessage)以及聚合计数器(AttachmentCount、ExtractedCount、SkippedCount、FailedCount、BytesWritten、PeakBufferBytes、Cancelled、Completed) |
| CancellationToken | IPdfCancellationToken。可选令牌,在每个附件之前和写入分块之间轮询;nil 表示批量处理不进行取消检查 |
| Result | Boolean。只有当批量处理在没有取消且零个附件失败的情况下完成时才为 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,而不是引发异常
ChunkBytes 控制该缓冲区推入流的精细程度,而不是分配大小。Report.PeakBufferBytes 记录使用的最大缓冲区
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;