将Chunk的一部分与iTextSharp右对齐

本文关键字:iTextSharp 右对齐 一部分 Chunk | 更新日期: 2023-09-27 18:26:36

我是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);

我得到这个结果:

789456|Test
456|Test
12345|Test

我可以做些什么来对我的区块中的部分文本进行右对齐。像这样:

789456|Test
   456|Test
 12345|Test

提前谢谢。

将Chunk的一部分与iTextSharp右对齐

请看下面的例子:第4章。他们引入了CCD_ 1的概念。与创建像"789456|Test"这样的Chunk对象,然后不可能使这些Chunk内容的单独部分正确对齐相比,您会发现创建一个具有2列的简单PdfPTable要容易得多,添加"789456|""Test"作为无边界单元格的内容。所有其他解决方案都将不可避免地导致代码变得更加复杂和容易出错。

卡尔·安德森给出的答案要复杂得多;马尼什·夏尔马给出的答案是错误的。虽然我不知道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);

请注意,表格的默认宽度是可用宽度(页边距之间的水平空间)的80%,并且默认情况下表格居中对齐。您可能需要使用WidthPercentageHorizontalAlignment 来更改这些默认值

不幸的是,您只能将对齐应用于PdfPTable0对象,而不能应用于Chunk对象,因此您需要使用使用列的页面布局。

阅读iTextSharp-带列的页面布局,了解如何使布局更接近您的要求。

试试这个,这是您的示例代码。

private void CreatePdf()
{
        using (FileStream msReport = new FileStream(Server.MapPath("~") + "/App_Data/" + DateTime.Now.Ticks + ".pdf", FileMode.Create))
        {
            Document doc = new Document(PageSize.LETTER, 10, 10, 20, 10);
            PdfWriter pdfWriter = PdfWriter.GetInstance(doc, msReport);
            doc.Open();
            PdfPTable pt = new PdfPTable(1);
            PdfPCell _cell;
            _cell = new PdfPCell(new Phrase("789456|Test"));
            _cell.VerticalAlignment = Element.ALIGN_RIGHT;
            _cell.HorizontalAlignment = Element.ALIGN_RIGHT;
            _cell.Border = 0;
            pt.AddCell(_cell);
            _cell = new PdfPCell(new Phrase("456|Test"));
            _cell.VerticalAlignment = Element.ALIGN_RIGHT;
            _cell.HorizontalAlignment = Element.ALIGN_RIGHT;
            _cell.Border = 0;
            pt.AddCell(_cell);
            _cell = new PdfPCell(new Phrase("12345|Test"));
            _cell.VerticalAlignment = Element.ALIGN_RIGHT;
            _cell.HorizontalAlignment = Element.ALIGN_RIGHT;
            _cell.Border = 0;
            pt.AddCell(_cell);
            doc.Open();
            doc.Add(pt);
            doc.Close();
      }
}