.Text sharp PdfPTable PdfPCell对齐方式,边框,边框颜色的使用

PdfPTable和PdfPCell对象,我们可以制作出丰富多彩的表格,可以制作出跨行、跨列,不同表格线,单元格中的文字旋转等效果,如下所示:

1、文本模式:

PdfPCell cell = new PdfPCell(new Paragraph("some text"));

2、组合模式:

PdfPCell cell = new PdfPCell();                                        
cell.AddElement(new Paragraph("some text"));

这两种区别:

文本模式下,对于内容的对齐方式、间距、缩进使用的是单元格来属性进行控制,在组合模式下,使用对象自身的属性进行控制。

在表格中,对单元格的边框进行隐藏和设置颜色,

PdfPCell中有一个属性:Border  边框属性

此值使用如果下值进行设置:

   1: public class Rectangle : Element, IElement
   2:     {
   3:         public const int BOTTOM_BORDER = 2;
   4:         public const int BOX = 15;
   5:         public const int LEFT_BORDER = 4;
   6:         public const int NO_BORDER = 0;
   7:         public const int RIGHT_BORDER = 8;
   8:         public const int TOP_BORDER = 1;

并且可以组合使用,如:Rectangle.TOP_BORDER|Rectangle.LEFT_BORDER

不要通过设置BorderWidth=0来进行隐藏边框,这样会造成表格对不齐。

如下图所示:

image

第一行默认对齐左边框设置为宽度为0,明显看出右边没有对齐。

正常情况:

image

通过设置Boder隐藏边框:

代码如下:

   1: cell = CreateCell("默认对齐", useAscender, useDescender, null, null);
   2:             cell.Border = Rectangle.RIGHT_BORDER | Rectangle.TOP_BORDER | Rectangle.BOTTOM_BORDER;
   3:             //cell.UseBorderPadding = false;
   4:            // cell.BorderWidthLeft = 0;
   5:             //cell.BorderColorTop = BaseColor.BLUE;
   6:             //cell.BorderWidthTop = 1;
   7:            
   8:             table.AddCell(cell);

显示效果:

image

对于边框颜色设置,如果要对边框整个设置颜色,可以使用BoderColor进行,如果只对单独表格线设置颜色,就发使用BorderColorTop,BorderColorLeft等属性进行,并且要设置其宽度,否则颜色显示不出来。

代码:

   1: cell = CreateCell("默认对齐", useAscender, useDescender, null, null);
   2:             cell.Border = Rectangle.RIGHT_BORDER | Rectangle.TOP_BORDER | Rectangle.BOTTOM_BORDER;
   3:             cell.BorderColor = BaseColor.RED;            
   4:             cell.BorderColorTop = BaseColor.BLUE;
   5:             cell.BorderWidthTop = 0.5f;
   6:            
   7:             table.AddCell(cell);

显示效果:

image

更多请查看:一步一步 IText.Sharp

原文地址:https://www.cnblogs.com/LifelongLearning/p/2086802.html