Monday, March 10, 2014

How to Add Image to PDF using itextsharp in asp.net

Leave a Comment
In previous article I explained the steps of creating pdf using itextsharp. In this tutorial I am going to explain how to add the image in PDF file using itextsharp. This image can be header image or any other image on PDF document.

Use Image class of itextsharp to add the image inside PDF.

HTML Code :
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Genrate PDF"
            onclick="Button1_Click" />
</div>
</form>
</body>
</html>


C# Code to Add Image in PDF using itextsharp:

Add Reference:
using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;

Code:
protected void Button1_Click(object sender, EventArgs e)
        {
            var doc1 = new Document();

      //Name of the folder into which PDF is to be uploaded
            string pathoffile = Server.MapPath("UploadPDF");

            //Created pdf file with the name test.pdf
            PdfWriter.GetInstance(doc1, new FileStream(pathoffile +" /test.pdf", FileMode.Create ));

            //Open Pdf
            doc1.Open();
            //Add New Paragraph to PDF File
            doc1.Add(new Paragraph("Add Image Using itextsharp"));

            //Specify the path of the image
            string imagepath = Server.MapPath("Lighthouse.jpg");

            iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imagepath);
            //Add the Image to pdf file
            doc1.Add(img);

            //Close the Pdf file
            doc1.Close();

           
        }


Final Output :

0 comments:

Post a Comment