如何居中对齐PdfPCell中的模板元素

Dav*_*Sav 6 android itext

我正在建立一个月份的垂直列表,每个月都有一个水平的天数列表.每天我都会添加一个大小有色的矩形; 大小和颜色取决于db查询的值.

我正在使用PdfPTable,PdfPCellcbCreateTemplate此答案中提供

除了矩形的位置之外,其他所有工作都很好(矩形的大小,矩形的颜色):它总是位于0,0,即使我(想)我已经设置了V&H定位.下面是代码的摘录; 请指教.

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);
Run Code Online (Sandbox Code Playgroud)

这是显示的图形: 应该对齐中心/中心

它应该是中心/中心.我哪里出错了?

这是使用已接受的解决方案的更新代码部分:

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);
Run Code Online (Sandbox Code Playgroud)

Bru*_*gie 11

你正在混合text modecomposite mode.

PdfPCell仅在文本模式下在工作级别上设置对齐属性.一旦切换到复合模式(通过使用该addElement()方法执行此操作),iText将忽略为单元格定义的对齐,以支持为单元格内容定义的对齐.

在文本模式下,所有内容都具有相同的对齐方式.在复合模式下,您可以使用不同的对齐方式.

您有不同的选项:您可以放入Chunka Paragraph并定义段落的对齐方式而不是单元格.您可以使用Phrase包含Chunk的文本模式创建单元格.甚至可以创建一个Image不使用Chunk等的单元格......

这一点在我写的"iText in Action"一书中有所解释.