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

How to align two paragraphs to the left and right on the same line?

我想在一行的左右两侧显示两段内容(可能是一段或一段文字)。我的输出应该是

 Name:ABC                                                               date:2015-03-02

我该怎么做?

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

方案一:使用胶水

我所说的胶水是指一种特殊的 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"

解决方案 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: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: 对齐文本

这个问题的答案中有解释:How justify text using iTextSharp?

但是,一旦字符串中有空格,这将导致奇怪的结果。例如:如果您有 "Name:ABC",它将起作用。如果你有 "Name: Bruno Lowagie" 它将不起作用,因为 "Bruno""Lowagie" 将向中间移动,如果你对齐该行。

我这样做是为了工作和它的工作

            Document document = new Document(PageSize.A4, 30, 30, 100, 150);
            document.SetPageSize(iTextSharp.text.PageSize.A4);
            PdfWriter writer = PdfWriter.GetInstance(document, fs);
            writer.PageEvent = new ITextEvents();
            document.Open();
            iTextSharp.text.Font fntHead2 = new iTextSharp.text.Font(bfntHead, 11, 1, BaseColor.BLACK);
            Paragraph para = new Paragraph();
            Chunk glue = new Chunk(new VerticalPositionMark());
            Phrase ph1 = new Phrase();

            Paragraph main = new Paragraph();
            ph1.Add(new Chunk("Left Side", fntHead2)); 
            ph1.Add(glue); // Here I add special chunk to the same phrase.    
            ph1.Add(new Chunk("Right Side", fntHead2)); 
            para.Add(ph1);
            document.Add(para);