2014-08-28 49 views
0

我會毫不猶豫地承認這可能是this的重複,但這裏一直沒有答案,我想我可以添加更多信息。iText PdfPTableEventForwarder沒有得到預期的調用時,

利用iText 5.5.0

我需要什麼:斑馬條紋表,其中有細胞之間的頂/底部邊框,但有一個底部邊框表本身,或每當表分成多個頁面。我使用「lorem ipsum」和其他任意數據從測試中獲得了一小段片段。我部分地切斷了「第1頁,共2頁」的頁腳,但該表確實有 有第2頁上的其他行。我希望該表看起來更多或更少,因爲它增加了底部邊框頁面的最後一行。

enter image description here

我想實現通過一個匿名內部類PdfPTableEventForwarder。我有一個看起來像這樣的方法:

public PdfPTable createStandardTable(int columnCount, int headerRows) { 
    PdfPTableEventForwarder tableEvent = new PdfPTableEventForwarder() 
    { 
     // begin another anonymous inner class extends PdfPTableEventForwarder 
     @Override 
     public void splitTable(PdfPTable table) { 
      PdfPRow lastRow = table.getRow(table.getLastCompletedRowIndex()); 
      for (PdfPCell cell : lastRow.getCells()) { 
       cell.setBorder(Rectangle.LEFT + Rectangle.RIGHT + Rectangle.BOTTOM); 
      } 
     } 
     // end anonymous inner class extends PdfPTableEventForwarder 
    }; 

    PdfPTable table = new PdfPTable(columnCount); 
    table.setSpacingBefore(TABLE_SPACING); 
    table.setSpacingAfter(TABLE_SPACING); 
    table.setWidthPercentage(TABLE_WIDTH_PERCENT); 
    table.setHeaderRows(headerRows); 
    table.setTableEvent(tableEvent); 
    return table; 
} 

和其他地方創建我的表像這樣:

// Details of code to create document and headers not shown 
PdfPTable table = createStandardTable(12, 2); 
// Details of code to build table not shown, but includes cell.setBorder(Rectangle.LEFT + Rectangle.RIGHT) 
document.add(table); 

我已經在調試器與一個破發點,在第一線運行這裏面splitTable找到該事件只被調用一次。我期望它會調用兩次:第一次在頁面1結束並且第2頁開始時,第二次在表格完成時。此外,我在此表中有30行加上2個標題行:第1頁的25行適合標題,最後5行在第2頁。調試程序告訴我table.getLastCompletedRowIndex() 的計算結果爲32,而不是預期的27

實際上,保存到我的文件的最終結果在第2頁的最後一行有一個底部邊框,但第1頁沒有一個邊框。在添加PdfPTableEventForwarder之前,兩者都沒有邊框。

回答

2
  • 如果您有一個包含10行的表格並且分割了一行,則總共有11行。這解釋了你對行數的困惑。
  • 我不明白爲什麼當你只需要一個事件時使用PdfPTableEventForwarder。當您有一系列PdfPTable事件時,使用PdfPTableEventForwarder
  • 更改表格或單元格事件中的單元格爲不正確。這會永不工作。當事件觸發時,單元格已經被渲染。如果要繪製底部邊框,請使用在PdfPTableEvent實現的tableLayout()方法中交給您的座標,在lineTo(),moveTo()stroke()命令序列中繪製底部邊框。

一個與您所需要的不同的示例,但以類似的方式可以在此找到:PressPreviews.java。沒有需要拆分之前或之後,您只需要基本的PdfPTableEvent接口和tableLayout()方法,看起來像這樣。

public void tableLayout(PdfPTable table, float[][] width, float[] height, 
     int headerRows, int rowStart, PdfContentByte[] canvas) { 
    float widths[] = width[0]; 
    float x1 = widths[0]; 
    float x2 = widths[widths.length - 1]; 
    float y = height[height.length - 1]; 
    PdfContentByte cb = canvas[PdfPTable.LINECANVAS]; 
    cb.moveTo(x1, y); 
    cb.lineTo(x2, y); 
    cb.stroke(); 
} 

我關於y值是誤會,但我希望你得到的總體思路。