Tuesday, 20 September 2016

Insert an image into PDF using iTextSharp with C# (C-Sharp)

In this article, we are going to learn how to insert an image into PDF file using itextsharp in asp.net with C#. First, you need to download iTextSharp dll from the internet. Click on the below link to download the dll.

https://github.com/itext/itextsharp

Related Article

  1. How to generate PDF file using iTextSharp in C#
  2. How to export GridView data into PDF using iTextSharp in asp.net with C#
  3. How to add meta information of PDF file using iTextSharp with C-Sharp
  4. How to extract images from a pdf file using C#.Net

Once file is downloaded, extract it, now you will find 6 more .rar file. Again extract itextsharp-dll-core.rar file, after that add reference of itextsharp.dll to your project.

In Code-Behind File

Add below nampespaces.

using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;

Complete C# code:

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        InsertImage();
    }
}

public void InsertImage()
{
    // create filestream object
    FileStream fs = new FileStream(Server.MapPath("Example.pdf"), FileMode.Create);

    // create document object
    Document doc = new Document();

    // create PdfWriter instance which will write at file filestream
    PdfWriter.GetInstance(doc, fs);

    // opening the dociment
    doc.Open();

    // creating paragraph object
    Paragraph para = new Paragraph("Insert an image into pdf using C#.");
    para.Alignment = Element.ALIGN_CENTER;

    // adding pargraph to document
    doc.Add(para);

    // setting image path
    string imagePath = Server.MapPath("Images") + "\\demo.PNG";
    // string imagePath = Server.MapPath("Images\\demo.PNG") + "";

    iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imagePath);

    image.Alignment = Element.ALIGN_CENTER;

    // set width and height
    image.ScaleToFit(180f, 250f);

    // adding image to document
    doc.Add(image);
    // closing the document
    doc.Close();
}

Below is the pdf file generated.

Insert image into pdf using c-sharp
Share:

0 comments:

Post a Comment

Email Subscription

Subscribe to our newsletter to get the latest articles directly into your inbox

Blog Archive

BUY FROM AMAZON