2016-11-15 93 views
0

我正在開發一個構建自定義PDF的Android應用程序,我使用了itext作爲庫支持,但是我對分隔符有很大的問題。如何減少LineSeparator itext中的行間距

分隔數據我用這個函數:

public void addSeparator(PdfPCell cellToAdd){ 
    LineSeparator ls = new LineSeparator(); 
    ls.setLineWidth(1); 
    cellToAdd.addElement(new Chunk(ls)); 
} 

cellToAdd是我需要添加LineSeparator細胞,結果的想法是:

my fantastic data 

----------------- 

Other data 

我需要增加線和數據之間的空間,但我不知道如何做到這一點。

回答

2

看看下面的屏幕截圖:

enter image description here

第一個單元格顯示您所描述的問題。第二行通過更改LineSeparator的屬性來解決此問題。如果這還不夠,您需要更改Paragraph實例。

這是創建全表的代碼:

public void createPdf(String dest) throws IOException, DocumentException { 
    Document document = new Document(); 
    PdfWriter.getInstance(document, new FileOutputStream(dest)); 
    document.open(); 
    PdfPTable table = new PdfPTable(1); 
    table.addCell(getCell1()); 
    table.addCell(getCell2()); 
    table.addCell(getCell3()); 
    table.addCell(getCell4()); 
    document.add(table); 
    document.close(); 
} 

的第一個單元格像這樣創建:

public PdfPCell getCell1() { 
    PdfPCell cell = new PdfPCell(); 
    Paragraph p1 = new Paragraph("My fantastic data"); 
    cell.addElement(p1); 
    LineSeparator ls = new LineSeparator(); 
    cell.addElement(ls); 
    Paragraph p2 = new Paragraph("Other data"); 
    cell.addElement(p2); 
    return cell; 
} 

我們只需要添加的LineSeparator和它堅持第一段。我們可以通過引入負避免這種偏差:

public PdfPCell getCell2() { 
    PdfPCell cell = new PdfPCell(); 
    Paragraph p1 = new Paragraph("My fantastic data"); 
    cell.addElement(p1); 
    LineSeparator ls = new LineSeparator(); 
    ls.setOffset(-4); 
    cell.addElement(ls); 
    Paragraph p2 = new Paragraph("Other data"); 
    cell.addElement(p2); 
    return cell; 
} 

如果需要更多的空間,我們可以增加第二款的領導,提高補償:

public PdfPCell getCell3() { 
    PdfPCell cell = new PdfPCell(); 
    Paragraph p1 = new Paragraph("My fantastic data"); 
    cell.addElement(p1); 
    LineSeparator ls = new LineSeparator(); 
    ls.setOffset(-8); 
    cell.addElement(ls); 
    Paragraph p2 = new Paragraph("Other data"); 
    p2.setLeading(25); 
    cell.addElement(p2); 
    return cell; 
} 

這可能是不能接受的,因爲如果其他數據由多於一行組成,則領導也將對後續行產生影響。

最好解決方案是使用setSpacingBefore()setSpacingAfter()(或兩者):

public PdfPCell getCell4() { 
    PdfPCell cell = new PdfPCell(); 
    Paragraph p1 = new Paragraph("My fantastic data"); 
    p1.setSpacingAfter(20); 
    cell.addElement(p1); 
    LineSeparator ls = new LineSeparator(); 
    cell.addElement(ls); 
    Paragraph p2 = new Paragraph("Other data"); 
    p2.setSpacingBefore(10); 
    cell.addElement(p2); 
    return cell; 
}