Creating PDF Files in ASP.NET Using ITextSharp

iText is a library that allows you to create and manipulate PDF documents. It enables developers looking to enhance a web or other application with dynamic PDF document generation and/or manipulation.

Developers can use iText to:

  1. Serve PDF to a browser
  2. Generate dynamic documents from XML files or databases
  3. Use a PDF's many interactive features
  4. Add bookmarks, page numbers, watermarks, etc
  5. Split, concatenate, and manipulate PDF pages
  6. Automate filling out of PDF forms
  7. Add digital signatures to a PDF file

iText is available in Java as well as in C#.

Find some links below that will help you to explore this:

Official Website: https://itextpdf.com/products/itext-7

Knowledge Base: https://kb.itextpdf.com/home

Assemblies Download: https://sourceforge.net/projects/itextsharp/

So, now if you want to use this in ASP.NET application, I have created sample solution for you; just follow the steps to understand it.

Step 1

First of all you need to download the components (dll) from here.

Step 2

Now, open the Visual Studio and create a simple website and add a "Bin" folder in the project.

Step 3

If you are done with the above, right-click on the "Bin" folder and select "Add Reference" and in the dialog box that appears click on the Browse button and locate the dll we have saved in step 1.

image1.png

Step 4

Now in the code-behind add the two namespaces iTextSharp.text and iTextSharp.text.pdf and add a folder named "PDF_Files" on the root. Remember, if you are using hosting then you need to allow Read and Write permission on this folder.

Step 5

Okay, use the following code-behind code:

var doc1 = new iTextSharp.text.Document();
string path = Server.MapPath("PDF_Files");
PdfWriter.GetInstance(doc1, new FileStream(path + "/Doc1.pdf", FileMode.Create));
doc1.Open();
doc1.Add(new Paragraph("My sample text goes here."));
doc1.Close();

Step 6

After doing the above, run the project and test it; the complete code is:

Code-Behind

using System
using System.Collections.Generic;using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using iTextSharp.text;
using iTextSharp.text.pdf;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        var doc1 = new iTextSharp.text.Document();
        string path = Server.MapPath("PDF_Files");
        PdfWriter.GetInstance(doc1, new FileStream(path + "/Doc1.pdf", FileMode.Create));
        doc1.Open();
        doc1.Add(new Paragraph("My sample text goes here."));
        doc1.Close();
    }
}

image2.jpg

If you want to explore it more, please visit here http://itextpdf.com/summit.php.

I hope you like it. Thanks.


Similar Articles