如何在同一行左右对齐两个段落?

我想在一行上向左侧和右侧显示两段内容(可能是段落或文本)。 我的输出应该是这样的

Name:ABC date:2015-03-02 

我怎样才能做到这一点?

请看一下LeftRight示例。 它为您的问题提供两种不同的解决方案:

在此处输入图像描述

解决方案1:使用胶水

通过粘合,我的意思是一个特殊的Chunk ,它像一个分隔两个(或更多)其他Chunk对象的分隔符:

 Chunk glue = new Chunk(new VerticalPositionMark()); Paragraph p = new Paragraph("Text to the left"); p.add(new Chunk(glue)); p.add("Text to the right"); document.add(p); 

这样,您将"Text to the left" "Text to the right"右侧"Text to the right"

解决方案2:使用PdfPTable

假设有一天,有人要求你把东西放在中间,那么使用PdfPTable是最具前瞻性的解决方案:

 PdfPTable table = new PdfPTable(3); table.setWidthPercentage(100); table.addCell(getCell("Text to the left", PdfPCell.ALIGN_LEFT)); table.addCell(getCell("Text in the middle", PdfPCell.ALIGN_CENTER)); table.addCell(getCell("Text to the right", PdfPCell.ALIGN_RIGHT)); document.add(table); 

在你的情况下,你只需要左边的东西和右边的东西,所以你需要创建一个只有两列的表: table = new PdfPTable(2)

如果你徘徊getCell()方法,这就是它的样子:

 public PdfPCell getCell(String text, int alignment) { PdfPCell cell = new PdfPCell(new Phrase(text)); cell.setPadding(0); cell.setHorizontalAlignment(alignment); cell.setBorder(PdfPCell.NO_BORDER); return cell; } 

解决方案3:对齐文本

这个问题的答案解释了这一点: 使用iTextSharp文本的合理性如何?

但是,只要字符串中有空格,这将导致奇怪的结果。 例如:如果您有"Name:ABC" ,它将起作用。 如果你有"Name: Bruno Lowagie"作为"Bruno"并且"Lowagie"将向中间移动,如果你certificate这条线的合理性,它将无法工作。