2013-05-16 3 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(); 
    } 
} 

, 당신은 페이지 번호를 추가 할 수 있습니다. 센터 대신에 어떤 위치에서나 사용할 수 있습니다.

관련 문제