How can I add page number to a page in a document generated using PDFBox?
Can anybody tell me how to add page numbers to a document after I merge different PDFs? I am u
It is easy, try the following code
public static void addPageNumbers(PDDocument document, String numberingFormat, int offset_X, int offset_Y) throws IOException {
int page_counter = 1;
for(PDPage page : document.getPages()){
PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true, false);
contentStream.beginText();
contentStream.setFont(PDType1Font.TIMES_ITALIC, 10);
PDRectangle pageSize = page.getMediaBox();
float x = pageSize.getLowerLeftX();
float y = pageSize.getLowerLeftY();
contentStream.newLineAtOffset(x+ pageSize.getWidth()-offset_X, y+offset_Y);
String text = MessageFormat.format(numberingFormat,page_counter);
contentStream.showText(text);
contentStream.endText();
contentStream.close();
++page_counter;
}
}
public static void main(String[] args) throws Exception {
File file = new File("your input pdf path");
PDDocument document = PDDocument.load(file);
addPageNumbers(document,"Page {0}",60,18);
document.save(new File("output pdf path"));
document.close();
}