簡體   English   中英

使用PDFBox添加頁碼

[英]Adding page numbers using PDFBox

如何將頁碼添加到使用PDFBox生成的文檔中的頁面?

合並不同的PDF后,有人能告訴我如何在文檔中添加頁碼嗎? 我在Java中使用PDFBox庫。

這是我的代碼,它運行良好,但我需要添加頁碼。

 PDFMergerUtility ut = new PDFMergerUtility();
        ut.addSource("c:\\pdf1.pdf");
        ut.addSource("c:\\pdf2.pdf");
        ut.addSource("c:\\pdf3.pdf");
        ut.mergeDocuments();

您可能需要查看PDFBox示例AddMessageToEachPage.java 中央代碼是:

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

1.8.x吊墜是:

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<allPages.size(); i++ )
    {
        PDPage page = (PDPage)allPages.get( i );
        PDRectangle pageSize = page.findMediaBox();
        float stringWidth = font.getStringWidth( message )*fontSize/1000f;
        // calculate to center of the page
        int rotation = page.findRotation(); 
        boolean rotate = rotation == 90 || rotation == 270;
        float pageWidth = rotate ? pageSize.getHeight() : pageSize.getWidth();
        float pageHeight = rotate ? pageSize.getWidth() : pageSize.getHeight();
        double centeredXPosition = rotate ? pageHeight/2f : (pageWidth - stringWidth)/2f;
        double centeredYPosition = rotate ? (pageWidth - stringWidth)/2f : pageHeight/2f;
        // append the content to the existing stream
        PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, 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.setTextRotation(Math.PI/2, centeredXPosition, centeredYPosition);
        }
        else
        {
            contentStream.setTextTranslation(centeredXPosition, centeredYPosition);
        }
        contentStream.drawString( message );
        contentStream.endText();
        contentStream.close();
    }

    doc.save( outfile );
}
finally
{
    if( doc != null )
    {
        doc.close();
    }
}

您可以添加頁碼,而不是消息。 而不是中心,你可以使用任何位置。

(但是可以改進示例: MediaBox是錯誤的選擇,應該使用CropBox ,並且頁面旋轉處理只能正確處理0°和90°; 180°和270°會創建顛倒的寫入。)

這很容易,請嘗試以下代碼

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM