问题
i've some problems with the onEndPage() method (itext), basically i'm already writing some text on footer, with the basc method like this way:
public class EventDichiarazionePdf extends PdfPageEventHelper{
private int numPage=0;
private static Font h6NormFont = new Font(Font.FontFamily.HELVETICA, 6,Font.NORMAL);
public void onStartPage(PdfWriter writer, Document document) {
numPage++;
}
public void onEndPage(PdfWriter writer, Document document) {
try {
Rectangle page = document.getPageSize();
PdfPTable footer = new PdfPTable(2);
PdfPCell cellFooter = new PdfPCell( new Phrase("Something – 03/12/2016 Customer n." + "here i need my variable",h6NormFont));
cellFooter.setHorizontalAlignment(Element.ALIGN_LEFT);
cellFooter.setBorder(0);
footer.addCell(cellFooter);
cellFooter = new PdfPCell( new Phrase( String.format("pag. %d",numPage),h6NormFont));
cellFooter.setHorizontalAlignment( Element.ALIGN_RIGHT );
cellFooter.setBorder(0);
footer.addCell(cellFooter);
footer.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
footer.writeSelectedRows( 0,-1,document.leftMargin(),document.bottomMargin(),writer.getDirectContent());
} catch ( Exception e ) {
throw new ExceptionConverter( e );
}
}
}
}
Basicaly i want to pass one more object plus write and document to the onEndPage,but this method is never called on the creation of the Pdf, reading on documentation, this kind of method is called by an Event, so i cant even change the signature of the method i guess...any suggestion? Thank you all for the answers.
回答1:
As you have found out yourself, you cannot change the method signature as you aren't the caller of the method. But as you create and register the event object, you can extend its class to have an additional property which you can use for your task, e.g.:
public class EventDichiarazionePdf extends PdfPageEventHelper{
// vvv--- Change
public String extraValue = "";
// ^^^--- Change
private int numPage=0;
private static Font h6NormFont = new Font(Font.FontFamily.HELVETICA, 6,Font.NORMAL);
public void onStartPage(PdfWriter writer, Document document) {
numPage++;
}
public void onEndPage(PdfWriter writer, Document document) {
try {
Rectangle page = document.getPageSize();
PdfPTable footer = new PdfPTable(2);
// vvv--- Change
PdfPCell cellFooter = new PdfPCell( new Phrase("Something – 03/12/2016 Customer n." + extraValue ,h6NormFont));
// ^^^--- Change
cellFooter.setHorizontalAlignment(Element.ALIGN_LEFT);
cellFooter.setBorder(0);
footer.addCell(cellFooter);
[...]
} catch ( Exception e ) {
throw new ExceptionConverter( e );
}
}
}
}
Thus, as soon as you know the value to use for the next footer, you simply assign it to its extraValue
variable.
来源:https://stackoverflow.com/questions/42853816/how-to-pass-custom-object-in-onendpage-itext-method