How to add an inner table surrounded by text?

Category: 
Tags: tablesnested tablesiText 7

I am trying to add a table surrounded by text to an outer table, but the inner table disappears and I can't seem to fix the problem.

Here is what I am expecting:

*********************
* Hello World       *
* +++++++++++++++++ * <--
* + Goodbye World + * <-- these 3 lines never show up in the PDF
* +++++++++++++++++ * <--
* Hello World       *
*********************
Here is my code example:

final PdfPTable table2 = new PdfPTable(1);
table2.getDefaultCell().setBorderColor(BaseColor.RED);
table2.getDefaultCell().setBorderWidth(1);
table2.addCell("Goodbye World");
final PdfPTable table1 = new PdfPTable(1);
table1.setWidthPercentage(100);
table1.getDefaultCell().setBorderColor(BaseColor.BLACK);
table1.getDefaultCell().setBorderWidth(1);
Phrase phrase = new Phrase();
phrase.add(new Chunk("Hello World"));
phrase.add(table2); // <--- added but doesn't show up!
phrase.add(new Chunk("Hello World"));
table1.addCell(phrase);
document.add(table1);
Posted on StackOverflow on Feb 10, 2015 by rveach

Please take a look at the NestedTableProblem example:

// table 2
Table table2 = new Table(1);
table2.setHorizontalAlignment(HorizontalAlignment.LEFT);
table2.addCell(new Cell().setBorder(new SolidBorder(Color.RED, 1)).add("Goodbye World"));
table2.setWidthPercent(80);
// table 1
Table table1 = new Table(1);
table1.setHorizontalAlignment(HorizontalAlignment.LEFT);
Cell cell = new Cell();
cell.setBorder(new SolidBorder(Color.BLACK, 1));
cell.add("Hello World");
cell.add(table2);
cell.add("Hello World");
table1.addCell(cell);
doc.add(table1);

In this code snippet, we compose the Cell object of different elements and add it to the main table. Here is the result:

Screen shot
Screen shot

Note that we use Table and Cell classes in iText 7 instead of PdfPTable and PdfPCell.

Click this link if you want to see how to answer this question in iText 5.