iText 7 column widths why do these not fit?

4.9k views Asked by At

I am brand new to iText and leaped straight into iText 7, but find setting column widths on my table to be ridiculously challenging. Clearly there is something basic I'm not getting.

In combing the web for answers, I found some itext 5-based answers that don't seem to be relevant to itext 7 (hard-coding a fixed width). The iText 7 stuff seems to assume knowledge I don't have! "relative column widths" -- what does that mean? should the numbers add up to 100? Simple examples with 2 or 4 columns make sense, but I'm having difficulty translating that into a 7-column table.

I have a table with 7 columns. The 1st, 3rd, and 5th columns should be relatively narrow, they are simply labels. the 7th column can take up whatever space is available. For instance:

Col1  Col2         Col3  Col4         Col5      Col6        Col7 
CMS#: C34827284    Date: 12/5/16      End Date: 12/6/16     approved

I thought I had it, but my latest attempt produces "Element does not fit current area" errors. Here is how I defined it

Table htable = new Table(new float[] {3, 8, 5, 10, 5, 10, 30});

These numbers add up to 71 so why do they not fit? Do they need to add exactly up to 100 or am I completely on the wrong track with the "adds up to 100" idea?

1

There are 1 answers

3
Bruno Lowagie On BEST ANSWER

Did you define a width for the table as a whole?

This is what I tried:

public void createPdf(String dest) throws IOException {
    //Initialize PDF writer
    PdfWriter writer = new PdfWriter(dest);

    //Initialize PDF document
    PdfDocument pdf = new PdfDocument(writer);

    // Initialize document
    Document document = new Document(pdf, PageSize.A4);

    // Create table
    Table htable = new Table(new float[] {3, 8, 5, 10, 5, 10, 30});
    htable.setFontSize(8);
    htable.setWidthPercent(100);
    htable.addHeaderCell(new Cell().add("Col1"));
    htable.addHeaderCell(new Cell().add("Col2"));
    htable.addHeaderCell(new Cell().add("Col3"));
    htable.addHeaderCell(new Cell().add("Col4"));
    htable.addHeaderCell(new Cell().add("Col5"));
    htable.addHeaderCell(new Cell().add("Col6"));
    htable.addHeaderCell(new Cell().add("Col7"));
    htable.addCell(new Cell().add("CMS#"));
    htable.addCell(new Cell().add("C34827284"));
    htable.addCell(new Cell().add("Date:"));
    htable.addCell(new Cell().add("12/5/16"));
    htable.addCell(new Cell().add("EndDate:"));
    htable.addCell(new Cell().add("12/6/16"));
    htable.addCell(new Cell().add("Approved"));
    // Add the table
    document.add(htable);
    // Close the document
    document.close();
}

The result is shown here:

enter image description here

Note that I reduced the font size to avoid that more text is split the way CMS# is split.

Try adding htable.setWidthPercent(100); to your code if you didn't already do so. The problem should disappear.