iText Flying Saucer pdf headers and ignoring html

戏子无情 提交于 2019-12-07 22:01:34

问题


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 grateful to hear.


回答1:


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

https://gist.github.com/626264




回答2:


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.



来源:https://stackoverflow.com/questions/6625379/itext-flying-saucer-pdf-headers-and-ignoring-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!