ドキュメントを単一のドキュメントにマージするために.NET用のiText7を使用しようとしましたが、エラーが発生した後、2番目のアプリケーションを作成しましたが、iTextSharp 5.5.9を使用しました。
同じ機能が新しいバージョンよりも 4 倍高速に動作することに驚きました。
以下は、バージョン 5 の私のコードです。
private bool Merge5(IEnumerable<string> fileNames, string targetPdf)
{
bool merged = true;
using (FileStream stream = new FileStream(targetPdf, FileMode.Create))
{
Document document = new Document();
PdfCopy pdf = new PdfCopy(document, stream);
PdfReader reader = null;
try
{
document.Open();
foreach (string file in fileNames)
{
reader = new PdfReader(file);
//not needed I guess
reader.ConsolidateNamedDestinations();
pdf.AddDocument(reader);
reader.Close();
}
}
catch (Exception)
{
merged = false;
if (reader != null)
{
reader.Close();
}
}
finally
{
if (pdf != null)
{
pdf.Close();
}
if (document != null)
{
document.Close();
}
}
}
return merged;
}
バージョン 7 のコード:
private void Merge7(List<string> src, string dest)
{
PdfDocument pdfDocument1;
try
{
pdfDocument1 = new PdfDocument(new PdfReader(src[0]), new PdfWriter(dest));
}
catch (Exception e)
{
Debug.WriteLine(e);
throw;
}
var path = string.Empty;
for (int i = 1, max = src.Count; i < max; i++)
{
path = src[i];
try
{
PdfDocument pdfDocument2 = new PdfDocument(new PdfReader(path));
var pagesCount = pdfDocument2.GetNumberOfPages();
pdfDocument2.CopyPagesTo(1, pagesCount, pdfDocument1);
pdfDocument2.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
try
{
pdfDocument1.Close();
}
catch (Exception e)
{
Debug.WriteLine("Dest: " + dest);
Debug.WriteLine("Src: " + path);
Console.WriteLine(e);
}
}
私の呼び出しは次のようになります。
string dest = @"E:\TEST\final.pdf";
var files = Directory.GetFiles(@"E:\TEST\PDFS", "*.pdf").OrderBy(x => x).Take(1000).ToList();
Stopwatch sw = new Stopwatch();
sw.Start();
Merge5(files, dest);
sw.Stop();
Debug.WriteLine(sw.Elapsed);
最初のテスト:
1000 個の PDF ファイル (同じファイルですが、1000 回コピーされ、サイズは 370 KB) の場合、次の結果が得られます。
| 1 pass | 2 pass | 3 pass |
---------------------------------------------------------------------------
iText7 for .NET | 00:00:13.4088770 | 00:00:13.5490370 | 00:00:14.2491171
iTextSharp 5.5.9 | 00:00:03.5330538 | 00:00:03.2058272 | 00:00:03.2854776
2 番目のテスト:
1000 個の PDF ファイル (同じファイルですが、1000 回コピーされ、サイズは 606 KB) の場合、次の結果が得られます。
| 1 pass | 2 pass | 3 pass |
---------------------------------------------------------------------------
iText7 for .NET | 00:00:25.5538607 | 00:00:24.6525861 | 00:00:26.7326629
iTextSharp 5.5.9 | 00:00:06.0918370 | 00:00:05.5687955 | 00:00:06.0283861
パフォーマンスに大きな違いが生じる理由は何ですか?
マージ関数を最適化して、より高速にすることはできますか (バージョン 5 のように高速)?
バージョン 7 を使用したいのですが、パフォーマンスのために古いバージョンを使用する可能性があります。