Change PDF Page Labels in Java

By default, a PDF’s pages are numbered from 1 to the number of pages contained within it. PDFs often have the page number substituted — or labeled — with some alternative text. For example, the first few pages of a document could be labeled with Roman numerals instead of the usual Western Arabic numerals — e.g. instead of 1, 2, 3, 4, 5, the pages could be labeled I, II, III, IV, V, and then continue on as 6, 7, 8, etc.

After producing a new document by shuffling around, adding, removing, or inserting new pages, it may be necessary to clear the page labels and set new ones.

This example demonstrates how to clear any existing page labels and add custom labels to the first page of the new document:

// Create a Document Editor from a source document.
DocumentEditor documentEditor = documentToEdit.createDocumentEditor();

// Clear any existing page labels.
documentEditor.clearPageLabels();

// Set custom labels for the first page.
Set<Integer> pages = new HashSet<>();
pages.add(0);
documentEditor.setPageLabel(pages, "Test");

// Generate a new document.
File file = File.createTempFile("documentEditorOutput", ".pdf");
documentEditor.saveDocument(new FileDataProvider(file));

Chaining Edits Together

Document edits can be chained to perform multiple synchronous operations to create a single document. For example:

File file = File.createTempFile("documentEditorOutput", ".pdf");
DocumentEditor documentEditor = documentToEdit.createDocumentEditor();
File secondDocument = new File("secondDocument.pdf");
documentEditor.importDocument(0, DocumentEditor.IndexPosition.BeforeIndex, new FileDataProvider(secondDocument));
documentEditor.clearPageLabels();
Set<Integer> pages = new HashSet<>();
pages.add(0);
documentEditor.setPageLabel(pages, "Test");
documentEditor.saveDocument(new FileDataProvider(file));