使用ItextSharp添加多个书签

问题描述 投票:0回答:1

我想基于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();

问题在这里是使用List<Dictionary<string, object>>集合的PdfStamper.Outline(stamp.Outlines)。但是字典的关键值是“字符串”。因此,由于键值无法重复,因此我无法将书签添加到列表中。抛出异常是“ System.ArgumentException:'已添加具有相同键的项。'“

但是我找不到其他任何使用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,或者您知道如何更正此代码?

c# itext bookmarks
1个回答
0
投票

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

我在循环中定义了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();
© www.soinside.com 2019 - 2024. All rights reserved.