5,913
社区成员




大家好,
我有一個租戶詳細資料 PDF 文件,有 500 多頁。其中在每個頁面上顯示租戶 ID。一名租戶的記錄分佈在多頁上。我需要根據每個租戶 ID 拆分 pdf 文件。
[例如:租戶1在前7頁有數據;租戶 2 從 8-19頁…;所以分割後我的第一個pdf檔應該包含第1頁到第7頁;第二個應該包含 8 到 19...等等]。
請問這個要如何使用DELPHI達成,請各位提供方式,
謝謝
//测试用的Delphi版本 : Delphi 10.3.3
//使用Debenu PDF Library , 请自己下载此软件和找到序列号, 并把代码里面的**********替换为序列号
//调用方式:
{procedure TForm1.Button1Click(Sender: TObject);
begin
with TSplitPdf.Create do
begin
Split('D:\Test.pdf', 'D:\');
Free;
end;
end;}
unit uSplitPdf;
interface
uses System.Classes, System.SysUtils, DebenuPDFLibrary;
type
TSplitPdf = class(TObject)
private
SourceDoc: Integer;
FileName, DestPath: String;
PDFLib: TDebenuPDFLibrary;
IDList: array of Integer;
procedure CreateList;
procedure DoSplit;
procedure SaveFile(const PID, FromPage, ToPage: Integer);
public
procedure Split(const aFileName: String; const aDestPath: String = '');
constructor Create;
destructor Destroy; override;
end;
implementation
constructor TSplitPdf.Create;
begin
inherited;
PDFLib := TDebenuPDFLibrary.Create;
PDFLib.UnlockKey('******************'); //要把**********替换为产品序列号
end;
destructor TSplitPdf.Destroy;
begin
PDFLib.Free;
inherited;
end;
procedure TSplitPdf.Split(const aFileName, aDestPath: String);
begin
FileName := aFileName.Trim;
DestPath := aDestPath.Trim;
if DestPath = '' then //如果不提供目标目录, 则把目标目设为源文件的目录
DestPath := ExtractFilePath(FileName);
if Copy(DestPath, DestPath.Length, 1) <> '\' then
DestPath := DestPath + '\';
PDFLib.LoadFromFile(FileName, '');
SourceDoc := PDFLib.SelectedDocument;
CreateList;
DoSplit;
PDFLib.RemoveDocument(SourceDoc);
end;
procedure TSplitPdf.CreateList;
var
S: String;
I, P: Integer;
begin
with PDFlib do
begin
SelectDocument(SourceDoc);
SetLength(IDList, PageCount+1);
for I := 1 to PageCount do
begin
SelectPage(I);
S := GetPageText(0);
P := Pos('ID: ', S);
if P <> 0 then
IDList[I] := StrToInt(Copy(S, P+4, 4)) //假定格式如: ID: 1234
else
IDList[I] := -1;
end;
end;
end;
procedure TSplitPdf.DoSplit;
var
I, PID, Len, FromPage: Integer;
begin
PID := -1; FromPage := -1;
Len := Length(IDList) - 1;
for I := 1 to Len do
begin
if I > 100 then
begin
PID := PID;
end;
if I = 1 then
begin
FromPage := 1;
PID := IDList[1];
end;
if I = Len then
begin
if PID = IDList[Len] then
begin
SaveFile(PID, FromPage, Len)
end
else
begin
SaveFile(PID, FromPage, Len-1);
PID := IDList[Len];
SaveFile(PID, Len, Len);
end;
end;
if (I > 1) and (I < Len) then
begin
if IDList[I] > PID then
begin
SaveFile(PID, FromPage, I-1);
FromPage := I;
PID := IDList[I];
end;
end;
end;
end;
procedure TSplitPdf.SaveFile(const PID, FromPage, ToPage: Integer);
var
DestDoc: Integer;
begin
if PID = -1 then Exit;
with PDFLib do
begin
DestDoc := NewDocument;
SelectDocument(DestDoc);
CopyPageRanges(SourceDoc, Format('%d-%d',[FromPage, ToPage]));
DeletePages(1, 1);
SaveToFile(DestPath + 'ID' + PID.ToString + '.PDF');
RemoveDocument(DestDoc);
end;
end;
end.