在写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();