itext document Footer on eachpage - Spring MVC

2019-09-09 05:02发布

问题:

I have used Spring's AbstractPdfView to generate Pdf Documents. I am trying to add footer to each page on the document but it doesn't seem to work. This is what I have so far..

  protected void buildPdfDocument(@SuppressWarnings("rawtypes") Map map, Document doc,
        PdfWriter writer, HttpServletRequest req, HttpServletResponse response)
        throws Exception {

    response.setContentType("application/pdf");
    response.setHeader("Content-Disposition", "attachment;filename=UserAccessReport.pdf");

    doc.setPageSize(PageSize.LEGAL.rotate());

    String date = new SimpleDateFormat("MM/dd/yyyy").format(new Date()).toString();
    String headerString = "Report Date: "+date;

    HeaderFooter hf = new HeaderFooter(new Phrase(headerString), true);
    doc.setFooter(hf);
    doc.newPage();

    PdfPTable table = new PdfPTable(8); 
    table.setHorizontalAlignment(Element.ALIGN_CENTER);
    ///add table cells

    doc.add(table);
}

Code above doesn't add any footer to the document.

If I add the HeaderFooter element to the document before calling newPage, like...

            HeaderFooter hf = new HeaderFooter(new Phrase(headerString), true);
    doc.setFooter(hf);
    doc.add(hf);
            doc.newPage();

in this case I see weird behavior. First page in the document is a blank document and the second page has the table with footer as expected. I understand why two pages are created but don't understand why footer wasn't added to first page.

If I moved add to after calling newPage then again, there is no footer after the table..

回答1:

you are in very old version ... new version does given below

HeaderFooter hfFooter = new HeaderFooter(new Phrase("My Footer", new    Font(FontFactory.GetFont("Tahoma", 10, 0))), false);
hfFooter.Alignment = 1;
docMyPDFDocument.Footer = hfFooter;


回答2:

I'm also using a footer in a Spring context and your example

HeaderFooter hf = new HeaderFooter(new Phrase(headerString), true);
doc.setFooter(hf);

works perfectly for me, except that i do not call newPage(). Why this call? Do you want a blank first page? Did you try it without calling newPage()?



回答3:

This worked for me: Just override the buildPdfMetadata method.

public class SomePdfView extends AbstractPdfView {
    @Override
    protected void buildPdfMetadata(Map<String, Object> model, Document document, HttpServletRequest request) {
        HeaderFooter footer = new HeaderFooter(new Phrase("Footer"), false);
        footer.setAlignment(Element.ALIGN_CENTER);
        footer.setBorder(Rectangle.TOP);
        document.setFooter(footer);
        super.buildPdfMetadata(model, document, request);
    }
}