2015-04-02 113 views
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在端(不作爲其構造)繪製順序。

來看我的調試 - 它看起來對我來說,單元格的背景顏色設置後正在畫的漸變填充,有效地覆蓋它。

有沒有人有關於如何做到這一點的任何想法?也許我不應該用桌子來達到這個目的?

我已經看到了一些其他的職位,建議使用一個表單字段是要走的路。我想如果可能避免這一點,但如果這是唯一的出路......

回答

1

你的背景顏色是越來越繪製,不幸的是它正在繪製漸變背景這就是爲什麼你不能看到它「下的」。只要你只嵌套這兩個表格,最簡單的解決方案可能就是在PdfPTable.BASECANVAS上繪製梯度而不是PdfPTable.BACKGROUNDCANVAS

+0

非常符合我的想法。我會給你建議去的。 – 2015-04-06 23:47:04

+0

不好。更改爲PdfPTable.BASECANVAS後,漸變完全不顯示。 – 2015-04-15 02:52:25

相關問題