[英]iText: set cell height during CellEvent
我正在使用iText创建带有表的PDF。 表格标题具有90度旋转文本,我使用CellEvent(下面的代码)添加了这些文本。 这很好用,除非表跨越多个页面,否则旋转的单元格标题文本将从页面顶部流出。
我尝试设置cell.setFixedHeight(100),但它似乎并不影响该单元格。 我也尝试过这种解决方案 ,但是我根本无法使单元格完全显示带有文本的图像。
@Override
public void cellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases) {
PdfContentByte canvas = canvases[PdfPTable.TEXTCANVAS];
try {
canvas.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.WINANSI, false), this.fontSize);
} catch (DocumentException | IOException e) {
e.printStackTrace();
}
if (this.alignment == PdfPCell.ALIGN_CENTER) {
this.left = ((position.getRight() - position.getLeft()) / 2 );
}
else if (this.alignment == PdfPCell.ALIGN_MIDDLE) {
this.top = ((position.getTop() - position.getBottom()) / 2 );
}
canvas.showTextAligned(this.alignment, this.text, position.getLeft() + this.left, position.getTop() - this.top, this.rotation);
}
这是单元头溢出的样子。 在此示例中,应显示月份和年份(2016年3月)。
我希望单元格的高度取决于所使用的实际标题文本。 关于如何解决这个问题的任何想法?
绘制单元格后触发一个单元格事件。 您可能已经怀疑iText会将带有position
的Rectangle
对象传递给cellLayout
方法。 传递了PdfPCell
对象,但该对象仅用于只读目的。 由于position
是固定的,因此不能在其上使用setFixedHeight()
。
看着屏幕快照,我感到困惑:为什么要使用单元事件添加旋转90度的内容? 解决您的问题的方法是使用setRotation()
方法:
PdfPCell cell = new PdfPCell(new Phrase("May 16, 2016"));
cell.setRotation(90);
现在将旋转内容,并且单元格的大小将适应该内容。 请看RotatedCell示例:
public void createPdf(String dest) throws IOException, DocumentException {
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(dest));
document.open();
PdfPTable table = new PdfPTable(8);
for (int i = 0; i < 8; i++) {
PdfPCell cell =
new PdfPCell(new Phrase(String.format("May %s, 2016", i + 15)));
cell.setRotation(90);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
table.addCell(cell);
}
for(int i = 0; i < 16; i++){
table.addCell("hi");
}
document.add(table);
document.close();
}
结果看起来像这样: rotation_cell.pdf
注意,将水平和垂直概念旋转到。 如果要水平旋转的内容居中,则必须使内容的垂直对齐方式居中并旋转对齐的内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.