How to enforce that the iText PageEvent.onStartPag

2019-09-01 04:19发布

问题:

Usually onStartPage() is called before any content is written.

In my use case its somehow invoked after some content is written to the new page.

What I do:

  1. Create a Paragraph with some introduction
  2. Create an Element with setKeepTogether(true). This element is so big, that iText will put it on the next page (what is the correct behaviour).
  3. Now the onStartPage() is called after the element is added to the new page.

I depend on this method because i need to add a small text like continuation of xx to the top of the page.

This example reproduces the behaviour:

public class Main {
    public static String someTompic = null;

    public static void main(final String[] args) throws Exception {
        final Document document = new Document(PageSize.A7);

        final PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("text.pdf"));

        // This PageEventHelper should write a small text "Continuation: ..." at the beginning if
        // a PageBreak was forced by "keepTogether"
        writer.setPageEvent(new PdfPageEventHelper() {

            @Override
            public void onStartPage(final PdfWriter writer, final Document document) {
                try {
                    if (someTompic != null)
                        document.add(new Paragraph("Continuation: " + someTompic));
                }
                catch (final DocumentException e) {
                    e.printStackTrace();
                }
            }
        });

        document.open();

        // Now I add the introduction text
        document.add(new Paragraph("A nice \nIntroduction \nover some lines."));

        // Now I put my "huge" thing. If this breaks,
        // the first line of the new page should be Continuation of ...
        someTompic = "smth.";

        final Paragraph paragraph = new Paragraph("What is \nthe answer \nto life the \nuniverse and \neverything?\n\nThe Answer to \nthis question \nis:\n42");
        paragraph.setKeepTogether(true);
        document.add(paragraph);

        document.close();
    }
}

This Link shows the broken PDF: PDF on Github

标签: java itext