如何使用C#中的iTextSharp将添加的图像添加到最前端

时间:2010-11-11 19:10:02

标签: c# .net pdf pdf-generation itextsharp

好的,我必须制作一个有一些风格的PDF。这是标签。我有以下代码:

Document doc = new Document(PageSize.A4);

    int labelHeight = 394;
    int labelWidth = 556;

    float labelTop = doc.PageSize.Height - 2;
    float labelBottom = doc.PageSize.Height - labelHeight;

    MemoryStream ms = new MemoryStream();
    PdfWriter writer = PdfWriter.GetInstance(doc, ms);
    doc.Open();

    PdfContentByte cb = writer.DirectContent;

    // Generate Boxes For Content

    cb.SetColorStroke(new CMYKColor(207, 115, 255, 133));
    cb.SetLineWidth(4);
    cb.SetColorFill(new CMYKColor(207, 71, 255, 38));

    cb.MoveTo(2, labelBottom);
    cb.LineTo(labelWidth - 2, labelBottom);
    cb.LineTo(labelWidth - 2, labelTop);
    cb.LineTo(2, labelTop);

    cb.ClosePathFillStroke(); // Draw Main Green Box

    cb.SetColorStroke(new CMYKColor(0, 0, 0, 0));
    cb.SetLineWidth(1);
    cb.SetColorFill(new CMYKColor(0, 0, 0, 0));

    int whiteBoxTop = 100;
    int whiteBoxHeight = 260;

    cb.MoveTo(5, labelTop - (whiteBoxTop + whiteBoxHeight));
    cb.LineTo(labelWidth - 5, labelTop - (whiteBoxTop + whiteBoxHeight));
    cb.LineTo(labelWidth - 5, labelTop - whiteBoxTop);
    cb.LineTo(5, labelTop - whiteBoxTop);

    cb.ClosePathFillStroke(); // Draw Inner White Content Box

    cb.SetColorStroke(new CMYKColor(20, 15, 41, 0));
    cb.SetLineWidth(0);
    cb.SetColorFill(new CMYKColor(20, 15, 41, 0));

    cb.MoveTo(labelWidth / 2, labelTop - ((whiteBoxTop + whiteBoxHeight) - 4));
    cb.LineTo(labelWidth - 9, labelTop - ((whiteBoxTop + whiteBoxHeight) - 4));
    cb.LineTo(labelWidth - 9, labelTop - (whiteBoxTop + 4));
    cb.LineTo(labelWidth / 2, labelTop - (whiteBoxTop + 4));

    cb.ClosePathFillStroke();

    string logoPath = Server.MapPath(".") + "/pdf_logo.jpg";

    iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(logoPath);

    logo.SetAbsolutePosition(labelWidth / 4, labelTop - (whiteBoxTop + whiteBoxHeight) + 25);
    logo.ScaleToFit(150, 30);


    doc.Add(logo);    

    doc.Close();

问题在于添加了徽标。如果我添加它并将其显示在我正在创建它的框下方,但是当我将绝对位置放到框的位置时,它会在绘制的框后面消失。我需要做什么才能将图像放在我绘制的方框上方?对于我尝试在框顶部添加的任何文本,也会发生同样的问题。

1 个答案:

答案 0 :(得分:6)

尝试将徽标添加到PdfContentByte对象而不是Document

替换它:

doc.Add(logo);

用这个:

cb.AddImage(logo);