Add image in PDF using iTextSharp

What is ITextSharp - iTextSharp is a free and open source assembly which helps to convert page output or html content in pdf file.

You can download from here:

http://sourceforge.net/projects/itextsharp/

Now add that dll in application.

Getting Started

Start visual studio and create a new website in asp.net and add these 2 dll in solution.

Itextsharp.dll

itextsharp.pdfa.dll

add namespaces  -

using iTextSharp.text;

using iTextSharp.text.pdf;

using iTextSharp.text.html;

using iTextSharp.text.html.simpleparser;

 

protected void btnCreatePDF_Click(object sender, EventArgs e)

    {

        Document doc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);

        string pdfFilePath = Server.MapPath(".") + "/PDFFiles";      

        PdfWriter writer = PdfAWriter.GetInstance(doc, new FileStream(pdfFilePath + "/Default.pdf", FileMode.Create));

        doc.Open();

        try

        {

            Paragraph paragraph = new Paragraph("Getting Started ITextSharp.");

            string imageURL = Server.MapPath(".") + "/image2.jpg";

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

            //Resize image depend upon your need

            jpg.ScaleToFit(140f, 120f);

            //Give space before image

            jpg.SpacingBefore = 10f;

            //Give some space after the image

            jpg.SpacingAfter = 1f;

            jpg.Alignment = Element.ALIGN_LEFT;

 

            doc.Add(paragraph);

            doc.Add(jpg);

 

        }

        catch (Exception ex)

        { }

        finally

        {

            doc.Close();

        }

    }

Hit F5 to see output.

img1.jpg

Image 1.

PDF file has been saved in “PDFFiles” folder under solution.