2016-05-16 96 views
1

我正在使用iText創建帶有表格的PDF。表頭有90度旋轉文本,我使用CellEvent(下面的代碼)添加。這個效果很好,除非表格跨越多個頁面,旋轉的單元格標題文本從頁面頂部流出。iText:在CellEvent期間設置單元格高度

我試過設置cell.setFixedHeight(100)但它似乎不影響單元格。我也嘗試過this solution,但是我無法讓單元格顯示帶有文本的結果圖像。

@Override 
public void cellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases) { 

    PdfContentByte canvas = canvases[PdfPTable.TEXTCANVAS]; 

    try { 
        canvas.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.WINANSI, false), this.fontSize); 
    } catch (DocumentException | IOException e) { 
     e.printStackTrace(); 
    } 

    if (this.alignment == PdfPCell.ALIGN_CENTER) { 
     this.left = ((position.getRight() - position.getLeft())/2); 
    } 
    else if (this.alignment == PdfPCell.ALIGN_MIDDLE) { 
     this.top = ((position.getTop() - position.getBottom())/2); 
    } 
    canvas.showTextAligned(this.alignment, this.text, position.getLeft() + this.left, position.getTop() - this.top, this.rotation); 
} 

下面是單元頭溢出的樣子。在這個例子中,它應該顯示月份和年份(2016年3月)。

enter image description here

我想有細胞依賴於所使用的實際標題文本任意高度。有關如何解決這個問題的任何想法?

回答

2

單元格事件觸發之後單元格被繪製。您可能已經懷疑這一點,因爲iText將positioncellLayout方法傳遞給Rectangle對象。 A PdfPCell對象已通過,但僅用於只讀目的。由於position已修復,因此您無法使用其上的setFixedHeight()

看着屏幕截圖,我很疑惑:爲什麼你使用單元格事件來添加旋轉90度的內容?你的問題的解決辦法是使用setRotation()方法:

PdfPCell cell = new PdfPCell(new Phrase("May 16, 2016")); 
cell.setRotation(90); 

現在的內容將被旋轉和單元格的大小將被改編的內容。請大家看看RotatedCell例如:

public void createPdf(String dest) throws IOException, DocumentException { 
    Document document = new Document(); 
    PdfWriter.getInstance(document, new FileOutputStream(dest)); 
    document.open(); 
    PdfPTable table = new PdfPTable(8); 
    for (int i = 0; i < 8; i++) { 
     PdfPCell cell = 
      new PdfPCell(new Phrase(String.format("May %s, 2016", i + 15))); 
     cell.setRotation(90); 
     cell.setVerticalAlignment(Element.ALIGN_MIDDLE); 
     table.addCell(cell); 
    } 
    for(int i = 0; i < 16; i++){ 
     table.addCell("hi"); 
    } 
    document.add(table); 
    document.close(); 
} 

結果看起來是這樣的:rotated_cell.pdf

​​

注意,概念水平和垂直旋轉來。如果您想要水平居中旋轉的內容,則必須居中對齊內容的垂直對齊並旋轉對齊的內容。

+0

這適用於90度增量旋轉,我會接受這個答案。由於需要任何文本角度,我正在使用CellEvent處理它,但我想我會看看90度旋轉是否適用於所有需求。謝謝! – JohnP

相關問題