且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

对角拆分表格单元格

更新时间:2023-02-04 19:58:32

You need to create that special cell using a cell event as documented in the official documentation.

I'll give you some pseudo code that you can convert to C# and that will create a table that looks like this:

This is the pseudo-code for the cell event:

class Diagonal implements PdfPCellEvent {
    protected String columns;
    protected String rows;

    public Diagonal(String columns, String rows) {
        this.columns = columns;
        this.rows = rows;
    }

    public void cellLayout(PdfPCell cell, Rectangle position,
        PdfContentByte[] canvases) {
        PdfContentByte canvas = canvases[PdfPTable.TEXTCANVAS];
        ColumnText.showTextAligned(canvas, Element.ALIGN_RIGHT, 
            new Phrase(columns), position.getRight(2), position.getTop(12), 0);
        ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, 
            new Phrase(rows), position.getLeft(2), position.getBottom(2), 0);
        canvas = canvases[PdfPTable.LINECANVAS];
        canvas.moveTo(position.getLeft(), position.getTop());
        canvas.lineTo(position.getRight(), position.getBottom());
        canvas.stroke();
    }
}

This is the pseudo-code that shows you how to use the cell event:

public void createPdf(String dest) throws IOException, DocumentException {
    Document document = new Document();
    PdfWriter.getInstance(document, new FileOutputStream(dest));
    document.open();
    PdfPTable table = new PdfPTable(6);
    table.getDefaultCell().setMinimumHeight(30);
    PdfPCell cell = new PdfPCell();
    cell.setCellEvent(new Diagonal("Gravity", "Occ"));
    table.addCell(cell);
    table.addCell("1");
    table.addCell("2");
    table.addCell("3");
    table.addCell("4");
    table.addCell("5");
    for (int i = 0; i < 5; ) {
        table.addCell(String.valueOf(++i));
        table.addCell("");
        table.addCell("");
        table.addCell("");
        table.addCell("");
        table.addCell("");
    }
    document.add(table);
    document.close();
}

Now it's up to you to convert this pseudo code (that is actually working Java code) to C#.