IText单元格数据的背景颜色

时间:2018-01-22 06:23:43

标签: c# asp.net itext

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

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

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;

在上面的代码&#34; myTable&#34;在我的PDF&#34;文档&#34;

中不可见

2 个答案:

答案 0 :(得分: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正在不再受支持。

答案 1 :(得分:1)

要使用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();
}

两种情况下的结果都是这样的:

Screenshot