如何使用java中的itext在pdf文档的最后一页底部创建表

时间:2014-05-09 06:28:29

标签: java itext

我在java中使用itext在pdf文档中创建了表。在功能方面工作得很好。 但我需要将表格显示为文档的下方。

这是我的代码

PdfPTable datatablebottom = new PdfPTable(8);
            PdfPCell cell = new PdfPCell();
            cell.setBorder(Rectangle.NO_BORDER);
            cell.setColspan(8);
            cell.setBackgroundColor(BaseColor.GRAY);
            cell.setBorderWidthTop(5.0f);
            cell.setBorderColorTop(BaseColor.DARK_GRAY);

            if(msgfb.equals("1")){
                //document.add(new Paragraph(""));
                cell.addElement(new Paragraph(""));
            }else if(msgfb.equals("2")){
                //document.add(new Paragraph("Thank you for your business"));
                Paragraph pf = new Paragraph("Thank you for your business Thanks for your bussiness Thanks for your bussiness Thanks for your bussiness Thanks for your bussiness Thanks for your bussiness Thanks for your bussiness",BT_NORMAL);
                pf.setAlignment(Element.ALIGN_CENTER);
                cell.addElement(pf);
            }else{
                //document.add(new Paragraph(msgfb));
                Paragraph pf = new Paragraph(msgfb,BT_NORMAL);
                pf.setAlignment(Element.ALIGN_CENTER);
                cell.addElement(pf);
                //cell.addElement(new Paragraph(msgfb,BT_NORMAL));
            }
            cell.setPaddingBottom(10.0f);
            datatablebottom.addCell(cell);
            datatablebottom.setTotalWidth(PageSize.A4.getWidth()-70);
            datatablebottom.setLockedWidth(true);
            document.add(datatablebottom);

1 个答案:

答案 0 :(得分:0)

您需要定义表格的绝对宽度:

datatable.setTotalWidth(document.right(document.rightMargin()) - document.left(document.leftMargin()));

然后你需要更换一行:

document.add(datatablebottom);

这一个:

datatable.writeSelectedRows(0, -1, document.left(document.leftMargin()), datatable.getTotalHeight() + document.bottom(document.bottomMargin()), writer.getDirectContent());

writeSelectedRows()方法将表绘制在绝对位置。我们通过询问document的左边距(x值)并将表格的高度添加到文档的下边距(Y坐标)来计算该位置。我们绘制所有行(0到-1)。