如何在PDFBox中添加多个页面

nb2*_*b23 1 java pdfbox

我想用PDFBox在我的PDF中写一些内容.一旦页面高度小于我需要创建另一页面的边距.我想保留游标信息.我有一种方法可以获取光标信息,例如光标所在的位置,这样我就可以从光标位置减去边距并为其添加另一个页面.现在我做了类似的事

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();
               }
Run Code Online (Sandbox Code Playgroud)

Nir*_*tel 5

您可以使用一些类级变量,如下所示,通过执行pdf生成来维护positionY.

float PAGE_MARGIN = 20;
float newPagepositionY = page.findMediaBox().getHeight() - PAGE_MARGIN;
float positionY = newPagepositionY;
PDPage currentPage = new PDPage();
Run Code Online (Sandbox Code Playgroud)

在PDF上添加任何内容之前,请检查光标是否已到达页面末尾.即创建功能,如下所示

public boolean isEndOfPage(Row row) 
{
    float currentY = this.positionY ;
    boolean isEndOfPage = currentY  <= (PAGE_MARGIN + 10);

    return isEndOfPage;
}
Run Code Online (Sandbox Code Playgroud)

使用上述功能,您可以根据需要创建新页面.

if (isEndOfPage(row)) 
{
    // Reset positionY  to newPagepositionY
    this.positionY  = newPagepositionY;

    this.currentPage = new PDPage();

    // your code
}
Run Code Online (Sandbox Code Playgroud)