itextpdf计算table高度,判断PDF剩余高度实现换页添加

在写PDF的时候你可能会遇到这种场景:

需要添加的table为一个整体,不能被拆分在两个PDF页中展示

这时候就需要先判断剩余的空白高度能否放下table的高度,否则换页添加

已使用高度计算:

 public static float currentHeight(PdfWriter writer) throws ReflectiveOperationException{
        Method getPdfDocument = writer.getClass().getDeclaredMethod("getPdfDocument");
        getPdfDocument.setAccessible(true);
        PdfDocument pdfD = (PdfDocument) getPdfDocument.invoke(writer);
        Field getHeight = pdfD.getClass().getDeclaredField("currentHeight");
        getHeight.setAccessible(true);
        return  (float)getHeight.get(pdfD);
    }

剩余高度计算:

纸张大小 - 上下边距:代码如下

document.getPageSize().getHeight() - document.bottomMargin() - document.topMargin();

剩余高度 = 纸张大小 - 上下边距 - 已使用高度

计算table高度

经过测试我发现没有被添加到document对象中的table计算的高度就一直是0,但是我必须计算出来table高度后我才能确定当前页的剩余高度能不能添加

实在没招了于是我想到了一个笨方法,(经测有效)

重新创建一个document对象计算出来后再将其销毁

    public float calculatePdfTableHeights(PdfPTable pdfPTable) throws DocumentException, IOException {
        Document document = new Document(PageSize.A4, 60, 60, 30, 40);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        PdfWriter writer = PdfWriter.getInstance(document, byteArrayOutputStream);
        document.open();
        document.add(pdfPTable);
        float hight  = pdfPTable.calculateHeights();
        document.close();
        byteArrayOutputStream.close();
        writer.close();
        return hight;
    }

于是table高度计算出来了,剩余高度也计算出来了,就可以判断是否需要换页

document.newPage();

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值