简体   繁体   English

使用itext5将文本添加到PDF中的矩形

[英]Adding text to a rectangle in PDF using itext5

PdfContentByte canvas = writer.getDirectContent();
Rectangle rect = new Rectangle(0, 805, 594, 820);
rect.setBorder(Rectangle.BOX);
rect.setBorderWidth(1);
rect.setBackgroundColor(BaseColor.GRAY);
rect.setBorderColor(BaseColor.GREEN);

ColumnText ct = new ColumnText(canvas);
ct.setSimpleColumn(rect);
Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18,Font.BOLD);

ct.addElement(new Paragraph("Your Text Goes here!! ",catFont));
ct.go();
canvas.rectangle(rect);

document.newPage();
document.close();

This is my code, here I'm trying to add text in rectangle. 这是我的代码,在这里我试图在矩形中添加文本。 It didn't work! 没用! the rectangle is created but the text is not dispalyed anywhere on the pdf page. 将创建矩形,但不会在pdf页面上的任何地方显示文本。

There are a couple of issues with your code causing the text not to show. 您的代码有几个问题,导致文本无法显示。

Firstly, you add the rectangle to the canvas AFTER you add the text. 首先,在添加文本之后,将矩形添加到画布。 The gray background will go over any text that was drawn, hiding it. 灰色背景将覆盖所有绘制的文本,将其隐藏。

Secondly, your font size is too big for column boundary, so no text is shown. 其次,字体大小对于列边界而言太大,因此不会显示任何文本。 You can make your rectangle larger and the text will show or decrease the size of your font. 您可以将矩形变大,文本将显示或减小字体大小。

For example, the following should work as I have increased the rectangle height and moved the canvas.rectangle() call to before the ColumnText.go(): 例如,当我增加矩形的高度并将canvas.rectangle()调用移到ColumnText.go()之前,以下代码应该起作用:

Rectangle rect = new Rectangle(0, 780, 494, 820);
rect.setBorder(Rectangle.BOX);
rect.setBorderWidth(1);
rect.setBackgroundColor(BaseColor.GRAY);
rect.setBorderColor(BaseColor.GREEN);
canvas.rectangle(rect);

ColumnText ct = new ColumnText(canvas);
ct.setSimpleColumn(rect);
Font catFont = new Font(Font.FontFamily.TIMES_ROMAN, 18, Font.BOLD);
ct.addElement(new Paragraph("Your Text Goes here!! ", catFont));
ct.go();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM