如何使用iText5在表中指定行背景

如何使用iText5在表中指定行背景,itext,Itext,使用iText5创建PDF表格时,可以通过实现PdfPTableEvent创建表格背景,通过实现PdfPCellEvent创建单元格背景 但是一排背景呢?我怎样才能创造呢 原因是我想创建一个日历表,如下图所示: 实际上,您已经在问题中包含了答案:您必须使用表事件。看看这个例子。它包含一个表事件RowBackgroundEvent,允许您创建一个表事件来绘制单行的背景 public class RowBackgroundEvent implements PdfPTableEvent { /

使用iText5创建PDF表格时,可以通过实现
PdfPTableEvent
创建表格背景,通过实现
PdfPCellEvent
创建单元格背景

但是一排背景呢?我怎样才能创造呢

原因是我想创建一个日历表,如下图所示:


实际上,您已经在问题中包含了答案:您必须使用表事件。看看这个例子。它包含一个表事件
RowBackgroundEvent
,允许您创建一个表事件来绘制单行的背景

public class RowBackgroundEvent implements PdfPTableEvent {
    // the row number of the row that needs a background
    protected int row;

    // creates a background event for a specific row
    public RowBackgroundEvent(int row) {
        this.row = row;
    }

    /**
     * Draws the background of a row.
     */
    @Override
    public void tableLayout(PdfPTable table, float[][] widths, float[] heights,
        int headerRows, int rowStart, PdfContentByte[] canvases) {
        float llx = widths[row][0];
        float lly = heights[row];
        float urx = widths[row][widths[row].length - 1];
        float ury = heights[row - 1];
        float h = ury - lly;
        PdfContentByte canvas = canvases[PdfPTable.BASECANVAS];
        canvas.saveState();
        canvas.arc(llx - h / 2, lly, llx + h / 2, ury, 90, 180);
        canvas.lineTo(urx, lly);
        canvas.arc(urx - h / 2, lly, urx + h / 2, ury, 270, 180);
        canvas.lineTo(llx, ury);
        canvas.setColorFill(BaseColor.LIGHT_GRAY);
        canvas.fill();
        canvas.restoreState();
    }
}
这是如何使用此事件的:

public void createPdf(String filename) throws SQLException, DocumentException, IOException {
    // step 1
    Document document = new Document(PageSize.A4.rotate());
    // step 2
    PdfWriter.getInstance(document, new FileOutputStream(filename));
    // step 3
    document.open();
    // step 4
    PdfPTableEvent event = new RowBackgroundEvent(3);
    PdfPTable table = new PdfPTable(7);
    table.setTableEvent(event);
    table.getDefaultCell().setBorder(Rectangle.NO_BORDER);
    for (int i = 0; i < 10; i++) {
        for (int j = 1; j < 8; j++) {
            table.addCell(String.valueOf(j));
        }
    }
    document.add(table);
    // step 5
    document.close();
}
public void createPdf(字符串文件名)抛出SQLException、DocumentException、IOException{
//第一步
文档=新文档(PageSize.A4.rotate());
//步骤2
getInstance(文档,新文件输出流(文件名));
//步骤3
document.open();
//步骤4
PdfPTableEvent事件=新行背景事件(3);
PdfPTable=新的PdfPTable(7);
table.setTableEvent(事件);
table.getDefaultCell().setBorder(矩形,无边框);
对于(int i=0;i<10;i++){
对于(int j=1;j<8;j++){
表.addCell(字符串.valueOf(j));
}
}
文件。添加(表);
//步骤5
document.close();
}
如您所见,我们需要第三行的背景。结果如下所示:

如果要调整背景栏的大小,可以调整
llx
lly
urx
ury


如果可以绘制一行的背景,则可以扩展代码以绘制多行的背景。

谢谢,Bruno。顺便说一句,所有这些iText示例都做得很好!我从他们那里学到了很多。谢谢,非常感谢这样的反馈。