我想在一行的左侧和右侧显示两段内容(可能是段落或文本)。我的输出应该是这样的
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(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 = 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);