Skip to content

RenderListener

Ralf Stuckert edited this page Apr 11, 2016 · 2 revisions

RenderListener

The RenderListener is a hook into the rendering process. You may add n listener to a Document, which are called before and after rendering a page:

public interface RenderListener {

    void beforePage(final RenderContext renderContext) throws IOException;

    void afterPage(final RenderContext renderContext) throws IOException;
}

You can use this to perform some custom rendering, like e.g. a header or footer, or - like in example Listener.java - to add the page number:

document.addRenderListener(new RenderListener() {

    @Override
    public void beforePage(RenderContext renderContext) {}

    @Override
    public void afterPage(RenderContext renderContext)
        throws IOException {
    String content = String.format("Page %s",
        renderContext.getPageIndex() + 1);
    TextFlow text = TextFlowUtil.createTextFlow(content, 11,
        PDType1Font.TIMES_ROMAN);
    float offset = renderContext.getDocument().getMarginLeft()
        + TextSequenceUtil.getOffset(text,
            renderContext.getWidth(), Alignment.Right);
    text.drawText(renderContext.getContentStream(), new Position(
        offset, 30), Alignment.Right);
    }
});

As always you will find the result in the corresponding example PDF listener.pdf.