我想在一行上向左侧和右侧显示两段内容(可能是段落或文字)。我的输出应该像
Name:ABC date:2015-03-02
我该怎么做?
答案 0 :(得分:11)
请查看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"
。
解决方案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"
,{{1}}如果你证明这条线的合理性,{{1}}会向中间移动,那么它将无法工作。
答案 1 :(得分:0)
我这样做是为了工作及其工作
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);