Merging the First Page of PDFs Using iText and VB/C#

Antonio Annunziata 0 Reputation points
2023-06-02T15:07:43.6333333+00:00

Hello,

i have written a function to merge the first page of one PDF into another using iTextSharp, and I have used the following code:

Public Function MergePagePdf(ByVal outputFile As String, ByVal inputFile2 As Byte(), ByVal inputFile1 As Byte(), ByRef strErrore As String) As Boolean
	Dim bRet As Boolean = False
	Dim positionx As Integer = 0
	Dim positiony As Integer = 0
	Dim document As iTextSharp.text.Document = New iTextSharp.text.Document()
	Try
		Dim writer As PdfWriter = PdfWriter.GetInstance(document, New FileStream(outputFile, FileMode.Create))
		document.Open()
		Dim cb As PdfContentByte = writer.DirectContent
		Dim page1 As PdfImportedPage
		Dim page2 As PdfImportedPage
		Dim reader1 As PdfReader = New PdfReader(inputFile1)
		Dim reader2 As PdfReader = New PdfReader(inputFile2)
		document.SetPageSize(reader1.GetPageSizeWithRotation(1))
		document.NewPage()
		page1 = writer.GetImportedPage(reader1, 1)
		page2 = writer.GetImportedPage(reader2, 1)
		cb.AddTemplate(page1, 0, 0)
		cb.AddTemplate(page2, positionx, positiony)

		If reader1.NumberOfPages > 1 Then
			For i As Integer = 2 To reader1.NumberOfPages
				document.SetPageSize(reader1.GetPageSizeWithRotation(i))
				document.NewPage()
				page1 = writer.GetImportedPage(reader1, i)
				cb.AddTemplate(page1, 0, 0)
			Next
		End If

		bRet = True
	Catch e As Exception
		strErrore = e.Message
		bRet = False
	Finally
		If document IsNot Nothing Then document.Close()
	End Try

	Return bRet
End Function

I am trying to achieve the same result with the new version of iText, but I haven't been successful. Is it possible to do it with the new version? If yes, can someone guide me on how to accomplish it?

Thank you for your help.

Developer technologies | VB
0 comments No comments
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.