PdfPTable overflowing to second page when it should fit in the remaining space

21 views Asked by At

I am trying to make sure a table fits in the space left on the current page. I check the vertical position, subtract the bottom margin and the footer height, but the table still overflows to another page.

Here is a code sample:

package openpdf;

import com.lowagie.text.Document;
import com.lowagie.text.HeaderFooter;
import com.lowagie.text.Phrase;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
import java.io.File;
import java.io.FileOutputStream;

public class TableHeightTest {

  public static void main(String[] args) 
  throws Exception {
    Rectangle pageSize = new Rectangle(432,648);
    Document doc = new Document(pageSize, 75, 75, 75, 75);
    FileOutputStream fos = new FileOutputStream(new File("C:/Tmp/test.pdf"));
    PdfWriter writer = PdfWriter.getInstance(doc, fos);
    
    HeaderFooter footer = new HeaderFooter(new Phrase("This is the footer"),true);
    footer.setAlignment(Rectangle.ALIGN_CENTER);
    doc.setFooter(footer);

    doc.open();
    
    PdfPTable table = new PdfPTable(1);
    table.setTotalWidth(225);
    
    float spaceRemaining = writer.getVerticalPosition(true) - 
        doc.bottomMargin() - footer.getHeight();
    while( table.getTotalHeight() < spaceRemaining ) {
      PdfPCell cell = new PdfPCell(new Phrase("This is a cell"));
      table.addCell(cell);
    }
    table.deleteLastRow();
    doc.add(table);
    
    doc.close();
    fos.close();
  }
}

The output should have only one page, but it has two. The first page has this: page1

There should not be a second page, but there is one with this content: page2

There should not be anything else on the page so I don't understand why the table overflows.

Any suggestions?

0

There are 0 answers