For some reason table.getDefaultCell().setBorder(PdfPCell.NO_BORDER) has no effect: my table has still borders.


Here is my code:


PdfPTable table = new PdfPTable(new float[] { 1, 1, 1, 1, 1 });
table.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
Font tfont = new Font(Font.FontFamily.UNDEFINED, 10, Font.BOLD);
table.setWidthPercentage(100);
PdfPCell cell;
cell = new PdfPCell(new Phrase("Menge", tfont));
table.addCell(cell);
cell = new PdfPCell(new Phrase("Beschreibung", tfont));
table.addCell(cell);
cell = new PdfPCell(new Phrase("Einzelpreis", tfont));
table.addCell(cell);
cell = new PdfPCell(new Phrase("Gesamtpreis", tfont));
table.addCell(cell);
cell = new PdfPCell(new Phrase("MwSt", tfont));
table.addCell(cell);
document.add(table);

Do you have any idea what I am doing wrong?

Posted on StackOverflow on Nov 30, 2014 by hiasl

You are mixing two different concepts.

Concept 1: you define every Cell (no PdfPCell in iText 7) manually, for instance:

Cell cell = new Cell()
    .add(new Paragraph("Menge"))
    .setFont(tfont)
    .setBorder(Border.NO_BORDER);

In this case, you define every aspect, every property of the cell on the cell itself.

Concept 2: you allow iText 7 to let the Cell use a Style object:

Style style = new Style()
    .setBorder(Border.NO_BORDER)
    .setFont(tfont);

table.addCell(new Cell("Adding a String").addStyle(style));
table.addCell(new Cell(new Paragraph("Adding a paragraph")).addStyle(style));

In this case, you can define properties at the level of the Style. The properties defined on the Style object will be used internally when iText adds a Cell to your table.

Conclusion: either you define the border for all the Cell instances separately, or you let iText use a Style in which case you can define the border at the level of the Style. If you choose the second option, you can adapt your code like this:

Table table = new Table(new float[] { 1, 1, 1, 1, 1 });
PdfFont tfont = PdfFontFactory.createFont(FontConstants.HELVETICA_BOLD);
table.setWidthPercent(100);
Style style = new Style()
    .setBorder(Border.NO_BORDER)
    .setFont(tfont);
table.addCell(new Cell(new Paragraph("Menge")).addStyle(style));
table.addCell(new Cell(new Paragraph("Beschreibung")).addStyle(style));
table.addCell(new Cell(new Paragraph("Einzelpreis")).addStyle(style));
table.addCell(new Cell(new Paragraph("Gesamtpreis")).addStyle(style));
table.addCell(new Cell(new Paragraph("MwSt")).addStyle(style));
document.add(table);

This decision was made by design, based on experience: it offers the most flexible to work with cells and properties.

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