【问题标题】:Background Color of Table is not shown in iTextSharp PDFiTextSharp PDF 中未显示表格的背景颜色
【发布时间】:2015-11-19 14:02:50
【问题描述】:

我生成了一个 Table 对象,其中一些单元格具有背景色。此背景颜色是从数据库中动态加载的。

我在我的代码中使用以下几行设置了 BackColor:

TableCell tCell = new TableCell();
tCell.BackColor = (Color)converter.ConvertFromString(color_startBorderCrtColor);
tCell.Text = Convert.ToString(row[column.ColumnName]);
tRow.Cells.Add(tCell);

当我将呈现的表格附加到StringBuilder 并使用iTextSharp 将其写入PDF 时,单元格的Background-Color未显示。相反,当我将 StringBuilder 写入文字时,单元格被正确绘制。

这是我如何转换表格并将其附加到我的StringBuilder 的代码:

TextWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
Table myGenTable = (Table)genObjects[0];
myGenTable.RenderControl(hw);
sb.Append(tw.ToString()); //sb is the StringBuilder I'm working with

有没有一种方法可以让我在 pdf codument 中绘制 ccell? 表格的边框也存在同样的问题,该边框使用以下代码设置为表格本身的属性:

tblcblCellsCQ.BorderColor = Color.Black;
tblcblCellsCQ.BorderWidth = 2;
tblcblCellsCQ.BorderStyle = BorderStyle.Dashed;

这是我将 StringBuilder 写入 PDF 文件的代码:

StringReader sr = new StringReader(sb.ToString());
Document pdfDoc = new Document(PageSize.A4.Rotate(), 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=" + friendlyName + ".pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(pdfDoc);
Response.End();

【问题讨论】:

  • 您的问题不清楚:在 iTextSharp 中,您有 PdfPTablePdfPCell 等对象。没有TableCell 对象。 iTextSharp 中没有TextWriter,也没有HtmlTextWriterPdfPCell 没有 BorderStyle 等属性。您在标题中声称“背景颜色未在 iTextSharp 中显示”是非常不礼貌和不正确的,因为在您的问题中我们看不到任何证明您正在使用 iTextSharp 的证据。 请重新表述您的问题: 要么将其设为真正的 iTextSharp 问题,要么将 iTextSharp 排除在外!
  • @BrunoLowagie 我不使用PdfTablePdfCell,因为我的网站中的其他部分也需要生成的表格,而不仅仅是pdf。我已经添加了生成 pdf 文件的代码。
  • 好的,我撤回了我的反对票。您正在使用HTMLWorker。正如许多问题的许多答案中所解释的那样,HTMLWorker 已被弃用,取而代之的是 XML Worker。HtmlWorker 是 HTML 到 PDF 的非常不完整的实现。它不再受支持。不应再使用它。切换到使用 iTextSharp 的 XML Worker,看看问题是否仍然存在。
  • 好的,我会看看它,明天尝试更新我的代码。
  • 看看这些例子:example 1example 2example 3example 4 等等。

标签: c# pdf itextsharp


【解决方案1】:

试试这个:

for (int i = 0; i < col.Length; ++i)  
{  
   Cell cell = new Cell(new Phrase(col[i], new iTextSharp.text.Font(iTextSharp.text.Font.COURIER, 5)));  
   cell.Header = true;  
   cell.BackgroundColor = new iTextSharp.text.Color(204, 204, 204);       
   table.AddCell(cell);  
}

https://forums.asp.net/t/1577892.aspx?iTextSharp+table+headers查看答案

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-13
    • 2013-09-28
    • 2013-08-01
    • 2014-01-06
    • 2014-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多