我有一张桌子,我想把它的标题行设为灰色。 我尝试了下面的方法,但它将整个表格视为灰色
PdfPTable table1 = new PdfPTable(4);
table1.SetTotalWidth(new float[] { 50f,80f,50f,330f });
table1.TotalWidth = 800f;//table size
table1.LockedWidth = true;
table1.HorizontalAlignment = 0;
table1.SpacingBefore = 5f;//both are used to mention the space from heading
table1.SpacingAfter = 5f;
table1.DefaultCell.BackgroundColor = BaseColor.LIGHT_GRAY;
table1.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
table1.AddCell(new Phrase("NO", time515));
table1.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
table1.AddCell(new Phrase("Date & Day", time515));
table1.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
table1.AddCell(new Phrase("Hr", time515));
table1.DefaultCell.HorizontalAlignment = Element.ALIGN_CENTER;
table1.AddCell(new Phrase("Topics to be Covered", time515));
Doc.add(table1);
答案 0 :(得分:2)
你有几个选择。如果您只是想在需要时更改给定行的背景颜色,您可以这样做。下面的代码将写入十行四个单元格,第一行为灰色,其余行为蓝色。
for (var i = 0; i < 10; i++) {
if (i == 0) {
table1.DefaultCell.BackgroundColor = BaseColor.LIGHT_GRAY;
}
else {
table1.DefaultCell.BackgroundColor = BaseColor.BLUE;
}
table1.AddCell(new Phrase("NO"));
table1.AddCell(new Phrase("Date & Day"));
table1.AddCell(new Phrase("Hr"));
table1.AddCell(new Phrase("Topics to be Covered"));
}
然而,iText中的表实际上支持更具体的概念&#34; Headers&#34;并且您只需通过告诉PdfPTable
应该将多少行视为&#34;标题&#34;来声明这些:
table1.HeaderRows = 1;
关于这一点的简洁之处在于,如果您的桌子实际跨越多个页面,那么您的标题将自动在下一页上重新绘制。但是,使用此方法还需要执行一些额外的工作。 iText为您实现了一个名为IPdfPTableEvent
的名为TableLayout
的公开和界面,它有一个名为private class MyTableEvent : IPdfPTableEvent {
public void TableLayout(PdfPTable table, float[][] widths, float[] heights, int headerRows, int rowStart, PdfContentByte[] canvases) {
//Loop through each header row
for( var row = 0; row < headerRows; row++ ){
//Loop through each column in the current row
//NOTE: For n columns there's actually n+1 entries in the widths array.
for( var col = 0; col < widths[row].Length - 1; col++ ){
//Get the various coordinates
var llx = widths[row][col];
var lly = heights[row];
var urx = widths[row][col + 1];
var ury = heights[row + 1];
//Create a rectangle
var rect = new iTextSharp.text.Rectangle(llx, lly, urx, ury);
//Set whatever properties you want on it
rect.BackgroundColor = BaseColor.PINK;
//Draw it to the background canvas
canvases[PdfPTable.BACKGROUNDCANVAS].Rectangle(rect);
}
}
}
}
的方法。下面是一个完整的实现示例,请参阅代码注释以获取更多详细信息:
table1.TableEvent = new MyTableEvent();
要使用它,只需将实例绑定到表对象:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("window-size=1,1")
driver = webdriver.Chrome(chrome_options=chrome_options)