我有一个很大的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,但无法解决我的问题。
更新:我添加了如何尝试创建标记为'//的书签的代码顺便说一句。我正在使用iTextSharp v5.4.4。我收到以下异常:无法将类型为“ System.Collections.ArrayList”的对象转换为类型为“ System.Collections.Generic.IList1[System.Collections.Generic.Dictionary
2 [System.String,System.Object]]”。因此,我再次使用字典列表而不是HashTable进行了更改。现在,我没有收到任何错误,但也没有任何书签。
尝试
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)