使用iTextSharp时,如何设置嵌套单元格的背景颜色?

时间:2015-04-02 00:51:42

标签: c# pdf pdf-generation 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是在最后绘制的(而不是它的构造)。

根据我的调试判断 - 在我看来,在设置单元格的背景颜色并有效覆盖它之后,正在绘制渐变填充。

有没有人对如何做到这一点有任何想法?也许我不应该使用表来实现这一目标?

我已经看到一些其他帖子建议使用表单字段是要走的路。如果可能的话,我想避免这种情况,但如果这是唯一的方法......

1 个答案:

答案 0 :(得分:1)

您的背景颜色正在被绘制,不幸的是它被绘制在渐变背景“下面”,这就是您无法看到它的原因。只要您只是嵌套这两个表,最简单的解决方案可能只是在PdfPTable.BASECANVAS而不是PdfPTable.BACKGROUNDCANVAS上绘制渐变。