1 回答

TA貢獻1840條經驗 獲得超5個贊
如果您在創建表時這樣做,您可以通過欺騙來完成此操作。
我將提供一個部分解決方案,它利用 PDF 中的一個復雜性表:表只是 PDF 中的行。它們不是結構化內容。
您可以利用這一點 - 在渲染表格時跟蹤您正在繪制垂直線的位置,然后將它們繼續到頁面底部。
讓我們創建一個新的單元格事件。它跟蹤4件事:left哪個是表格最左邊的x坐標,right哪個是表格最右邊的x坐標,xCoordinates它是我們畫垂直線的所有x坐標的集合,最后cellHeights哪個是一個列表所有單元格高度。
class CellMarginEvent implements PdfPCellEvent {
Set<Float> xCoordinates = new HashSet<Float>();
Set<Float> cellHeights = new HashSet<Float>();
Float left = Float.MAX_VALUE;
Float right = Float.MIN_VALUE;
public void cellLayout(PdfPCell pdfPCell, Rectangle rectangle, PdfContentByte[] pdfContentBytes) {
this.xCoordinates.add(rectangle.getLeft());
this.xCoordinates.add(rectangle.getRight());
this.cellHeights.add(rectangle.getHeight());
left = Math.min(left,rectangle.getLeft());
right = Math.max(right, rectangle.getRight());
}
public Set<Float> getxCoordinates() {
return xCoordinates;
}
}
然后我們將所有單元格添加到表格中,但暫時不會將表格添加到文檔中
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(OUTPUT_FILE));
document.open();
PdfPTable table = new PdfPTable(4);
CellMarginEvent cellMarginEvent = new CellMarginEvent();
for (int aw = 0; aw < 320; aw++) {
PdfPCell cell = new PdfPCell();
cell.addElement(new Paragraph("Cell: " + aw));
cell.setCellEvent(cellMarginEvent);
table.addCell(cell);
}
不,我們添加 get top- 表格的頂部位置,并將表格添加到文檔中。
float top = writer.getVerticalPosition(false);
document.add(table);
然后我們繪制完成的表格的垂直和水平線。對于每個單元格的高度,我只使用了cellHeights.
Set<Float> xCoordinates = cellMarginEvent.getxCoordinates();
//Draw the column lines
PdfContentByte canvas = writer.getDirectContent();
for (Float x : xCoordinates) {
canvas.moveTo(x, top);
canvas.lineTo(x, 0 + document.bottomMargin());
canvas.closePathStroke();
}
Set<Float> cellHeights = cellMarginEvent.cellHeights;
Float cellHeight = (Float)cellHeights.toArray()[0];
float currentPosition = writer.getVerticalPosition(false);
//Draw the row lines
while (currentPosition >= document.bottomMargin()) {
canvas.moveTo(cellMarginEvent.left,currentPosition);
canvas.lineTo(cellMarginEvent.right,currentPosition);
canvas.closePathStroke();
currentPosition -= cellHeight;
}
最后關閉文檔:
document.close()
示例輸出:
請注意,我說這是一個不完整示例的唯一原因是因為您可能需要對top
標題單元格進行一些調整,或者您可能需要自定義單元格樣式(背景顏色、線條顏色等)為自己記賬。
我還會注意到我剛剛想到的另一個缺點 - 在標記的 PDF 的情況下,此解決方案無法添加標記的表格單元格,因此如果您有該要求,則會違反合規性。
添加回答
舉報