java 使用 PDFBox 添加页码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16581471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding page numbers using PDFBox
提问by Jhon Stewart
How can I add page number to a page in a document generated using PDFBox?
如何将页码添加到使用 PDFBox 生成的文档中的页面?
Can anybody tell me how to add page numbers to a document after I merge different PDFs? I am using the PDFBox library in Java.
谁能告诉我在合并不同的 PDF 后如何向文档添加页码?我在 Java 中使用 PDFBox 库。
This is my code and it works well but I need to add page number.
这是我的代码,它运行良好,但我需要添加页码。
PDFMergerUtility ut = new PDFMergerUtility();
ut.addSource("c:\pdf1.pdf");
ut.addSource("c:\pdf2.pdf");
ut.addSource("c:\pdf3.pdf");
ut.mergeDocuments();
采纳答案by mkl
You may want to look at the PDFBox sample AddMessageToEachPage.java. The central code is:
您可能需要查看 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 );
}
The 1.8.x pendant was:
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();
}
}
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 MediaBoxis the wrong choice, the CropBoxshould be used, and the page rotation handling only appears to properly handle 0° and 90°; 180° and 270° create upside-down writing.)
(不过,该示例可以改进:MediaBox是错误的选择,应该使用CropBox,并且页面旋转处理似乎只能正确处理 0° 和 90°;180° 和 270° 创建颠倒书写。)
回答by imal hasaranga perera
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();
}