开发者

iText Flying Saucer pdf headers and ignoring html

We use xhtml to pdf with good success, but a new requirement came up to have headers and page count on every page. We are using newset release of Flying Saucer.

I followed example here: http://today.java.net/pub/a/today/2007/06/26/generating-pdfs-with-flying-saucer-and-itext.html#page-specific-features

...but this would not work. The header would be top left on first page.

If I use the r7 version, headers and page numbering works perfectly, but none of the passed in html is rendered, whilst in r8 the headers\ page numbers are ignored, but the html is rendered perfectly. xHTML used for tests is copied from url above.

I know I must be missing something very simple, if anyone has any ideas\ comments, I would be very gratefu开发者_StackOverflow中文版l to hear.


I think they changed this functionality in r8.... try this method instead:

https://gist.github.com/626264


We use the same method and everything works perfectly, I have however decided not to use flying-saucer's built in headers/footers and use a PdfStamper to add them after the PDF is generated, it works quite well, here is an example.

    public void modifyPdf(PdfStamper stamper) {
        this.reader = stamper.getReader();

        PdfContentByte under = null;

        PdfPTable header = null;
        PdfPTable footer = null;

        final int total = this.reader.getNumberOfPages();
        for (int page = 1; page <= total; page++) {
            under = stamper.getUnderContent(page);

            final PdfDocument doc = under.getPdfDocument();
            final Rectangle rect = this.reader.getPageSizeWithRotation(page);

            header = ... //build your header
            footer = ... // build your footer

            final float x = 0;

            //write header to PDF
            if (header != null) {
                float y = (rect.getTop() - 0);
                header.writeSelectedRows(0, -1, x, y, under);
            }

            //write footer to PDF
            if (footer != null) {
                float y = (rect.getBottom() + 20);
                footer.writeSelectedRows(0, -1, x, y, under);
            }
        }
    }

you can build your stamper like this:

        final PdfReader reader = new PdfReader(/*your pdf file*/);
        final PdfStamper stamper = new PdfStamper(reader, /* output */);

Hope you find this helpful.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜