Monday, March 10, 2014

How to Create PDF Using itextsharp in Asp.Net

1 comment
In this tutorial I am going to explain the process of creating pdf file using itextsharp in asp.net using c#.
First of all we will learn how to create static content PDF file using itextsharp . In the upcoming tutorials I will explain how to create PDF using database in asp.net and also how to customize the PDF document.

Steps to Create PDF in asp.net Using itextsharp:

Step 1: First download the itextsharp dll from this url: Dowload itextsharp.

Step 2: Extract the downloaded file. Inside that there will be multiple zip file. For creating PDF extract the the zip file named itextsharp-dll-core and copy and paste the itextsharp.dll on your desktop.

Step 3: Add new project or add reference to itextsharp.dll in existing project by Right Click on Add Reference as shown below:

add reference in visual studio

Step 4: In Add Reference window Select Browse as shown in the diagram below:

Add Reference to itextsharp

Step 5: Select the itextsharp.dll from desktop and click on ok as shown in the snapshot below:

Reference to itextsharp.dll

Add the following code to Generate 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>



Add Reference in Code Behind:

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


C # 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("This is your first PDF using itextsharp"));

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

           
        }

Note: Add UploadPDF folder into your project inside which the pdf would be created.

Hope this has given you basic idea of creating pdf using itextsharp dll.

1 comment:

  1. Nice article I have also taken reference from link below that has demo app with code availaible to download
    http://geeksprogrammings.blogspot.com/2014/03/convet-html-to-pdf-asp-itextsharp.html

    ReplyDelete