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