C# 使用iTextC为所有页面添加背景色#

C# 使用iTextC为所有页面添加背景色#,c#,asp.net,itext,C#,Asp.net,Itext,我正在使用iTextSharp C#创建PDF。我有固定的页眉页脚内容,这些内容与PDFEvents绑定。我想给每页的中间内容添加背景色 这是我的密码 private void CreatePDF() { string fileName = string.Empty; DateTime fileCreationDatetime = DateTime.Now; fileName = string.Format("{0}.pdf", fileCreationDatetim

我正在使用iTextSharp C#创建PDF。我有固定的页眉页脚内容,这些内容与PDFEvents绑定。我想给每页的中间内容添加背景色

这是我的密码

private void CreatePDF()
{
    string fileName = string.Empty;

    DateTime fileCreationDatetime = DateTime.Now;

    fileName = string.Format("{0}.pdf", fileCreationDatetime.ToString(@"yyyyMMdd") + "_" + fileCreationDatetime.ToString(@"HHmmss"));

    string pdfPath = Server.MapPath(@"~\PDF\") +   fileName;

    using (FileStream msReport = new FileStream(pdfPath, FileMode.Create))
    {
        //step 1
        using (Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 140f, 10f))
        {
            try
            {
                // step 2
                PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, msReport);
                pdfWriter.PageEvent = new Common.ITextEvents();

                //open the stream 
                pdfDoc.Open();

                for (int i = 0; i < 5; i++)
                {
                    Paragraph para = new Paragraph("Hello world. Checking Header Footer", new Font(Font.FontFamily.HELVETICA, 22));

                    para.Alignment = Element.ALIGN_CENTER;

                    pdfDoc.Add(para);

                    pdfDoc.NewPage();
                }

                pdfDoc.Close();

            }
            catch (Exception ex)
            {
                //handle exception
            }

            finally
            {


            }

        }

    }
}
这是我添加来创建背景的代码

cb.RoundRectangle(0f, 40f, document.PageSize.Width, document.PageSize.Height - 140f, 1f);
cb.SetColorFill(new CMYKColor(0f, 0f, 0f, 0.0706f));
cb.Fill();
当我在OpenDocument事件中添加此代码时,这在第一页上可以正常工作。第二页和后续页的内容隐藏在此矩形后面。StartPage事件也是如此


需要帮助我做错了什么

正如mkl评论所建议的那样,我通过覆盖启动页面上的函数和下的usgindirectcontents添加背景解决了问题

public override void OnStartPage(PdfWriter writer, Document document)
  {
    base.OnStartPage(writer, document);
    var cbb = writer.DirectContentUnder;
    cbb.RoundRectangle(0f, 40f, document.PageSize.Width, document.PageSize.Height - 140f, 1f);
    cbb.SetColorFill(new CMYKColor(0f, 0f, 0f, 0.0706f));
    cbb.Fill();
  }

好的,当所有其他内容都已添加时,您可以用颜色填充
DirectContent
页面区域。除了覆盖已经添加的内容之外,还应该发生什么?是的,这是出现在第2页内容顶部的问题矩形。在添加内容之前,我需要将此代码放置在何处以添加背景色。请使用
UnderContent
而不是
DirectContent
。严格来说,我不会使用
OnStartPage
进行此操作,而是使用
onedpage
。使用
DirectContentUnder
而不是
DirectContent
是诀窍。Ok将在OneDPage中使用它。
public override void OnStartPage(PdfWriter writer, Document document)
  {
    base.OnStartPage(writer, document);
    var cbb = writer.DirectContentUnder;
    cbb.RoundRectangle(0f, 40f, document.PageSize.Width, document.PageSize.Height - 140f, 1f);
    cbb.SetColorFill(new CMYKColor(0f, 0f, 0f, 0.0706f));
    cbb.Fill();
  }