How to put a text and image as a header in Itextsharp PDF document


Hello, I'm all working with Itextsharp and in the pdf document that I already have, I want to add a title as a heading and next to it an image of the company but it does not work out as I want. This is what I did. but it does not work:

Paragraph title = new Paragraph(string.Format("RAYO DE LUZ"), new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 20, iTextSharp.text.Font.BOLD));
           title.Alignment = Element.ALIGN_CENTER;

           byte[] bytesImagen = new System.Drawing.ImageConverter().ConvertTo(Resources.nplk, typeof(byte[])) as byte[];
           iTextSharp.text.Image imagen = iTextSharp.text.Image.GetInstance(bytesImagen);
           imagen.Alignment = Element.ALIGN_RIGHT;
           imagen.ScaleAbsolute(120f, 120f);

I hope you can help me, thanks in advance.

asked by karol 05.01.2017 в 20:37

3 answers


You have to play with the positions of the image, based on the Cartesian plane:

Starting at position x=0, y=0 (bottom left corner of page)

I enclose the lines of code in the example:

//OBTENGO LA IMAGEN desde archivo
    public static iTextSharp.text.Image img = Image.GetInstance("Logo.png");
    private void CrearPDFConImagen()
            Document Doc = new Document(PageSize.LETTER, 10f, 10f, 10f, 0f);//Horizontal
            //Document Doc = new Document(PageSize.LETTER, 10f, 10f, 10f, 0f);
                , new System.IO.FileStream(
                    + "\EjemploImagen" + Guid.NewGuid() + ".pdf",


            // Le colocamos el título y el autor
            // **Nota: Esto no será visible en el documento
            Doc.AddTitle("Reporte de ejemplo Con imagen");
            Doc.AddCreator("Cristina Carrasco - [email protected]");

            //var logo = iTextSharp.text.Image.GetInstance("Logo.png");
            var parrafo2 = new Paragraph("             Titulo del PDF");
            parrafo2.SpacingBefore = 200;
            parrafo2.SpacingAfter = 0;
            parrafo2.Alignment = 1; //0-Left, 1 middle,2 Right

            img.ScaleToFit(125f, 60F);

            //Imagen - Esquina inferior izquierda
            img.SetAbsolutePosition(0, 0);

            //Imagen  - Movio en el eje de las X
            img.SetAbsolutePosition(200, 0);

            //Imagen - Movio en el eje de las Y
            img.SetAbsolutePosition(0, 200);

            //Imagen - Movio en el eje de las Y
            img.SetAbsolutePosition(0, 750);

            //Imagen - Movio en el eje de las Y
            //Esta imagen es la que esta centrada a un lado del titulo
            img.SetAbsolutePosition(150, 750);

        catch (Exception ex)
            throw new Exception(ex.ToString(), ex);

In this line:

var parrafo2 = new Paragraph("             Titulo del PDF");

Add some spaces at the beginning so that the image looks more or less centered.

I hope you find it useful, greetings.


Annex source code: Click to download


I'll explain more in detail.

The version of itextsharp I use is, you should validate that.

I add the references in the file as shown in the green box.

And when creating the variable img , what I do is create an instance of iTextSharp.text.mage and I send the name of the file Logo.png to the constructor, which must be added to the project, as shown in the box red from the previous image.

Another important thing about the image is that it must exist in the application folder so I did the following:

Select the option Copy to Output Directory = Copy always in the properties box (right click on the file Logo.png and then click on the option propiedades of the contextual menu in the section Explorador de soluciones of Visual Studio ), you can do this or copy the file directly to the folder where the application runs.

This is the image that I have added to the project:

When executing the application, it is copied to the folder of .exe (in my case it is a Windows application):

Maybe that's the detail you need. When the image does not exist, the system looks for it and marks error ( Can not find the file ):

answered by 06.01.2017 / 20:03

Sorry for possible errors; I do not work with C # so I'm not 100% sure of the syntax; I hope it is clear.

In this way you can include a header and / or footer at the beginning / end of each page:

Inside your code, add this class (in my case, I added a table that contains an image, you can modify the table to have two cells side by side, or as best suits you):

public class itsEvents : PdfPageEventHelper {

    /*Evento que ocurre al iniciar una nueva página en el documento. Se utiliza para insertar el encabezado.*/
    public override void OnStartPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document)
        PdfPTable t;
        PdfPCell c;

        Image imgLogo;
        String rutaLogo = Server.MapPath("../logo.png");

        imgLogo = iTextSharp.text.Image.GetInstance(rutaLogo);

        t = new PdfPTable(1);
        t.WidthPercentage = 100;

        float[] w = new float[1];
        w[0] = 10;

        c = new PdfPCell(imgLogo);
        c.Border = 0;
        c.VerticalAlignment = Element.ALIGN_TOP;
        c.HorizontalAlignment = Element.ALIGN_LEFT;


    /*Evento que ocurre antes de pasar a una nueva página en el documento. Se utiliza para insertar el pie de página.*/
    public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document)


And in your main class, when you create the document:

PdfWriter pdfWrite = PdfWriter.GetInstance(document, new FileStream(ruta, FileMode.OpenOrCreate));
itsEvents ev = new itsEvents();
pdfWrite.PageEvent = ev;

If you need to put a heading only on certain pages, within the events OnStartPage and OnEndPage you get the page number as follows:

int pageN = writer.PageNumber;

if (pageN == 1) {
    // Encabezado/pie de página sólo en la primera página
answered by 09.01.2017 в 21:14

Try the following:

   string archivoImagen= "logo.jpg";
   string imagenPath= Path.Combine(Environment.CurrentDirectory, @"img\", archivoImagen); 
// Esto es C:\MyProjects\Apps\TUApp\bin\Debug\img\logo.jpg

Image imagen = Image.GetInstance(imagenPath);  
Paragraph p = new Paragraph();
p.Add(new Chunk(imagen, 0, 0));
p.Add(new Phrase("Esto es un logo")); 
answered by 05.01.2017 в 21:04