Merging two PDF documents by alternating pages from both files in C#
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.
//We assume that GdPicture has been correctly installed and unlocked.GdPicturePDF PdfSource1 = new GdPicturePDF();GdPicturePDF PdfSource2 = new GdPicturePDF();GdPicturePDF PdfDest = new GdPicturePDF();GdPictureStatus status = PdfSource1.LoadFromFile("input1.pdf", false);if (status != GdPictureStatus.OK){ MessageBox.Show("The first PDF document can't be loaded. Error: " + status.ToString(), "Merging PDF Example", MessageBoxButtons.OK, MessageBoxIcon.Error); goto end;}status = PdfSource2.LoadFromFile("input2.pdf", false);if (status != GdPictureStatus.OK){ MessageBox.Show("The second PDF document can't be loaded. Error: " + status.ToString(), "Merging PDF Example", MessageBoxButtons.OK, MessageBoxIcon.Error); goto end;}status = PdfDest.NewPDF();if (status != GdPictureStatus.OK){ MessageBox.Show("The destination PDF document can't be created. Error: " + status.ToString(), "Merging PDF Example", MessageBoxButtons.OK, MessageBoxIcon.Error); goto end;}status = GdPictureStatus.OK;int PageCountSource1 = PdfSource1.GetPageCount();int PageCountSource2 = PdfSource1.GetPageCount();int MaxPage = Math.Max(PageCountSource1, PageCountSource2);for (int Page = 1; Page <= MaxPage; Page++){ if (Page <= PageCountSource1) status = PdfDest.ClonePage(PdfSource1, Page); if (status != GdPictureStatus.OK) break; if (Page <= PageCountSource2) status = PdfDest.ClonePage(PdfSource2, Page); if (status != GdPictureStatus.OK) break;}if (status != GdPictureStatus.OK){ 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) { 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:PdfSource1.Dispose();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.