Adding page numbers using PDFBox

后端 未结 2 1220
别那么骄傲
别那么骄傲 2021-02-14 21:43

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

2条回答
  •  一向
    一向 (楼主)
    2021-02-14 22:32

    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();
        }
    

提交回复
热议问题