使用itext在pdf中正确扩展表格边框

时间:2014-05-29 14:18:04

标签: pdf itext

我想生成pdf,其中包含带边框的表格,并且该表格中包含更多数据,因此在生成pdf时,它会生成两页。但问题是桌面边界没有扩大 页面到页面,即在下一页边框(水平),上一页垂直边框再次框架,这是错误的。在下一页中是水平的,上一页中的垂直不应该来。

请参阅随附的pdf文件和html文件以供参考。

Generated PDf file with my code

Sample html file

1 个答案:

答案 0 :(得分:3)

您需要一个看起来像custom_border2.pdf的表格。

正如我的评论中所解释的那样,您需要通过更改默认单元格将单元格的边框设置为NO_BORDER

table.getDefaultCell().setBorder(Rectangle.NO_BORDER);

或者通过更改特定单元格的属性:

PdfPCell cell = new PdfPCell(new Phrase(TEXT));
cell.setBorder(Rectangle.NO_BORDER);

或两者兼而有之。

然后你必须创建一个表事件:

class BorderEvent implements PdfPTableEventAfterSplit {

    protected boolean bottom = true;
    protected boolean top = true;

    public void splitTable(PdfPTable table) {
        bottom = false;
    }

    public void afterSplitTable(PdfPTable table, PdfPRow startRow, int startIdx) {
        top = false;
    }

    public void tableLayout(PdfPTable table, float[][] width, float[] height,
            int headerRows, int rowStart, PdfContentByte[] canvas) {
        float widths[] = width[0];
        float y1 = height[0];
        float y2 = height[height.length - 1];
        float x1 = widths[0];
        float x2 = widths[widths.length - 1];
        PdfContentByte cb = canvas[PdfPTable.LINECANVAS];
        cb.moveTo(x1, y1);
        cb.lineTo(x1, y2);
        cb.moveTo(x2, y1);
        cb.lineTo(x2, y2);
        if (top) {
            cb.moveTo(x1, y1);
            cb.lineTo(x2, y1);
        }
        if (bottom) {
            cb.moveTo(x1, y2);
            cb.lineTo(x2, y2);
        }
        cb.stroke();
        cb.resetRGBColorStroke();
        bottom = true;
        top = true;
    }
}

如果需要绘制顶部或底部边框,splitTable()afterSplitTable()方法将会跟踪。实际边框使用tableLayout()方法绘制。

您需要在创建表后立即设置此表事件:

PdfPTable table = new PdfPTable(2);
BorderEvent event = new BorderEvent();
table.setTableEvent(event);

现在,您将获得所需的行为,如我的初始评论中所述。您可以找到完整的代码示例here。我提供了一个更复杂的例子here

相关问题