2016-06-13 62 views
0

我是一個iText Java開發人員。我一直在用大桌子工作,現在我被困在垂直分割桌子的地方。iText java - 垂直和水平分割表格

在iText in Action的第119頁,尊敬的布魯諾·洛瓦吉(我對這個人非常尊重)解釋瞭如何拆分一張大表,以便列出現在兩個不同的頁面中。

我跟着他的例子,它在文檔有幾行時工作正常。

在我的情況下,我有100行,這意味着文檔需要在多個頁面中分割100行,同時垂直分割列。我如下運行我的代碼,但只顯示前34行。

能有人好心解釋什麼可能是錯誤的,此代碼:

//create a PDFPTable with 24 columns 
PdfPTable tbl = new PdfPTable(new float{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}); 
//loop through 100 rows 
for (int i = 0; i < 100; i++) { 
    //insert 24 table cells 
} 

tbl.setTotalWidth(1500);//set table width 
float top = document.top() - document.topMargin() - 30; 
PdfContentByte canvas = writer.getDirectContent(); 
tbl.writeSelectedRows(0, 12, 0, -1, document.leftMargin(), top, canvas); 
document.newPage(); 
// draw the remaining two columns on the next page 
tbl.writeSelectedRows(12, -1, 0, -1, 5, top, canvas); 

回答

2

你看不到100行,因爲100行不適合燎頁面上。當您使用writeSelectedRows()時,您需要計算頁面上有多少行,並只添加適合的行的選擇。

我在暫時在柏林的會議,但是我寫了一個簡單的例子,顯示更多或更少,你需要做什麼:

public void createPdf(String dest) throws IOException, DocumentException { 
    Document document = new Document(PageSize.A4.rotate()); 
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest)); 
    document.open(); 
    PdfPTable tbl = new PdfPTable(new float[]{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}); 
    //loop through 100 rows 
    for (int r = 1; r <= 100; r++) { 
     for (int c = 1; c <= 24; c++) { 
      tbl.addCell(String.format("r%sc%s", r, c)); 
     } 
    } 
    PdfContentByte canvas = writer.getDirectContent(); 
    tbl.setTotalWidth(1500);//set table width 
    float top = document.top() - document.topMargin() - 30; 
    float yPos = top; 
    int start = 0; 
    int stop = 0; 
    for (int i = 0; i < 100; i++) { 
     yPos -= tbl.getRowHeight(i); 
     if (yPos < 0) { 
      stop = --i; 
      tbl.writeSelectedRows(0, 12, start, stop, document.leftMargin(), top, canvas); 
      document.newPage(); 
      tbl.writeSelectedRows(12, -1, start, stop, 5, top, canvas); 
      start = stop; 
      document.newPage(); 
      yPos = top; 
     } 
    } 
    tbl.writeSelectedRows(0, 12, stop, -1, document.leftMargin(), top, canvas); 
    document.newPage(); 
    tbl.writeSelectedRows(12, -1, stop, -1, 5, top, canvas); 
    document.close(); 
} 

正如你所看到的,我跟蹤的桌子的高度,一旦冒着「脫離頁面」的風險,我渲染出合適的行,然後進入下一頁。

+0

它完美的工作我的兄弟。這是被接受的答案。我已經在這一晚上睡了很多晚,現在我可以睡一覺了。在柏林一切順利,順便說一下,我們真的需要在肯尼亞Naiobi舉辦Java/iText會議。我希望你能來啓發非洲的年輕開發者。我會做到這一點。我怎樣才能親自寫信給你?如果我違反了Stackoverflow協議,我很抱歉。 – kobewarui

+0

我飛遍世界各地去參加會議,但我還沒有去過非洲。聯繫我參加一個會議的最好方法是發郵件到[email protected]。這樣你就能比我更好地瞭解那些瞭解我的旅行/會議議程的人。 –

+0

當然,我會寫信給你,很快兄弟。我很感激。 – kobewarui