我正在尝试将段落对齐设置为右对齐。
这是我尝试过的,没有任何结果:
Paragraph paragraph1 = new Paragraph(str1);
paragraph1.setHorizontalAlignment(HorizontalAlignment.RIGHT);
document.add(paragraph1);
我已经找到了很多 examples ,但它们似乎都处理表格中的单元格。就我而言,这只是一个段落。
最佳答案
请尝试 setTextAlignment 方法:
Paragraph paragraph1 = new Paragraph(str1);
paragraph1.setTextAlignment(TextAlignment.RIGHT);
document.add(paragraph1);
值得一提的是,setHorizontalAlignment 和 setTextAlignment 方法具有不同的目标。前者是关于放置段落本身(作为一个元素),后者是关于放置其内容。
要查看差异,可以设置段落的宽度并将该段落添加到 div 元素。
我创建了一个小测试来演示它:
PdfDocument pdfDocument = new PdfDocument(new PdfWriter(outFileName));
Document document = new Document(pdfDocument);
Div div = new Div()
.setWidth(500)
.setBackgroundColor(ColorConstants.YELLOW);
Paragraph paragraph = new Paragraph("Hello World!")
.setTextAlignment(TextAlignment.CENTER)
.setHorizontalAlignment(HorizontalAlignment.RIGHT)
.setWidth(300)
.setBackgroundColor(ColorConstants.BLUE);
div.add(paragraph);
document.add(div);
如您所见,我在这里创建了一个段落,其水平对齐设置为右对齐,文本对齐设置为居中。
关于java - 在 iText 中水平对齐段落,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54088539/