I am using iTextSharp to merge PDF documents together. My problem is I am trying to merge a large PDF which contains bookmarks. My current function is using PdfWriter to merge the documents. I know PdfStamper will work, but I cannot figure out how to change the function to work properly.
When I change PdfWriter to PdfStamper in the example below I get an error.
Code Example:
writer = PdfStamper.GetInstance(pdfDoc, New FileStream(outputPath, FileMode.OpenOrCreate))
Error Message:
'GetInstance' is not a member of 'iTextSharp.text.pdf.PdfStamper'
Here is the entire function:
Public Shared Function MergePdfFiles(ByVal pdfFiles() As String, ByVal outputPath As String) As Boolean
Dim result As Boolean = False
Dim pdfCount As Integer = 0
Dim f As Integer = 0
Dim fName As String
Dim reader As iTextSharp.text.pdf.PdfReader = Nothing
Dim pageCount As Integer = 0
Dim pdfDoc As iTextSharp.text.Document = Nothing
Dim writer As PdfWriter = Nothing
Dim cb As PdfContentByte = Nothing
Dim page As PdfImportedPage = Nothing
Dim rotation As Integer = 0
Try
pdfCount = pdfFiles.Length
If pdfCount > 1 Then
fName = pdfFiles(f)
reader = New iTextSharp.text.pdf.PdfReader(fName)
pageCount = reader.NumberOfPages
pdfDoc = New iTextSharp.text.Document(reader.GetPageSizeWithRotation(1), 18, 18, 18, 18)
writer = PdfWriter.GetInstance(pdfDoc, New FileStream(outputPath, FileMode.OpenOrCreate))
With pdfDoc
.Open()
End With
cb = writer.DirectContent
While f < pdfCount
Dim i As Integer = 0
While i < pageCount
i += 1
pdfDoc.SetPageSize(reader.GetPageSizeWithRotation(i))
pdfDoc.NewPage()
page = writer.GetImportedPage(reader, i)
rotation = reader.GetPageRotation(i)
If rotation = 90 Then
cb.AddTemplate(page, 0, -1.0F, 1.0F, 0, 0, reader.GetPageSizeWithRotation(i).Height)
ElseIf rotation = 270 Then
cb.AddTemplate(page, 0, 1.0F, -1.0F, 0, reader.GetPageSizeWithRotation(i).Width + 60, -30)
Else
cb.AddTemplate(page, 1.0F, 0, 0, 1.0F, 0, 0)
End If
End While
f += 1
If f < pdfCount Then
fName = pdfFiles(f)
reader = New iTextSharp.text.pdf.PdfReader(fName)
pageCount = reader.NumberOfPages
End If
End While
pdfDoc.Close()
result = True
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Return False
End Try
Return result
End Function
You can't just change PdfWriter
to PdfStamper
. You need to create a stamper with a reader and an output stream:
PdfReader reader = new PdfReader(pathToSrc);
PdfStamper.GetInstance(reader, New FileStream(outputPath, FileMode.OpenOrCreate));
// do stuff
stamper.Close();
You don't need a Document
instance if you use PdfStamper
; you only need to read the documentation more closely.
All of the above is useless for you, because PdfStamper
is the class to use when you manipulate a single file. If you want to merge different file, you need to use PdfCopy
or PdfSmartCopy
.
Please take a look at the ConcatenateBookmarks example. There's a C# example at the bottom of the page if you don't understand Java.
Browse the official iText website if you have further questions.