【问题标题】:IText background color for cell data单元格数据的 IText 背景颜色
【发布时间】:2018-06-30 17:40:52
【问题描述】:

我正在使用 itextsharp 创建 PDF,我有三行数据。我可以设置一段文本的背景颜色,但我需要的是根据不同行中的文本为整个区域赋予背景颜色。 我找到了通过添加表格来执行相同操作的解决方案,但是当我添加表格时,我的表格在文档中不可见。

任何人都可以分享完整的代码来添加表格然后单元格的内容和背景颜色吗? 这是我的代码:

float width = 85.6063f;
iTextSharp.text.Rectangle pageSize = new iTextSharp.text.Rectangle(width, tempHeight);
if (System.IO.File.Exists(path))
{
    System.IO.File.Delete(path);
}
Document document = null;
PdfWriter writer = null;
document = new Document(pageSize, 4, 4, 0, 5);

writer = PdfWriter.GetInstance(document, new FileStream(path, FileMode.OpenOrCreate));
document.Open();
PdfPCell myCell;
iTextSharp.text.Font font1 = FontFactory.GetFont(FontFactory.HELVETICA, 12, BaseColor.BLACK);
myCell = new PdfPCell(new Phrase("hi", font1));
PdfPTable myTable = new PdfPTable(2);

PdfPCell cellTest = new PdfPCell(new Phrase("This is a test document"));
cellTest.BackgroundColor=new BaseColor(255,0,0);
myTable.AddCell(cellTest);

document.Add(myTable);
Paragraph welcomeParagraph = new Paragraph("Hello, World");

document.Add(welcomeParagraph);
string BinPath = Server.MapPath("~");
String strAppPath = BinPath;
float fontSize = 5;

BaseFont bfnimodmt = BaseFont.CreateFont(BinPath + @"Fonts\mangalb.ttf", BaseFont.CP1252, BaseFont.EMBEDDED);
iTextSharp.text.Font font = new iTextSharp.text.Font(bfnimodmt, 12);
Chunk c1 = new Chunk(HTML, font);
Phrase p1 = new Phrase(c1);
Paragraph ph = new Paragraph();
ph.Add(p1);
iTextSharp.text.Font fonts = new iTextSharp.text.Font(bfnimodmt, (float)fontSize);
iTextSharp.text.Font fontsbold = new iTextSharp.text.Font(bfnimodmt, (float)fontSize);

BaseFont bfnimodmta = BaseFont.CreateFont(BinPath + @"Fonts\mangal.ttf", BaseFont.CP1252, BaseFont.EMBEDDED);
iTextSharp.text.Font fonts1 = new iTextSharp.text.Font(bfnimodmt, (float)fontSize);
iTextSharp.text.Font fontsbold1 = new iTextSharp.text.Font(bfnimodmt, (float)fontSize);
//For Image-------------------------------------------------Image------------------------------
#region For image

string imageURL = imageDynamicPath;
string FrameImgPath = Server.MapPath("~") + @"Images\big.jpg";

System.Drawing.Image img1 = System.Drawing.Image.FromFile(imageURL);
System.Drawing.Image img2 = System.Drawing.Image.FromFile(FrameImgPath);

String jpg3 = Server.MapPath("~") + @"Images\big1.jpg";
Bitmap template = new Bitmap(img2);
Bitmap Picture = new Bitmap(img1);
iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageURL);
jpg.ScaleAbsolute(80f, 80f);
//Framejpg.ScaleAbsolute(85f, 85f);
PdfPCell cell = new PdfPCell(jpg);
cell.HorizontalAlignment = Element.ALIGN_CENTER;
#endregion
string strFirst, strSecond;
string HTMLinput = HTML;
int FirstEnter = HTMLinput.IndexOf("\r\n");
int FirstSpace = HTMLinput.IndexOf(" ");
int firstLINE = HTMLinput.IndexOf("</p>");
if (FirstSpace == -1 && FirstEnter == -1)
{
    strFirst = HTMLinput;
    strSecond = "";
}
else
{
    if (FirstSpace == -1)
    {
        strFirst = HTMLinput.Substring(0, HTMLinput.IndexOf("\r\n"));
        strSecond = HTMLinput.Substring(HTMLinput.IndexOf("\r\n"));
    }
    else if (FirstEnter == -1)
    {
        strFirst = HTMLinput.Substring(0, HTMLinput.IndexOf(" "));
        strSecond = HTMLinput.Substring(HTMLinput.IndexOf(" "));
    }
    else if (FirstSpace > FirstEnter)
    {
        strFirst = HTMLinput.Substring(0, HTMLinput.IndexOf("\r\n"));
        strSecond = HTMLinput.Substring(HTMLinput.IndexOf("\r\n"));
    }
    else //if (FirstSpace < FirstEnter )
    {
        strFirst = HTMLinput.Substring(0, HTMLinput.IndexOf(" "));
        strSecond = HTMLinput.Substring(HTMLinput.IndexOf(" "));
    }
}
Chunk ch = new Chunk(strFirst.ToUpper());
string seperator = "", strThid = "";
Chunk ch1 = new Chunk(strSecond);
Chunk ch2 = new Chunk(strThid);
Chunk ch3 = new Chunk(seperator);
iTextSharp.text.Paragraph prText = new iTextSharp.text.Paragraph(" ");
prText.Leading = 1;
List<IElement> objects = HTMLWorker.ParseToList(new StringReader(HTMLinput), null);
foreach (IElement element in objects)
{
    pageSize.BackgroundColor = new BaseColor(255, 222, 173);
    document.Add(element);
    break;
}
int remove = Math.Min(objects.Count, 1);
objects.RemoveRange(0, remove);
foreach (IElement element in objects)
{
    document.Add(element);
}
document.Close();

return true;

在上面的代码中,“myTable”在我的 PDF“文档”中不可见

【问题讨论】:

  • 你试过什么?您没有包含任何代码。您也没有包含 iText 版本。
  • 我使用的是 IText 5.5.1 版
  • HTMLWorker 相关部分是否相关?特别是,您是否打算在 HTML 中创建需要背景颜色的表格?还是只是一些通用内容?

标签: c# asp.net itext


【解决方案1】:

如果您使用的是 iText7,您应该可以使用以下代码解决此问题:

    Table table = new Table(5);

    Cell sn = new Cell(2, 1).add("S/N");
    sn.setBackgroundColor(Color.YELLOW);
    table.addCell(sn);

    Cell name = new Cell(1, 3).add("Name");
    name.setBackgroundColor(Color.CYAN);
    ...

您还可以查看有关表格的教程 https://developers.itextpdf.com/examples/tables/clone-adding-background-table

如果您使用的是 iText5,请查看
https://developers.itextpdf.com/examples/tables-itext5/adding-background-table

如果您使用 iText 开始一个新项目,请考虑使用 iText7。由于 iText5 即将不再受支持。

【讨论】:

  • 此代码不起作用,我使用的是 IText 版本 5.5.1
  • 您的问题最初并未包含该信息。我无法猜测您使用的是哪个版本。如果你提供了代码,我就知道了。
【解决方案2】:

要使用 iText 5.x for .Net 创建具有单个单元格背景的表格,您可以使用BackgroundColor 单元格属性:

PdfPTable table = new PdfPTable(2);
PdfPCell cell1 = new PdfPCell(new Phrase("Cell A"));
cell1.BackgroundColor = BaseColor.YELLOW;
table.AddCell(cell1);
PdfPCell cell2 = new PdfPCell(new Phrase("Cell B"));
cell2.BackgroundColor = BaseColor.GREEN;
table.AddCell(cell2);

This very old question 显示了 iText for Java 的类似方法。


如需更多控制,例如对于同一单元格中的多种颜色,您应该使用单元格事件,例如使用这个事件类

public class ColorizeBackgroundEvent : IPdfPCellEvent
{
    BaseColor color;
    public ColorizeBackgroundEvent(BaseColor color)
    {
        this.color = color;
    }

    public void CellLayout(PdfPCell cell, iTextSharp.text.Rectangle position, PdfContentByte[] canvases)
    {
        PdfContentByte canvas = canvases[PdfPTable.BACKGROUNDCANVAS];
        canvas.SaveState();
        canvas.SetColorFill(color);
        canvas.Rectangle(position.Left, position.Bottom, position.Width, position.Height);
        canvas.Fill();
        canvas.RestoreState();
    }
}

使用此代码获得与上面相同的效果:

using (Stream output = new FileStream(@"TableWithColoredCellBackgrounds.pdf", FileMode.Create))
using (Document document = new Document(PageSize.A4, 50, 50, 25, 25))
{
    PdfWriter writer = PdfWriter.GetInstance(document, output);
    document.Open();

    PdfPTable table = new PdfPTable(2);
    PdfPCell cell1 = new PdfPCell(new Phrase("Cell A"));
    cell1.CellEvent = new ColorizeBackgroundEvent(BaseColor.YELLOW);
    table.AddCell(cell1);
    PdfPCell cell2 = new PdfPCell(new Phrase("Cell B"));
    cell2.CellEvent = new ColorizeBackgroundEvent(BaseColor.GREEN);
    table.AddCell(cell2);
    document.Add(table);

    document.Close();
}

两种情况的结果如下所示:

【讨论】:

  • 有关单元格事件使用的更有趣示例,请查看this answer - 它适用于 iText for Java,但应该很容易移植到 .Net。
  • This answer 还显示了BackgroundColor 单元格属性的用法。
猜你喜欢
  • 1970-01-01
  • 2011-09-18
  • 2022-12-12
  • 2015-11-29
  • 1970-01-01
  • 2011-04-03
  • 1970-01-01
  • 2014-10-08
  • 1970-01-01
相关资源
最近更新 更多