【问题标题】:iTextSharp - Unable to draw rectangle over tablecell background coloriTextSharp - 无法在表格单元格背景颜色上绘制矩形
【发布时间】:2015-07-06 12:14:56
【问题描述】:

我正在使用 iTextSharp 创建 PDF,并以 HTML 页面为例。我正在尝试在文本周围添加边框以突出显示某些项目。使用这些帖子(Draw Rect at curr position 和 Add Text over image)中的方法,我使用 OnGenericTag 事件为每个符合特定条件的块创建矩形。事件正确触发,矩形绘制在正确的元素上。但是,当我为表格单元添加背景时会出现问题,它出现在块矩形的顶部。有没有办法使从OnGenericTag 事件绘制的矩形绘制在表格单元格背景之上?


OnGenericTags 方法:

public class GenericTags : PdfPageEventHelper
    {
        public override void OnGenericTag(PdfWriter writer, Document pdfDocument, iTextSharp.text.Rectangle rect, String text)
        {
            if ("ellipse".Equals(text)) //I know it's not needed. 
                ellipse(writer.DirectContent, rect);
        }

        public void ellipse(PdfContentByte content, iTextSharp.text.Rectangle rect)
        {
            content.SaveState();
            content.SetRGBColorStroke(0x00, 0x00, 0xFF);
            content.SetLineWidth(2);
            content.Rectangle(rect.Left - 2f, rect.Bottom - 3f, rect.Width, rect.Height + 3f);
            content.Stroke();
            content.RestoreState();
        }
    }

每个PdfPCell定义为:

PdfPCell med = new PdfPCell(ph[4])
   {
     HorizontalAlignment = Element.ALIGN_CENTER,
     VerticalAlignment = Element.ALIGN_CENTER,
     BackgroundColor = hm_yellow //this draws above rect from onGenericTag()
   };

Chunks 是通过 foreach 循环创建和分配的:

ph[j] = new Phrase();
foreach (var x in p.Risks)
   {
      c[i] = new Chunk("R" + x.APP_RISK_ID.ToString() + ", ");
      if (x.RISK_STATUS_CD == "57")
      {
        //c[i].SetBackground(hm_top_tier); // still shows behind table cell background
        c[i].SetGenericTag("ellipse");
      }
    ph[j].Add(c[i]);
   }

这是我要转换为 PDF 的 HTML 页面。它显示了表格单元格的背景颜色以及需要在它们周围有一个矩形以突出显示它们的值。

这是呈现 PDF 时的结果。然而,突出显示的 R# 匹配,当我将背景颜色应用到 PdfPCell 时,它会绘制在来自 Chunk 的矩形上

【问题讨论】:

    标签: c# pdf itextsharp


    【解决方案1】:

    使用图层writer.DirectContentUnder 绘制表格以确保矩形保持在顶部 (writer.DirectContent)。

    【讨论】:

    • 如何将表格添加到 DirectContentUnder 层?
    • 使用PdfPTable.WriteSelectedRows()。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-21
    • 2016-05-19
    • 2013-06-15
    • 1970-01-01
    • 2015-11-29
    • 1970-01-01
    相关资源
    最近更新 更多