merge pdf pages in csharp

To merge PDF pages in C#, we can use the PdfSharp library. Here is an example of how to do it:

main.cs
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;

// Get paths of PDF documents to merge
string[] pdfPaths = { "document1.pdf", "document2.pdf", "document3.pdf" };

// Create a new PDF document
PdfDocument outputDocument = new PdfDocument();

// Loop through each PDF document and add its pages to the new document
foreach (string pdfPath in pdfPaths)
{
    // Open the PDF document
    PdfDocument inputDocument = PdfReader.Open(pdfPath, PdfDocumentOpenMode.Import);

    // Loop through each page in the PDF document and add it to the output document
    foreach (PdfPage page in inputDocument.Pages)
    {
        outputDocument.AddPage(page);
    }

    // Close the input document
    inputDocument.Close();
}

// Save the new PDF document
outputDocument.Save("merged.pdf");
774 chars
28 lines

In this example, we first define an array of PDF paths to merge. We then create a new PdfDocument object to store the merged pages. We loop through each PDF document and open it using the PdfReader class. We then loop through each page in the input document and add it to the output document using the AddPage() method. Finally, we close the input document and save the output document to a file named "merged.pdf".

related categories

gistlibby LogSnag