''' <summary>
''' Extract pages from an existing pdf file to create a new pdf with bookmarks preserved
''' </summary>
''' <param name="sourcePdf">full path to sthe source pdf</param>
''' <param name="pageNumbersToExtract">an integer array containing the page number of the pages to be extracted</param>
''' <param name="outPdf">the full path to the output pdf</param>
''' <remarks></remarks>
Public Shared Sub ExtractPdfPages(ByVal sourcePdf As String, ByVal pageNumbersToExtract As Integer(), ByVal outPdf As String)
Dim raf As iTextSharp.text.pdf.RandomAccessFileOrArray = Nothing
Dim reader As iTextSharp.text.pdf.PdfReader = Nothing
Dim outlines As System.Collections.ArrayList = Nothing
Dim page As iTextSharp.text.pdf.PdfImportedPage = Nothing
Dim stamper As iTextSharp.text.pdf.PdfStamper = Nothing
Dim hshTable As System.Collections.Hashtable = Nothing
Try
raf = New iTextSharp.text.pdf.RandomAccessFileOrArray(sourcePdf)
reader = New iTextSharp.text.pdf.PdfReader(raf, Nothing)
outlines = iTextSharp.text.pdf.SimpleBookmark.GetBookmark(reader)
reader.SelectPages(New System.Collections.ArrayList(pageNumbersToExtract))
stamper = New iTextSharp.text.pdf.PdfStamper(reader, New IO.FileStream(outPdf, IO.FileMode.Create))
RemoveUnusedBookmarks(outlines, pageNumbersToExtract)
stamper.Outlines = outlines
stamper.Close()
reader.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Shared Sub RemoveUnusedBookmarks(ByRef bookmarks As System.Collections.ArrayList, ByVal pagesToKeep() As Integer)
Dim bookmark As System.Collections.Hashtable = Nothing
Dim obj As Object = Nothing
For i As Integer = bookmarks.Count - 1 To 0 Step -1
obj = bookmarks(i)
If TypeOf obj Is System.Collections.ArrayList Then
RemoveUnusedBookmarks(DirectCast(obj, System.Collections.ArrayList), pagesToKeep)
ElseIf TypeOf obj Is System.Collections.Hashtable Then
bookmark = DirectCast(obj, System.Collections.Hashtable)
If bookmark.ContainsKey("Page") Then
Dim value As String = DirectCast(bookmark.Item("Page"), String)
If Not String.IsNullOrEmpty(value) Then
Dim parts() As String = value.Split(" "c)
If parts.Length > 0 Then
Dim pageNum As Integer = -1
If Integer.TryParse(parts(0), pageNum) Then
Dim idx As Integer = System.Array.IndexOf(pagesToKeep, pageNum)
If idx < 0 Then
bookmarks.Remove(obj)
Else
parts(0) = (idx + 1).ToString
value = String.Join(" ", parts)
bookmark.Item("Page") = value
End If
End If
End If
End If
End If
End If
Next
End Sub