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

随声附和 提交于 2019-12-12 20:27:47

问题


My requirement is same as described in this question: Bookmark to specific page using iTextSharp 4.1.6

I tried the answer, but the last line gives my the following error:

Can not implicitly convert ArrayList to IList<Dictionar(strin,object)>

I am not sure how to correct it.

The line that gave error is, in the Answer 1 of above link

wri.Outlines = bookmarks

I modified the example like this:

List<Dictionary<string, object>> testData = new List<Dictionary<string, object>>(100);
// Just Sample data for understanding.
//for (int i = 0; i < 100; i++)
//{
var test = new Dictionary<string, object>
{
    { "Action", "GoTo"},
    { "Title", "Page1 0 H 0" },
    {"Page", "1 XYZ 0 " + h + " 0" }
};
testData.Add(test);
//}
wri.Outlines = testData;

Now after adding the bookmarks, I'm unable to open the PDF because the file has been corrupted.


回答1:


Please consult the official documentation.

Bookmarks are discussed in Chapter 7 where you'll find the BookmarkedTimeTable example. As you're working with iTextSharp (C#), not iText (Java), you'll want to look up the corresponding example in the list of examples ported to C#, more specifically BookmarkedTimeTable.cs.

Update after you updated the question:

Your error indicates that testdata isn't really of type IList<Dictionar(string,object)>; note that I've added a g to strin assuming that this is a typo in your question, not in your actual code.

Please start with the example from my book, and then change that example gradually until you break that code.

Update based on extra comment:

When a PDF is digitally signed, there is a limited number of operations that may (or may not) be allowed. See Which operations are allowed on a digitally signed PDF? Adding bookmarks is not an allowed operation, so you'll have to remove all signature fields before applying the change. Depending on whether or not you want to keep the empty signature field or completely remove the field, you'll use either the method clearSignatureField() or removeField() passing the name of a signature field as parameter. You can get an ArrayList of names using the getSignatureNames() method (see ÀcroFields).




回答2:


Try making it an actual ArrayList of Hashtables:

            var outlines = firstComponentPages.Select(x => new Hashtable()
            {
                {"Title", x.Value},
                {"Action", "GoTo"},
                {"Page", $"{x.Key} Fit"}
            }).ToList();


            var outlinesArrayList = new ArrayList();
            foreach (var outline in outlines)
            {
                outlinesArrayList.Add(outline);
            }
            copy.Outlines = outlinesArrayList;


来源:https://stackoverflow.com/questions/20702728/add-page-bookmarks-to-an-existing-pdf-using-itextsharp-using-c-sharp-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!