Foxit Quick PDF Library

Programmatically insert pages from one PDF file to another PDF file

There are two different ways that this can be done depending on your exact requirements. I’ve included details of two different scenarios below as well as some sample code.

Scenario #1: You want to extract various pages from an existing document (original.pdf) and create a new document (extracted_pages.pdf) that only consists of the extracted pages.

// Load a PDF that you wish to extract pages from.
QP.LoadFromFile("original.pdf");

// Extract Pages 2,4 and 6 from the "oiginal.pdf" file.
// You can also use the ExtractFilePages function. The extracted
// pages will automatically be added to a new document in memory.
if (QP.ExtractPageRanges("2,4,6") == 1)
{
// The new document that was created from the 
// extracted pages has automatically been selected 
// by the previous function, so all you need to do 
// now is save the new document to a new fie 
// on the disk.
QP.SaveToFile("ExtractedPages.pdf");
}

Scenario #2: You want to extract various pages from an existing document (original.pdf) and insert these pages into a existing document (existing.pdf) at a specific location.

// Load the document that you will extract the pages from
QP.LoadFromFile("source.pdf");

// Get the ID for this document
int DocID1 = QP.SelectedDocument();

// Load the document that you will insert the extracted pages into
QP.LoadFromFile("destination.pdf");

// Get the ID for this document
int DocID2 = QP.SelectedDocument();

// Count the number of pages in the destination document
int tPages2 = QP.PageCount();

// Copy pages 2,4 and 6 from source document to the destination document
QP.CopyPageRanges(DocID1, "2,4,6");

// Again count the number of pages in the destination document
int tPages1 = qp.PageCount();

// Get the total number of pages added to the destination document
int tPages3 = tPages1 - tPages2;

// Specify the page number that the new pages should be inserted at
int NewPagePos = 2;

// Loop through each insert page and move it to the correct location
while (tPages3 > 0)
{
// We always move the last page
// in the document until all
// insert pages have been moved.
QP.SelectPage(QP.PageCount());
QP.MovePage(NewPagePos);

// Increase location of next page. So if
// first page is inserted at page number 2,
// then next page will be inserted at page number 3
NewPagePos++;

// Decrease number of pages left to process
tPages3--;
}
// Save updated destination document to disk
QP.SaveToFile("destination_updated.pdf");

This article refers to a deprecated product. If you are looking for support for Foxit PDF SDK, please click here.

Updated on May 16, 2022

Was this article helpful?
Thanks for your feedback. If you have a comment on how to improve the article, you can write it here: