I am trying to use Itext to output some strings to a PDF. Currently I can print them to the document but I would like to draw/write them to a specific (x,y) in the document. How would I go about this? Or is there any tutorial or resource that can help? Any info would be appreciated.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
If you are using iText 5, please go to the FAQ section conveniently titled as Absolute positioning of text
You'll find answers to questions such as How to write a Zapfdingbats character at a specific location on a page? In the answer to that question, we use ColumnText.showTextAligned()
:
Phrase phrase = new Phrase(zapfstring, font);
Where zapfstring
is a string containing any Zapfdingbats character you want and font
is a Font
object. Then we add it at an absolute position:
PdfContentByte canvas = writer.getDirectContent();
ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, phrase, x, y, 0);
If you want to add text inside a rectangle (text wraps if it doesn't fit the width), take a look at this question: How to add text inside a rectangle?
PdfContentByte canvas = writer.getDirectContent();
ColumnText ct = new ColumnText(canvas);
ct.setSimpleColumn(rect);
ct.addElement(new Paragraph("This is the text added in the rectangle"));
ct.go();
If you are using iText 7, use the setFixedPosition()
method, for instance on the Paragraph
object.