Add PDF Pages in Java

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.

  1. Open the source PDF Document.
  2. Insert a new page into the target position in the page collection.
  3. 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.

  1. Open the source PDF Document.
  2. Add a new page to the end of the page collection.
  3. 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.

  1. Create the destination Document and open the source document.
  2. Add any required destination content and import the target page from the source PDF.
  3. 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());
    }
}