2016-06-13 88 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