问题
I'm looking at the sample : http://developers.itextpdf.com/question/how-add-html-headers-and-footers-page
but in the onEndPage method
@Override
public void onEndPage(PdfWriter writer, Document document) {
try {
ColumnText ct = new ColumnText(writer.getDirectContent());
ct.setSimpleColumn(new Rectangle(36, 832, 559, 810));
for (Element e : header) {
ct.addElement(e);
}
ct.go();
ct.setSimpleColumn(new Rectangle(36, 10, 559, 32));
for (Element e : footer) {
ct.addElement(e);
}
ct.go();
} catch (DocumentException de) {
throw new ExceptionConverter(de);
}
}
we must know height and width of the ractangle in which the header elements will go.
In my case at compilation time I don't know which HTML will be used, so I would like to deduce dimensions, or use another code that don't need width and heght
回答1:
You have a Document object in the parameters of the onEndPage() method. You can get the page size of the document like this:
Rectangle pageSize = document.getPageSize();
You can also ask the document for its margins:
float left = document.leftMargin();
float right = document.rightMargin();
float top = document.topMargin();
float bottom = document.bottomMargin();
You can use these values to define the available space for headers and footers.
E.g. the header:
Rectangle rect1 = new Rectangle(
pageSize.left() + left, pageSize.top() - top,
pageSize.right() - right, pageSize.top());
Or the footer:
Rectangle rect2 = new Rectangle(
pageSize.left() + left, pageSize.bottom(),
pageSize.right() - right, pageSize.bottom() + bottom);
Caveat: there is a chance that your rectangles will be too small for the content that you are adding. In that case, some of the content will be lost. You will know when that happens by looking at the return value of the go() method:
int status = ct.go();
boolean fits = !ColumnText.hasMoreText(status);
If fits is true no content was lost. If fits is false, you may want to reconsider how you're adding the content. You could add the content in simulation mode first, check if it fits, and then add it for real. If it doesn't fit, you can make the content smaller (for instance by reducing the font size) and try again until the content fits.
回答2:
In reply at Bruno Lowagie:
My aim is to discover the exact dimensions of the header rectangle, so I can print the body of the document with the right top margin.
I don't want this:
but I don't know the html header content before runtime, so I need a way to get the header rectangle height without doing any attemps.
来源:https://stackoverflow.com/questions/40129084/itext-html-header-and-footer-dimensions