使用iTextSharp将书签添加到PDF

时间:2014-08-18 12:55:10

标签: pdf itextsharp bookmarks

我有一个很大的PDF文件,想要使用iTextSharp将一些页面复制到一个新的PDF文件中。 使用以下代码可以正常工作。

Dim sourceFullFilePathAndName As String = "src.pdf"
Dim outputFullFilePathAndName As String = "cpy.pdf"
Dim pageFirst As Integer = 5
Dim pageLast As Integer = 10

Using rdr As iTextSharp.text.pdf.PdfReader = New iTextSharp.text.pdf.PdfReader(sourceFullFilePathAndName)
    Dim docSrc As New iTextSharp.text.Document(rdr.GetPageSizeWithRotation(1))
    Using fs = New System.IO.FileStream(outputFullFilePathAndName, System.IO.FileMode.Create)
        Dim copy As New iTextSharp.text.pdf.PdfCopy(docSrc, fs)
        docSrc.Open()
        Dim bookmarks = New List(Of Dictionary(Of String, Object))() 'New ArrayList() '// changed
        For pagenumber As Integer = pageFirst To pageLast
            Dim ip = copy.GetImportedPage(rdr, pagenumber)

            If pagenumber = pageFirst Then '// changed
                Dim h = ip.Height '// changed
                Dim test = New Dictionary(Of String, Object) 'New Hashtable() '// changed
                test.Add("Action", "GoTo") '// changed
                test.Add("Title", "Page1 0 H 0") '// changed
                test.Add("Page", "1 XYZ 0 " & h.ToString & " 0") '// changed
                bookmarks.Add(test) '// changed
            End If '// changed

            copy.AddPage(ip)
        Next
        copy.Outlines = bookmarks '// changed - got exception here!
        docSrc.Close()
    End Using
    rdr.Close()
End Using

但我无法找到如何为每个新页面添加书签。 我找到了一些像Bookmark to specific page using iTextSharp 4.1.6这样的样本,但无法解决我的问题。

更新: 我添加了代码,我尝试创建标记为'// changed的书签 顺便说一句。我正在使用iTextSharp v5.4.4。 我收到以下异常: 无法将类型为'System.Collections.ArrayList'的对象强制转换为'System.Collections.Generic.IList 1[System.Collections.Generic.Dictionary 2 [System.String,System.Object]]'。 所以我使用List of Dictionary而不是HashTable再次更改。现在我没有收到错误,但我也没有书签。

1 个答案:

答案 0 :(得分:0)

尝试

    Dim oReader As PdfReader
    oReader = New PdfReader(file name)
    Dim book_mark As New List(Of Dictionary(Of String, Object))
    book_mark = SimpleBookmark.GetBookmark(oReader)
相关问题