2012-09-24 50 views
5

我正在用月份的水平天數列表構建月份的垂直列表。每天我都會添加一個尺寸和顏色的矩形;大小和顏色取決於數據庫查詢的值。如何在PdfPCell中居中對齊模板元素

我正在使用其他this answer

一切提供PdfPTablePdfPCellcbCreateTemplate工作正常(矩形,矩形的顏色的大小),除了矩形的位置:它總是定位在0,0即使我(想)我已經設置了V的定位。代碼摘錄如下;請指教。

int Severity = args.getPLR().get(i).getItems().get(j).getItems().get(itemIndex).getSeverity(); 
Severity = Severity + 5; //plump up, so that max (10) should fill the cell 
PdfPCell cell = new PdfPCell(); 
cell.setPadding(0); 
template = cb.createTemplate(Severity, Severity); 
template.setLineWidth(0.5f); 
template.rectangle(0, 0, Severity, Severity); 
//we should switch the color 
//based on the Severity 
switch ((Severity-5)) { 
    case 0: 
     template.setColorFill(Color.GREEN); 
     break; 
    case 1: 
     template.setColorFill(Color.GREEN); 
     break; 
    case 2: 
     template.setColorFill(Color.YELLOW); 
     break; 
    case 3: 
     template.setColorFill(Color.YELLOW); 
     break; 
    case 4: 
     template.setColorFill(Color.YELLOW); 
     break; 
    case 5: 
     template.setColorFill(Color.ORANGE); 
     break; 
    case 6: 
     template.setColorFill(Color.ORANGE); 
     break; 
    case 7: 
     template.setColorFill(Color.ORANGE); 
     break; 
    case 8: 
     template.setColorFill(Color.RED); 
     break; 
    case 9: 
     template.setColorFill(Color.RED); 
     break; 
    case 10: 
     template.setColorFill(Color.RED); 
     break; 
} 
template.fill(); 
img = Image.getInstance(template);   
chunk = new Chunk(img, 0f, 0f); 
cell.addElement(chunk); 
cell.setHorizontalAlignment(Element.ALIGN_CENTER); 
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); 
painTable.addCell(cell); 

這是所顯示的圖形: should be aligned center/center

它應該是中心/中心。我哪裏錯了?

這是使用接受的解決方案更新的代碼部分:

img = Image.getInstance(template);   
chunk = new Chunk(img, 0f, 0f); 
Phrase severityChunk = new Phrase(chunk); 
PdfPCell cell = new PdfPCell(severityChunk); 
cell.setPadding(0); 
cell.setHorizontalAlignment(Element.ALIGN_CENTER); 
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); 
painTable.addCell(cell); 

回答

10

你混合text modecomposite mode

設置在PdfPCell級別上的對齊屬性僅在文本模式下工作。只要切換到複合模式(通過使用addElement()方法即可),iText將忽略爲單元格定義的對齊方式,以便爲單元格內容定義的對齊方式。

在文本模式下,所有內容具有相同的對齊方式。在複合模式下,可以使用不同的路線具有不同的元素。

您有不同的選擇:您可以將Chunk置於Paragraph中,併爲段落而不是單元格定義對齊方式。您可以使用包含該塊的Phrase以文本模式創建單元格。甚至可以用Image創建一個單元而不使用塊,等等......

這是在我寫的「iText in Action」一書中解釋的。

+0

謝謝布魯諾。我在單元解決方案中使用了短語,並在上面添加了更新後的代碼。 – DaveSav