Replace pages in pdf

hi ,

we have a use case where we want to replace page in a pdf
for example if we have and original pdf of 10 pages in size, and edited pdf of 3 pages…
the pages in the edited pdf correspond to 1,4,7 th page in the original pdf…

how can we replace the pages such that the original pdf gets the 1st, 4th and 7th pages from the edited pdf?

please advise,
thanks

@randomuser123

You can use Delete() and Insert() methods of Pages collection of a Document. Please check below sample code snippet:

// Load the original PDF
Document originalPdf = new Document("original.pdf");

// Load the edited PDF
Document editedPdf = new Document("edited.pdf");

// Define the page numbers to replace (1-based index)
int[] pageNumbersToReplace = { 1, 4, 7 };

foreach (int pageNumber in pageNumbersToReplace)
{
    // Extract the page from the edited PDF
    Page extractedPage = editedPdf.Pages[pageNumber];

    // Delete the corresponding page from the original PDF
    originalPdf.Pages.Delete(pageNumber);

    // Insert the extracted page into the original PDF at the same position
    originalPdf.Pages.Insert(pageNumber, extractedPage);
}

// Save the modified original PDF
originalPdf.Save("output.pdf");

Thanks @asad.ali, this works perfectly!