Tuesday, September 28, 2010

Merging Pdf files in Asp.Net

Solution

1. First u need to download 'itextsharp.dll' from the internet.
2. Then add this dll using add reference.
3. Import the below name space.

Imports iTextSharp.text
Imports iTextSharp.text.pdf


4. Use the below function to merge the pdf.

Public Sub Merge()

Private ReadOnly m_documents As List(Of PdfReader)
Dim newDocument As Document = Nothing

//Merge pdf path. All the pdf files will merged here and become one pdf.
ByVal outputStream As Stream
outputStream = New FileStream(pdfMergePath, FileMode.Create)

Try
newDocument = New Document()
Dim pdfWriter__1 As PdfWriter = PdfWriter.GetInstance(newDocument, outputStream)

newDocument.Open()
newDocument.SetPageSize(PageSize.A3)

Dim pdfContentByte__2 As PdfContentByte = pdfWriter__1.DirectContentUnder

// Add all the pdf to merge
m_documents.Add(New PdfReader(pdfPath1))
m_documents.Add(New PdfReader(pdfPath2))
m_documents.Add(New PdfReader(pdfPath2))

For Each doc In m_documents
totalPages += doc.NumberOfPages
Next

Dim currentPage As Integer = 1
For Each pdfReader As PdfReader In m_documents
For page As Integer = 1 To pdfReader.NumberOfPages
newDocument.NewPage()

Dim importedPage As PdfImportedPage = pdfWriter__1.GetImportedPage(pdfReader, page)
pdfContentByte__2.AddTemplate(importedPage, 0, 0)

pdfContentByte__2.BeginText()
m_baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED)
pdfContentByte__2.SetFontAndSize(m_baseFont, 9)
pdfContentByte__2.ShowTextAligned(PdfContentByte.ALIGN_RIGHT, String.Format("{0} of {1}", currentPage, totalPages), 520, 5, 0)
pdfContentByte__2.EndText()

currentPage = currentPage + 1
Next
Next

Finally
outputStream.Flush()
If newDocument IsNot Nothing Then
newDocument.Close()
End If
outputStream.Close()
End Try

End Sub

No comments: