我可以使用 iText PDF 向生成的 PDF 添加单行页脚,但我需要添加多行页脚。
我试过用 Java 的换行符 (\n
) 连接两个字符串,但没有成功(参见代码 #1)。此外,已尝试通过 PdfPageEventHelper
类的 onEndPage
方法的 float x, float y
参数设置多行页脚。也不起作用(参见代码 #2)。
到目前为止,这是我尝试过的:
代码#1
Phrase phrase = new Phrase("line1" + "\n" + "line2", fontNormal10);
ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_LEFT, phrase, 40, 30, 0);
代码#2
Phrase phrase = new Phrase("line1", fontNormal10);
ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_LEFT, phrase, 40, 30, 0);
Phrase phrase2 = new Phrase("line2", fontNormal10);
ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_LEFT, phrase2, 40, 0, 0);
最佳答案
您正在使用 ColumnText.showTextAligned()
。这是一种可以用来添加单行文本的方法。您不应该期望它能用于添加多行文本。
如果要添加多行,则必须定义一个Rectangle
,并且必须使用ColumnText
来添加该矩形内的内容。这(当然)在官方文档中有解释,更具体地在 Absolute positioning of text (iText 5) 部分在哪里可以找到问题 How to add text inside a rectangle?
该问题的答案中的代码是 C# 代码,但很容易将其转换为 Java:
Rectangle rect = new Rectangle(x1, y1, x2, y2);
ColumnText ct = new ColumnText(writer.getDirectContent());
ct.SetSimpleColumn(rect);
ct.addElement(new Paragraph("This is the text added in the rectangle"));
ct.go();
定义x1
、y1
、x2
和y2
的值,使得所有文本适合矩形(不适合的文本将被忽略),并且位于页面底部。
关于java - iText PDF - 如何添加多行页脚?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45811500/