看看下面的屏幕截圖:
第一個單元格顯示您所描述的問題。第二行通過更改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;
}