Java itext Pdf 表格单元格中的居中文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19703715/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Centered text in itext Pdf table cell
提问by ErrorNotFoundException
I need to center the text inside a Pdf table cell. Unfortunately all the text is appearing at the Bottom of the cell. Here is my sample code:
我需要将文本居中放置在 Pdf 表格单元格中。不幸的是,所有文本都出现在单元格的底部。这是我的示例代码:
String line = br.readLine();
Font f2 = new Font(Font.NORMAL, 12, Font.BOLD);
f2.setColor(Color.BLACK);
Paragraph p1 = new Paragraph(line, f2);
p1.setAlignment(Element.TABLE);
PdfPTable table = new PdfPTable(1);
table.setWidthPercentage(100);
PdfPCell cell = new PdfPCell();
cell.setBorder(Rectangle.NO_BORDER);
cell.setBorderWidthBottom(1f);
cell.setUseBorderPadding(true);
cell.setPadding(0);
cell.setBorderColor(new java.awt.Color(255, 255, 255));
cell.addElement(p1);
table.addCell(cell);
output.add(table);
I need the text inside the cell centered vertically inside the cell. Please help.
我需要单元格内的文本在单元格内垂直居中。请帮忙。
采纳答案by Bruno Lowagie
There are several errors in the snippet you shared. I've adapted the code and posted an example here http://itextpdf.com/sandbox/tables/CenteredTextInCell(dead link, now https://github.com/itext/i5js-sandbox/blob/master/src/main/java/sandbox/tables/CenteredTextInCell.java)
您共享的代码段中有几个错误。我已经修改了代码并在此处发布了一个示例http://itextpdf.com/sandbox/tables/CenteredTextInCell(死链接,现在是https://github.com/itext/i5js-sandbox/blob/master/src/main /java/sandbox/tables/CenteredTextInCell.java)
Reduced overview of changes:
减少更改概述:
The way you define a font is wrong, or you're using a version of iText that is really, really old.
您定义字体的方式是错误的,或者您使用的 iText 版本确实非常老旧。
The following line doesn't really make sense:
以下行实际上没有意义:
p1.setAlignment(Element.TABLE);
There is no such value in iText (there used to be one, but it has been removed a really long time ago) and evenso it doesn't make sense to use a value reserved to define an object type as to define an alignment.
iText 中没有这样的值(曾经有一个,但很久以前它已经被删除了),即使如此,使用保留的值来定义对象类型来定义对齐是没有意义的。
If you don't want a border:
如果您不想要边框:
cell.setBorder(Rectangle.NO_BORDER);
It doesn't make sense to define border widths, padding or colors:
定义边框宽度、填充或颜色没有意义:
cell.setBorderWidthBottom(1f);
cell.setUseBorderPadding(true);
cell.setBorderColor(new java.awt.Color(255, 255, 255));
The line you need to define vertical alignment is:
您需要定义垂直对齐的行是:
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
回答by Michele Mariotti
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);