Move PDF Pages in Java
Contents
[
Hide
]
Aspose.PDF for Java lets you move pages between documents or reposition pages within the same PDF.
Move a page to another document
Use this example when a single page should be removed from the source PDF and saved into a separate document.
- Open the source PDF Document and create a destination document.
- Add the target page to the destination and delete it from the source.
- Save both documents.
public static void movePageFromOneDocumentToAnother(Path inputFile, Path sourceOutputFile, Path outputFile) {
try (Document document = new Document(inputFile.toString());
Document anotherDocument = new Document()) {
anotherDocument.getPages().add(document.getPages().get_Item(2));
document.getPages().delete(2);
document.save(sourceOutputFile.toString());
anotherDocument.save(outputFile.toString());
}
}
Move multiple pages to another document
Use this example when several pages should be transferred from the source PDF to a new document.
- Open the source PDF Document and create the destination document.
- Copy the selected pages into the destination document.
- Delete the moved pages from the source and save both files.
public static void moveBunchPagesFromOneDocumentToAnother(Path inputFile, Path sourceOutputFile, Path outputFile) {
try (Document srcDocument = new Document(inputFile.toString());
Document dstDocument = new Document()) {
Integer[] pages = {1, 2};
for (Integer pageIndex : pages) {
dstDocument.getPages().add(srcDocument.getPages().get_Item(pageIndex));
}
dstDocument.save(outputFile.toString());
srcDocument.getPages().delete(pages);
srcDocument.save(sourceOutputFile.toString());
}
}
Move a page within the same document
Use this example when a page should be repositioned to a new location in the same PDF.
- Open the source PDF Document.
- Duplicate the target page into the new position and remove the original page entry.
- Save the reordered document.
public static void movePageInNewLocationInSameDocument(Path inputFile, Path outputFile) {
try (Document srcDocument = new Document(inputFile.toString())) {
srcDocument.getPages().add(srcDocument.getPages().get_Item(2));
srcDocument.getPages().delete(2);
srcDocument.save(outputFile.toString());
}
}