Itext 将文本放置在带有 arial 粗体和一些颜色的特定位置

Itext place text in particular position with arial bold and some color

我需要使用带有颜色的粗体 Arial 字体并将文本放在特定位置,

Font name = FontFactory.getFont("file/ResumeBuilder/arial.tiff", 22, Font.BOLD,new CMYKColor(0, 0, 0, 175));
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("helloWorld.pdf"));
document.open();
Paragraph paragraph = new Paragraph("Add in PDF document", name);
document.add(paragraph);

我尝试使用段落,但通过使用段落,我不确定如何将文本放置在特定位置或者是否有更好的方法来实现。

我假设你指的是 iText 版本 5。5.x(特别是因为在 iText 7.x 中任务变得微不足道)。

此外,我假设您的意思是添加一小段文本而不需要换行。

在这种情况下,请查看 iText 示例 FoobarFilmFestival。关键代码:

Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
document.open();
String foobar = "Foobar Film Festival";
...
Font times = new Font(bf_times, 12);
...
PdfContentByte canvas = writer.getDirectContent();
...
Phrase phrase = new Phrase(foobar, times);
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase, 200, 572, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_RIGHT, phrase, 200, 536, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, phrase, 200, 500, 0);
ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, phrase, 200, 464, 30);
ColumnText.showTextAligned(canvas, Element.ALIGN_CENTER, phrase, 200, 428, -30);
document.close();

ColumnText.showTextAligned 允许您以给定的对齐方式和角度在给定的位置自由放置文本行。


如果您的意思是添加一段较长的需要换行的文本,请查看 iText 示例 MovieCalendar。关键代码:

Rectangle rect = getPosition(screening);
ColumnText column = new ColumnText(directcontent);
column.setSimpleColumn(new Phrase(screening.getMovie().getMovieTitle()),
        rect.getLeft(), rect.getBottom(),
        rect.getRight(), rect.getTop(), 18, Element.ALIGN_CENTER);
column.go();

此代码在矩形 rect 中绘制 Phrase,必要时应用换行符。