How to resize a PdfPTable to fit the page?

Category: 
Tags: adjust page sizepage sizetablestable heightposition tableiText 5

I am generating a document that contains a table. I need to make sure that this table never exceeds one page in size, regardless of the amount of content in the cells. Is there a way to do this?

Posted on StackOverflow on Feb 19, 2013 by Jannis Alexakis

If you want a table to fit a page, you should create the table before even thinking about page size and ask the table for its height as is done in the TableHeight example. Note that the getTotalHeight() method returns 0 unless you define the width of the table. This can be done like this:

table.setTotalWidth(width);
table.setLockedWidth(true);

Now you can create a Document with size Rectangle(0, 0, width + margin * 2, getTotalHeight() + margin * 2) and the table should fit the document exactly when you add it with the writeSelectedRows() method.

If you don't want a custom page size, then you need to create a PdfTemplate with the size of the table and add the table to this template object. Then wrap the template object in an Image and use scaleToFit() to size the table down.

public static void main(String[] args) throws DocumentException, FileNotFoundException, IOException {
    String TARGET = "temp.pdf";
    Document document = new Document(PageSize.A4);
    PdfWriter writer 
        PdfWriter.getInstance(document, new FileOutputStream(TARGET));
    document.open();
    PdfPTable table = new PdfPTable(7);         
 
    for (int i = 0; i < 700; i++) {
        Phrase p = new Phrase("some text");
        PdfPCell cell = new PdfPCell();
        cell.addElement(p);
        table.addCell(cell);            
    }
 
    table.setTotalWidth(PageSize.A4.getWidth());
    table.setLockedWidth(true);
    PdfContentByte canvas = writer.getDirectContent();
    PdfTemplate template = canvas.createTemplate(
        table.getTotalWidth(), table.getTotalHeight());
    table.writeSelectedRows(0, -1, 0, table.getTotalHeight(), template);
    Image img = Image.getInstance(template);
    img.scaleToFit(PageSize.A4.getWidth(), PageSize.A4.getHeight());
    img.setAbsolutePosition(
        0, (PageSize.A4.getHeight() - table.getTotalHeight()) / 2);
    document.add(img);
    document.close();
}