【问题标题】:Adding Multiple Bookmark Using ItextSharp使用 ItextSharp 添加多个书签
【发布时间】:2019-10-26 21:17:02
【问题描述】:

我想根据 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&lt;Dictionary&lt;string, object&gt;&gt; 集合。但是字典的键值是“字符串”。所以我不能将书签添加到列表中,因为键值不能重复。抛出异常是“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 的多个书签,或者您知道如何更正此代码?

【问题讨论】:

  • 尝试添加两个其他代码
    stamp.JavaScript ="var root = this.bookmarkRoot;root.createChild("+title+", 'this.pageNum = ' + 5, 5);"
    stamp.AddJavaScript(title, "var root = this.bookmarkRoot;root.createChild(" + title + ", 'this.pageNum = ' + 5, 5);");&lt;br/&gt; 这些代码似乎有效,但问题是这些代码不是插入书签而是 javascipt,所以每次当我打开和关闭pdf,书签加倍。我仍然需要帮助

标签: c# itext bookmarks


【解决方案1】:

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

我在循环中定义了Dictionary&lt;string, object&gt; bm = new Dictionary&lt;string, object&gt;();,但我错过了一个代码。工作代码如下


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();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-03
    • 1970-01-01
    • 2018-11-17
    • 2015-02-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多