需要帮助才能触发iText单元格事件。
在下面的演示中,我预计单元格事件会触发两次。但它只在第一个细胞上触发。差异似乎是第一个细胞的细胞事件 在将单元格添加到表格之前添加到单元格。我已经阅读了这本书和javadoc,并且无法将提到的内容作为先决条件。这是一个错误吗?有解决方法吗?
public class ITextCellEvent {
public static void main( String[] args ) throws FileNotFoundException, DocumentException {
Document doc = new Document( PageSize.A4 );
float twocm = Utilities.millimetersToPoints( 20f );
doc.setMargins( twocm, twocm, twocm, twocm );
PdfWriter.getInstance( doc, new FileOutputStream( new File( "iTextCellEventProblem.pdf" ) ) );
try {
doc.open();
PdfPTable table = new PdfPTable( 2 );
table.setTotalWidth( doc.right() - doc.left() );
table.setLockedWidth( true );
table.setWidths( new int[] { 50, 50 } );
PdfPCell leftCell = new PdfPCell();
leftCell.addElement( new Paragraph( "I am the left" ) );
leftCell.setCellEvent( new MyCellEvent() ); //Event added to cell before adding cell to table, it works.
PdfPCell rightCell = new PdfPCell();
rightCell.addElement( new Paragraph( "I am the right" ) );
table.addCell( leftCell );
table.addCell( rightCell );
rightCell.setCellEvent( new MyCellEvent() ); //Event added to cell after adding cell to table, doesn't work.
doc.add( table );
}
finally {
doc.close();
}
}
static final class MyCellEvent implements PdfPCellEvent {
@Override
public void cellLayout( PdfPCell cell, Rectangle position, PdfContentByte[] canvases ) {
System.out.println( "Cell event was called" );
}
}
}
重要的是我需要对表(和其他东西)进行一些测量,并将值传递给单元格渲染器的构造函数。我无法进行表格测量,直到 之后我已将单元格添加到表格中;这就是我需要的原因 将单元格添加到表格后设置单元格渲染器。
由于
答案 0 :(得分:0)
cell
方法的addCell()
参数是最终的,并且在cell
添加到PdfPTable
之后更改PdfPCell
无效,因为正在使用对象复制PdfPHeaderCell
类或PdfPCell
类的PdfPRow row = table.getRow(0);
PdfPCell cell = row.getCells()[1];
副本构造函数。我们处理副本,因为只要将单元格添加到表格中,我们就会对该单元格执行不同的操作。如果我们在原始单元格上执行这些操作,那么该单元格就无法重用(这就是某些人所做的事情:他们创建一个单元格然后重复使用它。)
但是,您的问题可能有解决方法。您可以从行中检索复制的单元格:
cell
然后将单元格事件添加到该{{1}}实例。它并不优雅,但可能有用。