问题
Does iTextPdf allow to set spacing between cells in table?
I have a table with 2 columns and I am trying to draw a border-bottom on cell. I want space between each border same as cell padding.
I am using below code:
PdfPTable table = new PdfPTable(2);
table.setTotalWidth(95f);
table.setWidths(new float[]{0.5f,0.5f});
table.setHorizontalAlignment(Element.ALIGN_CENTER);
Font fontNormal10 = new Font(FontFamily.TIMES_ROMAN, 10, Font.NORMAL);
PdfPCell cell = new PdfPCell(new Phrase("Performance", fontNormal10));
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setBorder(Rectangle.BOTTOM);
cell.setPaddingLeft(10f);
cell.setPaddingRight(10f);
table.addCell(cell);
table.addCell(cell);
table.addCell(cell);
table.addCell(cell);
document.add(table);
How do I do this?
回答1:
You probably want this effect:
That is explained in my book, more specifically in the PressPreviews example.
You need to remove the borders first:
cell.setBorder(PdfPCell.NO_BORDER);
And you need to draw the border yourself in a cell event:
public class MyBorder implements PdfPCellEvent {
public void cellLayout(PdfPCell cell, Rectangle position,
PdfContentByte[] canvases) {
float x1 = position.getLeft() + 2;
float x2 = position.getRight() - 2;
float y1 = position.getTop() - 2;
float y2 = position.getBottom() + 2;
PdfContentByte canvas = canvases[PdfPTable.LINECANVAS];
canvas.rectangle(x1, y1, x2 - x1, y2 - y1);
canvas.stroke();
}
}
You declare the cell event to the cell like this:
cell.setCellEvent(new MyBorder());
In my example, I add or subtract 2 user units from the cell's dimensions. In your case, you could define a padding p
and then add or subtract p / 2
from the cell dimensions in your PdfPCellEvent
implementation.
来源:https://stackoverflow.com/questions/29391037/is-it-possible-to-have-space-between-cells-in-itextpdf