使用 ItextSharp 添加多个书签

Adding Multiple Bookmark Using ItextSharp

我想在 pdf 上添加基于条形码的多个书签。条形码读取没问题。没有问题。但是在尝试添加书签时我做了一些研究并找到了以下答案。

Bookmark to specific page using iTextSharp 4.1.6

Add Page bookmarks to an existing PDF using iTextSharp using C# code

这些代码非常有用。但问题是这些代码只是一个书签。我不能在循环中添加多个书签。您可以在下面找到我为多个书签所做的相关代码

Dictionary<string, object> bm = new Dictionary<string, object>();
List<Dictionary<string, object>> bookmarks = new List<Dictionary<string, object>>();

foreach (var barcode in barcodes)
{

string title = barcode.Text.Substring(11, barcode.Text.Length - 11);
bm.Add("Title", title);
bm.Add("Action", "GoTo");
bm.Add("Page", barcode.Page.ToString() + " XYZ 0 0 0");

}

PdfStamper stamp = new PdfStamper(source, output);

stamp.Outlines = bookmarks;

stamp.Close();

问题出在 PdfStamper.Outline (stamp.Outlines) 使用 List<Dictionary<string, object>> 集合。但是Dictionary的键值为"string"。所以我不能将书签添加到列表中,因为键值不能重复。有一个异常抛出是 "System.ArgumentException: 'An item with the same key has already been added.'"

但是我找不到任何其他文档来使用 itextsharp 将书签植入 pdf。

我确信此代码仅适用于书签。您可以在下面找到示例。

Dictionary<string, object> bm = new Dictionary<string, object>();
List<Dictionary<string, object>> bookmarks = new List<Dictionary<string, object>>();

//foreach (var barcode in barcodes)
//{

string title = barcodes[0].Text.Substring(11, barcodes[0].Text.Length - 11);
bm.Add("Title", title);
bm.Add("Action", "GoTo");
bm.Add("Page", barcodes[0].Page.ToString() + " XYZ 0 0 0");

//}

PdfStamper stamp = new PdfStamper(source, output);

stamp.Outlines = bookmarks;

stamp.Close();

由于 stamp.Outlines 的性质,我认为此代码无法添加多个书签。 有没有其他方法可以使用 itextsharp 为 PDF 实现多个书签,或者您知道如何更正此代码吗?

所以我错过了一个简单的点。

我在循环中定义了Dictionary<string, object> bm = new Dictionary<string, object>();,但我漏掉了一个代码。工作代码如下


List<Dictionary<string, object>> bookmarks = new List<Dictionary<string, object>>();

foreach (var barcode in barcodes)
{
Dictionary<string, object> bm = new Dictionary<string, object>();
string title = barcode.Text.Substring(11, barcode.Text.Length - 11);
bm.Add("Title", title);
bm.Add("Action", "GoTo");
bm.Add("Page", barcode.Page.ToString() + " XYZ 0 0 0");
bookmarks.Add(bm);
}

PdfStamper stamp = new PdfStamper(source, output);

stamp.Outlines = bookmarks;

stamp.Close();