How do I insert a background image on all pages of a pdf-document?

26,308

You can try this;

void makePDF()
{
    Response.ContentType = "application/pdf";

    Response.AddHeader("content-disposition", "attachment;filename=test.pdf");

    Response.Cache.SetCacheability(HttpCacheability.NoCache);

    string imageFilePath = Server.MapPath(".") + "/images/test.jpg";

    iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageFilePath);

    // Page site and margin left, right, top, bottom is defined
     Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);

    //Resize image depend upon your need
    //For give the size to image
     jpg.ScaleToFit(3000, 770);

    //If you want to choose image as background then,

    jpg.Alignment = iTextSharp.text.Image.UNDERLYING;

    //If you want to give absolute/specified fix position to image.
    jpg.SetAbsolutePosition(7, 69);

    PdfWriter.GetInstance(pdfDoc, Response.OutputStream);

    pdfDoc.Open();

    pdfDoc.NewPage();

    Paragraph paragraph = new Paragraph("this is the testing text for demonstrate the image is in background \n\n\n this is the testing text for demonstrate the image is in background");

    pdfDoc.Add(jpg);

    pdfDoc.Add(paragraph);

    pdfDoc.Close();

    Response.Write(pdfDoc);

    Response.End();
 }
Share:
26,308

Related videos on Youtube

roman
Author by

roman

I'm a student and software developer in Conscensia firm

Updated on July 09, 2022

Comments

  • roman
    roman almost 2 years

    I need sample code in C# to insert the background image on all pages of the finished pdf-document. I'm using iTextSharp library.

  • roman
    roman about 13 years
    I can not use Response. Maybe I need connect something namespace?
  • Soner Gönül
    Soner Gönül about 13 years
    I think you should add using iTextSharp.text using iTextSharp.text.pdf like that. I'm not sure..
  • Mark Storer
    Mark Storer about 13 years
    I think he just wants to write it out to a file.
  • spadelives
    spadelives almost 11 years
    This solution only adds the background image to the first page. How about adding the background to every page?
  • ahmednawazbutt
    ahmednawazbutt about 2 years
    any update yet?

Related