我对onEndPage((方法(itext(有一些问题,基本上我已经在页脚上写了一些文本,使用bassc方法如下:
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 );
}
}
}
}
基本上我想再传递一个对象加上写入和文档到 onEndPage,但是在创建 PDF 时从未调用过此方法,阅读文档,这种方法是由事件调用的,所以我什至无法更改我猜的方法的签名......有什么建议吗?谢谢大家的回答。
正如您自己发现的那样,您无法更改方法签名,因为您不是该方法的调用方。但是,在创建和注册事件对象时,可以扩展其类以具有可用于任务的附加属性,例如:
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 );
}
}
}
}
因此,一旦您知道要用于下一个页脚的值,您只需将其分配给其extraValue
变量即可。