【问题标题】:table borders not expanding properly in pdf using itext使用 itext 在 pdf 中未正确扩展表格边框
【发布时间】:2014-05-29 14:18:04
【问题描述】:

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

请查找附件的pdf文件和html文件以供参考。

Generated PDf file with my code

Sample html file

【问题讨论】:

  • 边界是设计的。如果想改变默认绘制边框的方式,需要去掉边框(NO_BORDER),实现PdfPTable接口绘制自己的自定义边框:api.itextpdf.com/itext/com/itextpdf/text/pdf/…
  • 是的,边框是设计出来的,但问题是我已通过评论在附件 pdf 文件中显示。虽然表格创建没有在第一页水平边框中完成,并且从第二页水平边框开始显示哪个错误。请查看随附的 pdf 文件以了解问题。
  • 我了解您的问题。拆分表格时,您不需要底部边框。这意味着您必须删除设计中存在的边框,并且您需要使用单元格和表格事件以您喜欢的方式绘制自定义边框。你可能误解了我的回答,因为我写的是PdfPTable 而不是PdfPTableEvent。但是,该链接引用了正确的类。
  • 请注意,您的问题是说 iText 的行为不正确:上一页垂直边框再次加框,这是错误的。 这是一种观点,而不是事实。 iText 的行为方式是大多数 iText 用户所期望的。如果您想要不同的行为,您可以按照我的回答中的说明微调边框的绘制方式。

标签: pdf itext


【解决方案1】:

您想要一个类似于 custom_border2.pdf 的表格。

正如我的 cmets 中所解释的,您需要将单元格的边框设置为 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

【讨论】:

  • 这就是我要找的
猜你喜欢
  • 2017-05-12
  • 1970-01-01
  • 1970-01-01
  • 2017-05-27
  • 1970-01-01
  • 2013-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多