2013-05-16 65 views
7

如何將頁碼添加到使用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(); 
+0

請在句子的開頭添加大寫字母。還要使用大寫字母I和專有名稱(如Java),以及縮寫和首字母縮略詞(如JEE或WAR)。這使人們更容易理解和幫助。 –

+0

我有同樣的問題,任何人都可以幫忙嗎? – mohammad

回答

8

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

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

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