右键将部分块与iTextSharp对齐

dan*_*elu 2 c# itextsharp

我是iTextSharp的新手,我正在尝试创建PDF.只是一个简单的例子.如果我做这样的事情:

Paragraph p = new Paragraph();

p.Add(new Chunk("789456|Test", f5));
newDocument.Add(p);
p.Add(new Chunk("456|Test", f5));
newDocument.Add(p);
p.Add(new Chunk("12345|Test", f5));
newDocument.Add(p);
Run Code Online (Sandbox Code Playgroud)

我得到这个结果:

789456|Test
456|Test
12345|Test
Run Code Online (Sandbox Code Playgroud)

我该怎么做才能正确对齐我的块中的部分文本.像这样:

789456|Test
   456|Test
 12345|Test
Run Code Online (Sandbox Code Playgroud)

提前致谢.

Bru*_*gie 5

请看下面的例子:第4章.他们介绍了一个概念PdfPTable.而不是Chunk像这样创建对象"789456|Test",然后不可能让这些内容的各个部分Chunk正确对齐,你会发现创建一个简单PdfPTable的2列,添加"789456|""Test"作为无边框单元格的内容要容易得多.所有其他解决方法将不可避免地导致代码更复杂且容易出错.

卡尔安德森提供的答案要复杂得多; Manish Sharma提供的答案是错误的.虽然我不知道C#,但我试图写一个例子(基于我将如何在Java中实现这一点):

PdfPTable table = new PdfPTable(2);
table.DefaultCell.Border = PdfPCell.NO_BORDER;
table.DefaultCell.VerticalAlignment = Element.ALIGN_RIGHT;
table.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT;
table.addCell(new Phrase("789456|", f5));
table.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
table.addCell(new Phrase("Test", f5));
table.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT;
table.addCell(new Phrase("456|", f5));
table.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
table.addCell(new Phrase("Test", f5));
table.DefaultCell.HorizontalAlignment = Element.ALIGN_RIGHT;
table.addCell(new Phrase("12345|", f5));
table.DefaultCell.HorizontalAlignment = Element.ALIGN_LEFT;
table.addCell(new Phrase("Test", f5));
doc.Add(table);
Run Code Online (Sandbox Code Playgroud)

请注意,表的默认宽度是可用宽度的80%(边距之间的水平间距),默认情况下表是中心对齐的.您可能希望使用WidthPercentage和更改这些默认值HorizontalAlignment