PDF footer at the bottom using iTextSharp

2019-06-24 12:15发布

问题:

I am trying to create a pdf document in c# using iTextSharp 5.0.6. I want to add header and footer to every page in OnStartPage and OnEndPage events respectively.

In case of footer there is a problem that the footer is created right where the page ends whereas I would like to be at the bottom of page.

Is there a way in iTextSharp to specify page height so that footer is always created at the bottom.

Thanks!

回答1:

The page's height is always defined:

document.PageSize.Height // document.getPageSize().getHeight() in Java

Keep in mind that in PDF 0,0 is the lower left corner, and coordinates increase as you go right and UP.

Within a PdfPageEvent you need to use absolute coordinates. It sounds like you're either getting the current Y from the document, or Just Drawing Stuff at the current location. Don't do that.

Also, if you want to use the same exact footer on every page, you can draw everything into a PdfTemplate, then draw that template into the various pages on which you want it.

PdfTemplate footerTmpl = writer.getDirectContent().createTemplate( 0, 0, pageWidth, footerHeight );

footerTmpl.setFontAndSize( someFont, someSize );
footerTmpl.setTextMatrix( x, y );
footer.showText("blah");
// etc

Then in your PdfPageEvent, you can just add footerTempl at the bottom of your page:

 writer.getDirectContent().addTemplateSimple( footerTmpl, 0, 0 );

Even if most of your footer is the same, you can use this technique to save memory, execution time, and file size.

Furthermore, if you don't want to mess with PdfContentByte drawing commands directly, you can avoid them to some extent via ColumnText. There are several SO questions tagged with iText or iTextSharp dealing with that class. Poke around, you'll find them.