如何使用onEndPage方法在PDF标头中打印动态字符串

时间:2019-04-04 20:33:46

标签: java itext pdf-generation

在以pdf格式打印一张表格时,我的pdf文档中有多个表格,我需要在要打印表格的所有页面的页眉部分中打印表格的名称。另外,标题值需要根据表名进行更改。

我尝试为每个表的标题设置新的表名,但是所有页面仅打印最后一个表名。

示例代码

PdfGenerator.class



    public static void main(String[] args) throws FileNotFoundException, DocumentException {

        try {
            String pdfFilePath = "C:\\Users\\ychitela\\Desktop\\demo\\NewPdf.pdf";
            File file = new File(pdfFilePath);
            FileOutputStream fileout = new FileOutputStream(file);
            Document document = new Document(PageSize.A4.rotate(), 36, 36, 55, 25);
            PdfWriter writer = PdfWriter.getInstance(document, fileout);
            ReportHeader event = new ReportHeader();
            writer.setPageEvent(event);
            writer.setViewerPreferences(PdfWriter.PageModeUseOutlines);
            document.open();
            document.addAuthor("Me");
            document.addTitle("Table Report");

            Font font = FontFactory.getFont("TIMES_ROMAN", 12, BaseColor.BLACK);
            document.add(new Paragraph("Intro Page"));
            document.newPage();
            Chapter chapter = new Chapter(new Paragraph("Table \n\n"), 0);
            chapter.setNumberDepth(0);
            chapter.add(new Paragraph("   "));
            for (int i = 1; i < 5; i++) {

                float[] columnWidths = { 1f, 1f };
                // create PDF table with the given widths
                PdfPTable table = new PdfPTable(columnWidths);
                table.setHorizontalAlignment(Element.ALIGN_LEFT);
                table.setWidthPercentage(30.0f);
                Section subsection = chapter.addSection(new Paragraph("Table "+i+" \n\n"), 0);
                event.setTableName("Table header" + i);
                writer.setPageEvent(event);
                table.addCell(new PdfPCell(new Phrase("Column 1", font)));
                table.addCell(new PdfPCell(new Phrase("Column 2", font)));
                table.setHeaderRows(1);
                for (int j = 0; j < 25; j++) {
                    table.addCell(new PdfPCell(new Phrase("Hello" + j, font)));
                    table.addCell(new PdfPCell(new Phrase("World" + j, font)));
                }
                subsection.add(table);
                subsection.newPage();

            }
            document.add(chapter);
            document.close();
            System.out.println("Done");
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

Header.class

public class ReportHeader extends PdfPageEventHelper {

    private String tableName;

    public String getTableName() {
        return tableName;
    }

    public void setTableName(String tableName) {
        this.tableName = tableName;
    }

    @Override
    public void onEndPage(PdfWriter writer, Document document) {
        PdfPTable table2 = new PdfPTable(1);

        try {
            BaseColor basecolour = BaseColor.DARK_GRAY;
            Font fontboldHead = FontFactory.getFont("TIMES_ROMAN", 8, basecolour);

            table2.setTotalWidth(300);
            PdfPCell cell2 = new PdfPCell(new Paragraph(tableName, fontboldHead));
            cell2.setBorder(Rectangle.NO_BORDER);
            cell2.setHorizontalAlignment(Element.ALIGN_LEFT);
            cell2.setVerticalAlignment(Element.ALIGN_BOTTOM);
            table2.addCell(cell2);
            table2.writeSelectedRows(0, -1, document.left(), 580, writer.getDirectContent());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

1 个答案:

答案 0 :(得分:1)

发现自己的原因是

  

我在实际的代码和循环中使用了章节和小节,在循环的最后,我将该章节添加到文档中。因此导致只打印最后一个表名。

要使动态标题正常工作,必须更早地添加内容;特别是每次添加新表时,即每次标题更改时,都必须将本章的当前内容添加到文档中。

您可以利用Chapter实现LargeElement的事实来做到这一点,即您可以向文档中多次添加Chapter实例,并且每次仅添加新内容自上次以来的章节已写入文档。为此,您必须在开始时将其Complete属性设置为false,然后再将其设置为true,直到最后一次添加。因此,

Chapter chapter = new Chapter(new Paragraph("Table \n\n"), 0);
// prepare chapter to be set piecewise
chapter.setComplete(false);
chapter.setNumberDepth(0);
chapter.add(new Paragraph("   "));
for (int i = 1; i < 5; i++) {

    float[] columnWidths = { 1f, 1f };
    // create PDF table with the given widths
    PdfPTable table = new PdfPTable(columnWidths);
    table.setHorizontalAlignment(Element.ALIGN_LEFT);
    table.setWidthPercentage(30.0f);
    // add recent chapter additions
    document.add(chapter);
    Section subsection = chapter.addSection(new Paragraph("Table "+i+" \n\n"), 0);
    event.setTableName("Table header" + i);
    writer.setPageEvent(event);
    table.addCell(new PdfPCell(new Phrase("Column 1", font)));
    table.addCell(new PdfPCell(new Phrase("Column 2", font)));
    table.setHeaderRows(1);
    for (int j = 0; j < 25; j++) {
        table.addCell(new PdfPCell(new Phrase("Hello" + j, font)));
        table.addCell(new PdfPCell(new Phrase("World" + j, font)));
    }
    subsection.add(table);
    subsection.newPage();

}
// prepare chapter to be completed
chapter.setComplete(true);
// final adding of chapter
document.add(chapter);

ChapterAndDynamicHeader测试testLikeYuvarajChitelaImproved