Marcus Junius Brutus
Marcus Junius Brutus

Reputation: 27286

iText setRowspan not working for tables in headers?

Exactly the same code is used to create a PdfPTable for the main body of a document and the document's page header. The table is properly rendered in the main body but doesn't seem to take into account setRowspan values in the header.

Below I paste a screenshot of the produced pdf and, after that, the minimal standalone program that was used to generate the pdf.

PDF output

enter image description here

code

import java.io.*;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;

class HeaderAndFooter extends PdfPageEventHelper{

    private PdfPTable header;

    public HeaderAndFooter() throws Exception {
        header = FooMain.createTable();
        header.setTotalWidth(530);
    }

    @Override
    public void onEndPage(PdfWriter writer, Document document) {
        PdfContentByte cb = writer.getDirectContent();
        float x   = document.leftMargin();
        float hei = header.getTotalHeight();
        float y   = document.top()+hei;
        header.writeSelectedRows(0, -1, x , y, cb);
    }
}

public class FooMain {

    public static void main(String[] args) throws Exception {
        Document doc = new Document(PageSize.A4, 30, 30, 150, 40);
        PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream("./brokenTableInHeader.pdf"));
        writer.setPageEvent(new HeaderAndFooter());
        doc.open();
        doc.add(createTable());
        doc.close();
    }

    public static PdfPTable createTable() throws Exception {
        PdfPTable table = new PdfPTable(2);
        PdfPCell cell = new PdfPCell(new Phrase("cell spanning two rows")); 
        cell.setRowspan(2);
        table.addCell(cell);
        table.addCell( new Phrase ("a"));
        table.addCell( new Phrase ("b"));
        return table;
    }
}

Upvotes: 1

Views: 1428

Answers (1)

Marcus Junius Brutus
Marcus Junius Brutus

Reputation: 27286

Found the answer in this SO question (use ColumnText::go instead of PdfPTable::writeSelectedRows)

Here's an excerpt from my working code:

ColumnText column = new ColumnText(writer.getDirectContent());
column.addElement(footer);
column.setSimpleColumn (0, 0, 630, 80);
column.go();

Upvotes: 1

Related Questions