[]
You can combine pages from one PDF document into another using the mergeWithDocument method of the PdfDocument class. This method appends all or selected pages from a source document to the current document.
To merge PDF documents:
Load the destination PDF document using PdfDocument.load.
Load the source PDF document that contains the pages to merge.
Call the mergeWithDocument method to append pages from the source document to the destination document.
Save the resulting document.
The mergeWithDocument method also accepts optional parameters that allow you to control how the documents are merged via the MergeDocumentOptions type.
The following code example shows how to merge one PDF document into another.
const doc = PdfDocument.load(await Util.loadFile("CompleteJavaScriptBook.pdf"));
// Save page count for the navigation link added below:
const pgNo = doc.pages.count;
const doc1 = PdfDocument.load(await Util.loadFile("Wetlands.pdf"));
doc.mergeWithDocument(doc1);
// Insert a note at the beginning of the document:
const page = doc.pages.insertNew(0);
const rc = Util.addNote(
"GcPdfDocument.MergeWithDocument() method allows adding to the current document all or some pages " +
"from another document.\n" +
"In this sample we load one PDF, append another whole PDF to it, and save the result.\n" +
"Click this note to jump directly to the first page of the 2nd document.",
page);
// Link the note to the first page of the second document:
page.annotations.add({
type: 'link',
rect: rc,
action: { type: 'fit', pageIndex: pgNo + 1 }
});
//Save the document
Util.saveFile("merge.pdf", doc.savePdf());You can split a PDF document into multiple documents by copying selected pages into new PDF documents. This can be achieved by creating a new PdfDocument and merging specific pages from the source document using the mergeWithDocument method with a page range.
To split a PDF document:
Load the source PDF document.
Create a new PdfDocument for each page or page range you want to extract.
Use mergeWithDocument with the range option to copy the desired page(s) into the new document.
Save each resulting document separately.
The following code example shows how to split a PDF document by saving each page as a separate file.
const srcDoc = PdfDocument.load(await Util.loadFile("Wetlands.pdf"));
// save each page into separate file
for (let i = 1; i <= srcDoc.pages.count; i++) {
const doc = new PdfDocument();
doc.mergeWithDocument(srcDoc, { range: { fromPage: i, toPage: i } });
const dstFileName = `split_page${i}.pdf`;
Util.saveFile(dstFileName, doc.savePdf());
}