【问题标题】:PDF Cell Vertical Alignment with com.lowagie.textPDF 单元格垂直对齐与 com.lowagie.text
【发布时间】:2014-12-01 12:23:02
【问题描述】:

我正在使用 com.lowagie.text 在我的代码中创建 PDF。除了我试图垂直对齐单元格内容外,一切正常。我希望单元格文本位于单元格高度的中间。

这是我的代码

PdfPCell cell = new PdfPCell(new Phrase(value, fontValueNew));
cell.setBorder(o);
cell.setBackgroundColor(new Color(233,232,232));
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);

在这里,水平对齐工作正常,但垂直对齐无效。

【问题讨论】:

标签: java pdf itext


【解决方案1】:

我不太确定为什么,但这对我有用(垂直居中对齐):

String headingLabel = "Test";

Paragraph heading = new Paragraph(headingLabel,
        new Font(helvetica, 28, Font.NORMAL, new BaseColor(0, 0, 0)));

Float textWidth = ColumnText.getWidth(heading);
Float maxAllowed = 630f;

while (maxAllowed < textWidth) {
    fontSize -= 2;
    heading = new Paragraph(headingLabel,
        new Font(helvetica, fontSize, Font.NORMAL, new BaseColor(0, 0, 0)));
    textWidth = ColumnText.getWidth(heading);
}

heading.setAlignment(Element.ALIGN_CENTER);

PdfPCell titleCell = new PdfPCell();
titleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
titleCell.setVerticalAlignment(Element.ALIGN_TOP);
titleCell.addElement(heading);
titleCell.setFixedHeight(65f);
headerTable.addCell(titleCell);

【讨论】:

    【解决方案2】:

    ALIGN_MIDDLE 具有在 iText 代码中定义的整数值 5。请注意在编写 ALIGN_MIDDLE 时会出现提示“垂直元素的可能值”。这意味着如果您的元素处于垂直方向,那么它将在计算元素的中心时起作用。我的建议是将 ALIGN_MIDDLE 替换为 ALIGN_CENTER,这样您的代码将如下所示:

    cell.setVerticalAlignment(Element.ALIGN_CENTER);
    

    【讨论】:

      【解决方案3】:

      试试这个:

      PdfPCell cell = new PdfPCell(new Phrase(value, fontValueNew));
      cell.setBorder(o);
      cell.setBackgroundColor(new Color(233,232,232));
      cell.setHorizontalAlignment(Element.ALIGN_LEFT);
      cell.setVerticalAlignment(Element.ALIGN_CENTER);
      

      【讨论】:

        猜你喜欢
        • 2011-07-30
        • 1970-01-01
        • 2018-08-15
        • 1970-01-01
        • 1970-01-01
        • 2013-04-03
        • 2014-08-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多