0
我有两个表。外表是用于绘制渐变背景的单列/单元包装。然后,我添加一个嵌套/子表,这是一个单行,并有三个单元格。如何在使用iTextSharp时设置嵌套单元格的背景颜色?
// set up wrapper table
var wrapperTable = new PdfPTable(1);
wrapperTable .WidthPercentage = 100;
// set up wrapper cell
var wrapperCell = new PdfPCell();
wrapperCell.CellEvent = new GradientBackgroundEvent(writer); // set gradient background
wrapperCell.Border = PdfPCell.NO_BORDER;
// setup nested table
var nestedTable = new PdfPTable(3);
nestedTable.WidthPercentage = 100;
nestedTable.SetWidths(new float[] { 15f, 70f, 15f });
var col1 = new PdfPCell(new Phrase(myText1, font));
col1.VerticalAlignment = Element.ALIGN_TOP;
col1.HorizontalAlignment = Element.ALIGN_CENTER;
col1.Border = PdfPCell.NO_BORDER;
nestedTable.AddCell(col1);
// this is the cell that I'm interested in - borders work, but no bgcolor
var col2 = new PdfPCell(new Phrase(myText2, font));
col2.VerticalAlignment = Element.ALIGN_TOP;
col2.HorizontalAlignment = Element.ALIGN_LEFT;
col2.BackgroundColor = BaseColor.WHITE;
col2.BorderColor = new BaseColor(204, 204, 204);
col2.BorderWidth = 0.2f;
nestedTable.AddCell(col2);
var col3 = new PdfPCell(new Phrase(myText3, font));
col3.VerticalAlignment = Element.ALIGN_TOP;
col3.HorizontalAlignment = Element.ALIGN_CENTER;
col3.Border = PdfPCell.NO_BORDER;
nestedTable.AddCell(col3);
// add nested table to the wrapper table
wrapperCell.AddElement(nestedTable);
我可以设置这些单元格的边框并且它们可以正确绘制。然而,我没有尝试过(除去渐变背景之后),我可以看到我在嵌套表格中的单元格上设置的背景颜色。
这是我的代码来做渐变填充。
public class GradientBackgroundEvent : IPdfPCellEvent
{
private PdfWriter w;
public GradientBackgroundEvent(PdfWriter w)
{
this.w = w;
}
public void CellLayout(PdfPCell cell, Rectangle position, PdfContentByte[] canvases)
{
var c1 = new BaseColor(238, 238, 238);
var c2 = new BaseColor(221, 221, 221);
PdfShading shading = PdfShading.SimpleAxial(w, position.Left, position.Top, position.Left, position.Bottom, c1, c2);
PdfShadingPattern pattern = new PdfShadingPattern(shading);
ShadingColor color = new ShadingColor(pattern);
PdfContentByte cb = canvases[PdfPTable.BACKGROUNDCANVAS];
position.BackgroundColor = color;
// Fill the rectangle
cb.Rectangle(position);
}
}
我试图走动代码和改变,其中表/细胞加入但没有差别,因为PDF在端(不作为其构造)绘制顺序。
来看我的调试 - 它看起来对我来说,单元格的背景颜色设置后正在画的渐变填充,有效地覆盖它。
有没有人有关于如何做到这一点的任何想法?也许我不应该用桌子来达到这个目的?
我已经看到了一些其他的职位,建议使用一个表单字段是要走的路。我想如果可能避免这一点,但如果这是唯一的出路......
非常符合我的想法。我会给你建议去的。 – 2015-04-06 23:47:04
不好。更改为PdfPTable.BASECANVAS后,渐变完全不显示。 – 2015-04-15 02:52:25