当使用Table和Cell类在iText 7中创建表格时,默认情况下,表格单元带有一些内置的填充。据我看生成的文档可以看出,它看起来大约是2个PDF单位。
有什么方法可以检索此值以供计算使用?另外,是否有任何方法可以更改此默认设置,以便可以将自己的填充设置为在所有表的所有单元格中使用,而不必在每个单元格上单独进行设置?
请查看iText 7:Building Blocks教程。
在“开始之前”部分中,我们看到每个构建基块都是从名为的类派生的ElementPropertyContainer
。此类是属性的容器。
对于Cell
类,有一组定义填充的属性。您可以通过以下通用方式(使用AbstractElement
类的方法)获取这些属性:
System.out.println(cell.getProperty(Property.PADDING_LEFT));
System.out.println(cell.getProperty(Property.PADDING_RIGHT));
System.out.println(cell.getProperty(Property.PADDING_TOP));
System.out.println(cell.getProperty(Property.PADDING_BOTTOM));
但是,如果您还可以简单地使用BlockElement
该类中提供的便捷方法,那么为什么会变得困难:
System.out.println(cell.getPaddingLeft());
System.out.println(cell.getPaddingRight());
System.out.println(cell.getPaddingTop());
System.out.println(cell.getPaddingBottom());
如您在本教程中所看到的,Cell
该类是该类的子BlockElement
类。该BlockElement
是的子类AbstractElement
类。该AbstractElement
班是一个子ElementPropertyContainer
类。
如果要更改填充(或倾斜的边距),请阅读该教程的第5章。它有一个名为CellMarginPadding的示例:
public void createPdf(String dest) throws IOException {
PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
Document document = new Document(pdf);
Table table = new Table(new float[]{2, 1, 1});
table.setBackgroundColor(Color.ORANGE);
table.setWidthPercent(80);
table.setHorizontalAlignment(HorizontalAlignment.CENTER);
table.addCell(
new Cell(1, 3).add("Cell with colspan 3")
.setPadding(10).setMargin(5).setBackgroundColor(Color.GREEN));
table.addCell(new Cell(2, 1).add("Cell with rowspan 2")
.setMarginTop(5).setMarginBottom(5).setPaddingLeft(30)
.setFontColor(Color.WHITE).setBackgroundColor(Color.BLUE));
table.addCell(new Cell().add("row 1; cell 1")
.setFontColor(Color.WHITE).setBackgroundColor(Color.RED));
table.addCell(new Cell().add("row 1; cell 2"));
table.addCell(new Cell().add("row 2; cell 1").setMargin(10)
.setFontColor(Color.WHITE).setBackgroundColor(Color.RED));
table.addCell(new Cell().add("row 2; cell 2").setPadding(10)
.setFontColor(Color.WHITE).setBackgroundColor(Color.RED));
document.add(table);
document.close();
}
看起来是这样的:
很抱歉,如果它有点伤眼睛,但是使用这些颜色似乎是向我解释边距和填充之间的区别的最佳方法。
大多数属性都是继承的。例如:如果您为设置了字体Div
,则该字体将是添加到该字体的所有元素的默认字体Div
。虽然有一些例外。填充是其中之一。这是Cell
定义类特定属性的默认值的方式:
@Override
public <T1> T1 getDefaultProperty(int property) {
switch (property) {
case Property.BORDER:
return (T1) (Object) DEFAULT_BORDER;
case Property.PADDING_BOTTOM:
case Property.PADDING_LEFT:
case Property.PADDING_RIGHT:
case Property.PADDING_TOP:
return (T1) (Object) 2f;
default:
return super.<T1>getDefaultProperty(property);
}
}
如您所见,整个单元格没有填充值。填充由默认情况下相同的四个值组成。
如果您不愿意为每个填充定义不同于默认的填充Cell
,只需创建一个子类Cell
并对其进行调用MyCustomCell
。从某种意义上说,使它自定义是通过覆盖getDefaultProperty()
类来使用您选择的填充。
在本教程中,您将找到一个子类示例,该子类绘制带有圆角边界的单元格,这样我们就不必在每次要引入圆角时都设置声明渲染器。
我是该文档的原始作者。我希望您发现回答有关Cell
iText 7中的和其他对象的这些和其他问题很有用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句