Reputation: 11
i am creating one pdf output using iText 5.0.5.
I am reading the data in the form of bytes from database and then adding it to the document using HTMLWorker to generate pdf.
BUt i am not able to add header on each paage for that pdf document.
please help.
Upvotes: 1
Views: 3973
Reputation: 15870
1) The latest iText is 5.0.6.
2) To create a page header and footer, you need to use the PdfPageEvent
interface. This is generally done by deriving from PdfPageEventHelper
, and overriding just the methods you need.
In the PdfPageEvent
, you must draw to the PDF using a PdfContentByte
. The good news is that you can use a ColumnText
to add aligned text into a given bounding box, and it'll handle line breaks for you.
public class HeaderFooterPageEvent extends PdfPageEventHelper {
private String headerStr, footerStr;
private Rectangle hBox, fBox;
public HeaderFooterPageEvent(String hStr, Rectangle _hBox, String fString, Rectangle _fBox) {
headerStr = hStr;
hBox = _hBox;
footerStr = fStr;
fBox = _fBox;
}
public onEndPage(PdfWriter writer, Document doc) {
// draw the header text.
ColumnText.showTextAligned(writer.getDirectContent(),
Element.ALIGN_RIGHT, headerStr, hBox.getRight(), hBox.getTop, 0);
// draw the footer text.
ColumnText.showTextAligned(writer.getDirectContent(),
Element.ALIGN_RIGHT, footerStr, fBox.getRight(), fBox.getTop, 0);
}
}
This won't work so well if your header & footer are in HTML. For that you'll have to do some round-about hackery.
1) Create a new Document/PdfWriter with page margins matching the size (height & width) of your header.
2) Render all the header HTML into that page.
3) save the pdf.
4) Import that PDF page into your other document, and draw it thusly:
public onEndPage(PdfWriter writer, Document doc) {
PdfReader reader = new PdfReader(headerPDFPath);
PdfImportedPage headerPageImport = writer.getImportedPage(reader, 1); // 1 -> first page
PdfContentByte cb = writer.getDirectContent();
cb.addTemplate(headerPageImport, hBox.bottom(), hBox.left());
}
Upvotes: 2