如何在PDFBox中添加多个页面 [英] How to add multiple pages in PDFBox
问题描述
我想使用 PDFBox 在我的 PDF 中写入一些内容.一旦页面高度小于边距,我需要创建另一个页面.我想保留光标信息.我有一种方法可以获取光标信息,例如光标所在的位置,这样我就可以从光标位置减去边距并向其添加另一个页面.现在我做了这样的事情
I want to write some content in my PDF using PDFBox. Once the page height is less than the margin I need to create another page. I want to retain the cursor information. I s there a way through which i can get the cursor information like where the cursor is present so i can subtract the margin from cursor position and add another page to it. Right now I have done something like this
PDRectangle rect = page.getMediaBox();
float positionY = rect.getWidth();
positionY = positionY - pdfWriter.defaultBottomMargin;
if(positionY < positionX) {
positionY = rect.getWidth();
PDPage page2 = page;
rect = page2.getMediaBox();
document.addPage(page2);
PDPageContentStream contentStream = new PDPageContentStream(document, page2);
contentStream.appendRawCommands("T*\n");
contentStream.beginText();
// contentStream.setFont(font, 12);
contentStream.moveTextPositionByAmount(positionX, positionY);
contentStream.drawString(tmpText[k]);
contentStream.endText();
contentStream.close();
}
推荐答案
您可以使用一些类级别的变量,如下所示,它们通过执行 pdf 生成来保持 positionY.
You can use some class level variables like below which maintains positionY throught execution of pdf generation.
float PAGE_MARGIN = 20;
float newPagepositionY = page.findMediaBox().getHeight() - PAGE_MARGIN;
float positionY = newPagepositionY;
PDPage currentPage = new PDPage();
在PDF上添加任何内容之前,请检查光标是否已到达页面末尾.即创建如下所示的功能
Before adding any content on PDF, check whether cursor has reached at end of page or not. i.e. Create funtion as shown below
public boolean isEndOfPage(Row row)
{
float currentY = this.positionY ;
boolean isEndOfPage = currentY <= (PAGE_MARGIN + 10);
return isEndOfPage;
}
使用上述功能,您可以根据需要创建新页面.
Using above funtion, you can create new page as required.
if (isEndOfPage(row))
{
// Reset positionY to newPagepositionY
this.positionY = newPagepositionY;
this.currentPage = new PDPage();
// your code
}
这篇关于如何在PDFBox中添加多个页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!