merge pdf pages using pdfsharp in csharp

Here's a sample code that merges multiple PDFs into a single PDF file by appending pages from each PDF file to the output file:

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

// List of input PDF files to be merged
List<string> inputPdfFiles = new List<string>();
inputPdfFiles.Add("input1.pdf");
inputPdfFiles.Add("input2.pdf");
inputPdfFiles.Add("input3.pdf");

// Output PDF file
string outputPdfFile = "output.pdf";

// Merge PDFs
using (PdfDocument outputPdf = new PdfDocument())
{
    foreach (string inputPdfFile in inputPdfFiles)
    {
        using (PdfDocument inputPdf = PdfReader.Open(inputPdfFile, PdfDocumentOpenMode.Import))
        {
            int pageCount = inputPdf.PageCount;
            for (int i = 0; i < pageCount; i++)
            {
                // Append each page from input PDF to output PDF
                PdfPage page = inputPdf.Pages[i];
                outputPdf.AddPage(page);
            }
        }
    }
    // Save output PDF file
    outputPdf.Save(outputPdfFile);
}
880 chars
32 lines

Note that each input PDF is first opened as a PdfDocument instance using PdfReader.Open and then its pages are appended to the PdfDocument instance of the output PDF file using outputPdf.AddPage. Finally, the output PDF file is saved using outputPdf.Save.

related categories

gistlibby LogSnag