我可以在PdfPcell对象的左侧放置一些文本,在同一个单元格的右侧放置一些其他文本吗?

时间:2014-05-14 14:56:11

标签: c# pdf pdf-generation itextsharp itext

我正在使用iTextSharp在我的PDF页脚中创建一个圆角桌。

我可以通过以下代码来完成:

PdfPTable tabFot = new PdfPTable(new float[] { 1F });
tabFot.TotalWidth = 300F;

tabFot.DefaultCell.Border = PdfPCell.NO_BORDER;
tabFot.DefaultCell.CellEvent = new RoundedBorder();

tabFot.AddCell("Footer");

这是我的RoundBorder类的代码:

class RoundedBorder : IPdfPCellEvent
{
    public void CellLayout(PdfPCell cell, iTextSharp.text.Rectangle rect, PdfContentByte[] canvas)
    {
        /* PdfContentByte is an object containing the user positioned text and graphic contents of a page. 
         * It knows how to apply the proper font encoding
         */
        PdfContentByte cb = canvas[PdfPTable.BACKGROUNDCANVAS];

        // Adds a round rectangle to the current path: roundRectangle(float x, float y, float w, float h, float r) 
        cb.RoundRectangle(
          rect.Left + 1.5f,         // x: x-coordinate of the starting point
          rect.Bottom + 1.5f,       // y: y-coordinate of the starting point
          rect.Width - 3,           // w: width
          rect.Height - 3,          // h: height
          4                         // r: radius of the arc corner
        );
        cb.Stroke();
    }
}

这项工作很好,我得到以下结果:

enter image description here

正如你所看到的,我获得了字符串" Footer"出现在单元格的左侧(根据常见行为的要求)

我的问题是我想要类似下面的例子:

enter image description here

如你所见,我想在左边有一些信息文本,在我的单元格右边有一些其他文字(页码)。

我可以用某种方式吗?

我推断我将 PdfPCell 对象传递给我的 CellLayout()方法,并且我可以将文本放入此单元格中执行CellLayout()。但是我该怎样做才能在单元格左侧放置一些文本,在右边放置一些其他文本?

或者,我可以将所有文本放在单元格的中心吗?

TNX

1 个答案:

答案 0 :(得分:1)

这是两个问题合二为一;;)

第一个问题:您希望文本位于左侧,文本位于右侧。这可以这样做:

Phrase phrase = new Phrase();
phrase.add(new Chunk("Left"));
phrase.add(new Chunk(new VerticalPositionMark()));
phrase.add(new Chunk("Right"));
PdfPCell cell = new PdfPCell(phrase);

诀窍是我们添加new Chunk(new VerticalPositionMark())

第二个问题:您希望将内容集中在一个单元格中。

这很棘手,因为有两种不同的模式:文本模式复合模式。

在文本模式下,您可以在单元格级别设置对齐:

cell.setHorizontalAlignment(Element.ALIGN_CENTER);

在你的情况下:

tabFot.DefaultCell.setHorizontalAlignment(Element.ALIGN_CENTER);

在复合模式下,您可以将对齐设置为要添加的内容级别。