Adding page numbers using PDFBox

后端 未结 2 1218
别那么骄傲
别那么骄傲 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:46

    You may want to look at the PDFBox sample AddMessageToEachPage.java. The central code is:

    try (PDDocument doc = PDDocument.load(new File(file)))
    {
        PDFont font = PDType1Font.HELVETICA_BOLD;
        float fontSize = 36.0f;
    
        for( PDPage page : doc.getPages() )
        {
            PDRectangle pageSize = page.getMediaBox();
            float stringWidth = font.getStringWidth( message )*fontSize/1000f;
            // calculate to center of the page
            int rotation = page.getRotation();
            boolean rotate = rotation == 90 || rotation == 270;
            float pageWidth = rotate ? pageSize.getHeight() : pageSize.getWidth();
            float pageHeight = rotate ? pageSize.getWidth() : pageSize.getHeight();
            float centerX = rotate ? pageHeight/2f : (pageWidth - stringWidth)/2f;
            float centerY = rotate ? (pageWidth - stringWidth)/2f : pageHeight/2f;
    
            // append the content to the existing stream
            try (PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, true))
            {
                contentStream.beginText();
                // set font and font size
                contentStream.setFont( font, fontSize );
                // set text color to red
                contentStream.setNonStrokingColor(255, 0, 0);
                if (rotate)
                {
                    // rotate the text according to the page rotation
                    contentStream.setTextMatrix(Matrix.getRotateInstance(Math.PI / 2, centerX, centerY));
                }
                else
                {
                    contentStream.setTextMatrix(Matrix.getTranslateInstance(centerX, centerY));
                }
                contentStream.showText(message);
                contentStream.endText();
            }
        }
    
        doc.save( outfile );
    }
    

    The 1.8.x pendant was:

    PDDocument doc = null;
    try
    {
        doc = PDDocument.load( file );
    
        List allPages = doc.getDocumentCatalog().getAllPages();
        PDFont font = PDType1Font.HELVETICA_BOLD;
        float fontSize = 36.0f;
    
        for( int i=0; i

    Instead of the message, you can add page numbers. And instead of the center, you can use any position.

    (The example can be improved, though: the MediaBox is the wrong choice, the CropBox should be used, and the page rotation handling only appears to properly handle 0° and 90°; 180° and 270° create upside-down writing.)

提交回复
热议问题