Merging two PDF documents by alternating pages from both files in VB.NET

This example shows how to merge two PDF documents, alternating a page from the first document and a page from the second document. This can be useful when you don’t have a duplex option on your scanner and want to scan a batch of documents, so you can acquire the frontsides first and then the backsides.


VB.NET
'We assume that GdPicture has been correctly installed and unlocked.
Dim PdfSource1 As New GdPicturePDF()
Dim PdfSource2 As New GdPicturePDF()
Dim PdfDest As New GdPicturePDF()
Dim status As GdPictureStatus = PdfSource1.LoadFromFile("input1.pdf", False)
If status <> GdPictureStatus.OK Then
MessageBox.Show("The first PDF document can't be loaded. Error: " + status.ToString(), "Merging PDF Example", MessageBoxButtons.OK, MessageBoxIcon.Error)
GoTo [end]
End If
status = PdfSource2.LoadFromFile("input2.pdf", False)
If status <> GdPictureStatus.OK Then
MessageBox.Show("The second PDF document can't be loaded. Error: " + status.ToString(), "Merging PDF Example", MessageBoxButtons.OK, MessageBoxIcon.Error)
GoTo [end]
End If
status = PdfDest.NewPDF()
If status <> GdPictureStatus.OK Then
MessageBox.Show("The destination PDF document can't be created. Error: " + status.ToString(), "Merging PDF Example", MessageBoxButtons.OK, MessageBoxIcon.Error)
GoTo [end]
End If
status = GdPictureStatus.OK
Dim PageCountSource1 As Integer = PdfSource1.GetPageCount()
Dim PageCountSource2 As Integer = PdfSource1.GetPageCount()
Dim MaxPage As Integer = Math.Max(PageCountSource1, PageCountSource2)
For Page As Integer = 1 To MaxPage
If Page <= PageCountSource1 Then
status = PdfDest.ClonePage(PdfSource1, Page)
End If
If status <> GdPictureStatus.OK Then
Exit For
End If
If Page <= PageCountSource2 Then
status = PdfDest.ClonePage(PdfSource2, Page)
End If
If status <> GdPictureStatus.OK Then
Exit For
End If
Next
If status <> GdPictureStatus.OK Then
MessageBox.Show("Error occurred when cloning. Error: " + status.ToString(), "Merging PDF Example", MessageBoxButtons.OK, MessageBoxIcon.Error)
Else
status = PdfDest.SaveToFile("output.pdf")
If status = GdPictureStatus.OK Then
MessageBox.Show("Done!", "Merging PDF Example", MessageBoxButtons.OK, MessageBoxIcon.Information)
Else
MessageBox.Show("The final PDF document can't be saved. Error: " + status.ToString(), "Merging PDF Example", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
End If
PdfSource2.Dispose()
PdfDest.Dispose()

This code sample is an example that illustrates how to use our SDK. Please adapt it to your specific use case.