How to add an inner table surrounded by text?
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); // phrase.add(new Chunk("Hello World")); table1.addCell(phrase); document.add(table1);
Posted on StackOverflow on Feb 10, 2015 by rveach
You are using text mode (to be used when you only have text) in a situation where you should use composite mode (because you are adding a table to a cell).
Please take a look at the NestedTableProblem example:
// table 2 final PdfPTable table2 = new PdfPTable(1); table2.setHorizontalAlignment(Element.ALIGN_LEFT); table2.getDefaultCell().setBorderColor(BaseColor.RED); table2.getDefaultCell().setBorderWidth(1); table2.addCell("Goodbye World"); // table 1 final PdfPTable table1 = new PdfPTable(1); table1.setHorizontalAlignment(Element.ALIGN_LEFT); table1.setWidthPercentage(100); // contents PdfPCell cell = new PdfPCell(); cell.setBorderColor(BaseColor.BLACK); cell.setBorderWidth(1); cell.addElement(new Chunk("Hello World")); cell.addElement(table2); cell.addElement(new Chunk("Hello World")); table1.addCell(cell); document.add(table1);
In this code snippet, the cell
object is composed of different elements (that's what composite mode is about):

Screen shot
In your code snippet, you add several elements to a Phrase
and you add this Phrase
to a PdfPCell
in text mode. As one element isn't ordinary text but a table, it can not be rendered.