Add PDF Pages in Java
Contents
[
Hide
]
Aspose.PDF for Java lets you insert blank pages or import pages from another document.
Insert an empty page at a specific position
Use this example when you need to add a blank page in the middle of an existing PDF.
- Open the source PDF Document.
- Insert a new page into the target position in the page collection.
- Save the updated document.
public static void insertEmptyPage(Path inputFile, Path outputFile) {
try (Document document = new Document(inputFile.toString())) {
document.getPages().insert(2);
document.save(outputFile.toString());
}
}
Append an empty page to the end
Use this example when you need to extend the document with a new blank last page.
- Open the source PDF Document.
- Add a new page to the end of the page collection.
- Save the modified PDF.
public static void addEmptyPageToEnd(Path inputFile, Path outputFile) {
try (Document document = new Document(inputFile.toString())) {
document.getPages().add();
document.save(outputFile.toString());
}
}
Add a page from another document
Use this example when you want to import a page from one PDF into another PDF.
- Create the destination Document and open the source document.
- Add any required destination content and import the target page from the source PDF.
- Save the resulting document.
public static void addPageFromAnotherDocument(Path inputFile, Path outputFile) {
try (Document document = new Document();
Document anotherDocument = new Document(inputFile.toString())) {
document.getPages().add().getParagraphs().add(new TextFragment("This is first page!"));
document.getPages().add(anotherDocument.getPages().get_Item(1));
document.save(outputFile.toString());
}
}