Skip to main content

Add and Insert PDF Pages

  • 2 minutes to read

You can append pages to a document or insert them at a specific position.

Add a Page

Use the add(DXPaperKind kind) method to append a page with the specified paper size to the document.

The following code snippet adds an A4 page:

import com.devexpress.docs.pdf.*;
import com.devexpress.drawing.printing.*;

import java.nio.channels.*;
import java.nio.file.*;

public class Main {
    public static void main(String[] args) throws Exception {
        try (PdfDocument pdfDocument = new PdfDocument()) {

            // Add an A4-size page to the document.
            pdfDocument.getPages().add(DXPaperKind.A4);

            // Save the document to a PDF file.
            try (WritableByteChannel writableByteChannel =
                     FileChannel.open(Path.of("result.pdf"),
                         StandardOpenOption.CREATE,
                         StandardOpenOption.WRITE,
                         StandardOpenOption.TRUNCATE_EXISTING)) {

                pdfDocument.save(writableByteChannel);
            }
        }
    }
}

You can also create a Page object and append it to the document.

import com.devexpress.docs.pdf.*;
import com.devexpress.drawing.printing.*;


// Create a Letter-size page.
Page page = new Page(DXPaperKind.LETTER);

// Append the page to the document.
pdfDocument.getPages().add(page);

Insert a Page

Use the add(int index, Page page) method to insert a page at the specified zero-based index.

The following code snippet inserts a Letter-size page after the first page:

pdfDocument.getPages().add(1, new Page(DXPaperKind.LETTER));

Tip

Use the addFirst() method to insert a page at the beginning of a document.

Copy a Page

The following code snippet duplicates the first page in the document and inserts the copy after it:

// Get the first page in the document.
Page page = pdfDocument.getPages().getFirst();

// Create a copy of the page.
Page pageClone = page.deepClone();

// Insert the cloned page after the first page.
pdfDocument.getPages().add(1, pageClone);

Next Steps