Create PDFs in ASP.NET - getting started with iTextSharp

4.45 (157 votes)

The .NET framework does not contain any native way to work with PDF files. So, if you want to generate or work with PDF files as part of your ASP.NET web application, you will have to rely on one of the many third party components that are available. Google will help you to find one that fits your budget, as well as a range of open-source free components. One of the free components is iTextSharp, which is a port of a well known Java utility, iText.

The main problem with iTextSharp is that it lacks documentation. There are some basic tutorials available, but most programmers have to resort to trying to wrestle with the documentation provided for the Java version - iText - to get going with the component, or you may want to purchase the book iText In Action. However, this only provides guidance in Java. Many of the code samples are transferable to C# without a lot of modification, but if you are relatively new to C#, you may frequently become frustrated with undocumented or inexplicable differences in classes and method names between the two versions. So, as part of a series of How To articles, here's how to get started using iTextSharp with code samples in C#.

First thing to do is to install the Nuget package.. The dll will be copied to your Bin directory, and is now available to the web site or project. Note that this link takes you to an older version of iTextSharp (4.1.6) instead of the later version 5 releases. The reason for that is that version 5 is available under a different licence that requires you to either make all of the source code of your application available as open source, or to purchase a commercial licence to use iTextSharp in commercial projects. Version 4 does not apply those restrictions. All of the articles I have written about iTextSharp are based on version 4.1.6 in any event, and they may not work with version 5.

I have also added a folder called PDFs in which I plan to store my generated files. To avoid typing full references to the dll, it is best to add a couple of using statements to the default ones in your code-behind:

using iTextSharp.text;

using iTextSharp.text.pdf;

You will also want to reference System.IO, as you will be creating, opening and closing files, and classes in this namespace are required.

The principal object within iTextSharp is the Document object. You need to create an instance of this to be able to work with your PDF in memory. So, the first thing to do is to instantiate one:


var doc1 = new Document();


This creates a PDF document object in memory with the default settings. The size of the document by default is A4 (which measures 210mm x 297mm, or 8.26 inches x 11.69 inches). Margins are set at half an inch all round. The next thing to do is to commit the document to disk. The iTextSharp.text.pdf.PdfWriter class is required for this:


//use a variable to let my code fit across the page...

string path = Server.MapPath("PDFs");

PdfWriter.GetInstance(doc1, new FileStream(path + "/Doc1.pdf", FileMode.Create));


Now to begin actually working with the document, open it, and add a new paragraph, then close it:



doc1.Add(new Paragraph("My first PDF"));



That's it! If you refresh the PDFs folder in your web site, you will see that a new item - Doc1.pdf - has been added, and opening it will reveal your success.

It may be, however, that you don't want to always create a PDF with the default size and margins, so iTextSharp provides ways for you to customise these settings. There are 2 further constructors to the Document object:


public Document(iTextSharp.text.Rectangle pageSize);

public Document(iTextSharp.text.Rectangle pageSize, float, float, float, float);


The first one can be used like this:


var doc = new Document(PageSize.A5);


The PageSize class contains a number of Rectangle objects representing the most common paper sizes from A0 to A10, B0 to B10, LEGAL, LEDGER, LETTER, POSTCARD, TABLOID and so on. If you want to apply a custom size that isn't available within the PageSize class, you define your own Rectangle object, set its properties and pass that into the constructor as an argument:


var doc = new Document(new Rectangle(100f, 300f));

PdfWriter.GetInstance(doc, new FileStream(path + "/Doc2.pdf", FileMode.Create));


doc.Add(new Paragraph("This is a custom size"));



In this case, a PDF document was created with the width being 100 points, and the height set at 300 points. There are 72 points to an inch, so this particular document isn't very large. It's in fact 1.39 inches x 4.17 inches. (You will probably find that as well as iTextSharp.dll, a calculator will be very handy....).

The second constructor which takes a Rectangle object and a series of 4 float values allows you to set your custom margins through the floats. Again, these values are measured in points. The default half inch margins are 36 points.

If you use the PageSize class constructor, or a Rectangle directly, you can also set the background colour of the document. This can be done using RGB colour values, or CMYK (Cyan - a kind of blue, Magenta - a pinkish red, Yellow and "Key", or black). It used to be that if you wanted to prepare a PDF for printing by a professional lithographic printer, you had to ensure that all colours were CMYK, but with greater adoption of digital printing by printing companies, RGB is becoming more acceptable. Certainly, for display on the web, RGB is preferred. To set the background colour, we use the BackgroundColorproperty of the Rectangle object:


r.BackgroundColor = new CMYKColor(25, 90, 25, 0);

r.BackgroundColor = new Color(191, 64, 124);


Both of the above result in a rather fetching pinkish colour for the document.

This article has introduced iTextSharp, and should have provided a starting point. Subsequent articles examine a range of functionality and features offered by this rather natty component. They can be found here:


Date Posted:
Last Updated:
Posted by:
Total Views to date: 557273


- Nilesh

Write articles for each Control in ASP.NET 3.5
please ....Do this for beginners like me

- Kirun

thanks for the nice article

- Wu

Good example for newbie

- jigar

i want to create 2 pages

- Mike


If you read some of my other articles on iTextSharp, you will discover that you need to use Document.NextPage() to add a page.

- David Welker

I used ItextSharp once to create printable versions of a page, and it's a huge pain to figure out. It's great that you are creating a how to, but it will be hard to get into in depth things. Good luck!

- Mike


It is very difficult to convert an HTML page to PDF using iTextSharp because the htmlparser that's built into iTextSharp is rudimentary at best. I store valid xhtml snippets in the database behind my site, so I reckon I may have more luck than most. When I have a bit more time on my hands, I will have a stab and blog the results.

- NA

iTextSharp is very limited and quite cumbersome to use. For thos who are serious about generating PDF, look at purchasing one.

- Mike


Your comment may have a carried a little weight if you had expanded on it a little more, such as detailing where iTextSharp is limited or how it is cumbersome, or perhaps providing some info on paid-for alternatives.

As it stands, I think you are wrong. iTextSharp is no more cumbersome that eg ASPPdf, and the only limitation I have found with it is in parsing HTML.

Your comment has all the hallmarks of a flame. Maybe that's why you chose to remain completely anonymous.

- NitinK

Nice Article !!!

- Jason McKenzie

I'm using PDF Duo .NET component by duodimension company.
For creating a PDF I just put html string:

conv.OpenHTML("This is a new page");

- Mike


I noticed that it's not free, and plonks an advert on your PDF if you are using the evaluation version.

- Gareth

You don't need to use Reflector to view the source - you can just download it from the iTextSharp sourceforge site (just don't pick the -dll zip), and compile it yourself. Makes it much easier to work out what's going on, by viewing the comments in the code!

- Mike


Nice spot! I didn't notice that option.

- Mike

Thanks to your blog I was able to complete an assignment that required me to create a dynamic shipping form.
Kind Regards,

- Kieran

Thanks for this series of articles, very helpful and informative

- Peter Ingraham

Thanks for these articles! I wouldn't have been able to complete my project as quickly as I dd without them.

- Moiz

Thanks for nice articles.

"It is very difficult to convert an HTML page to PDF using iTextSharp because the htmlparser that's built into iTextSharp is rudimentary at best."

I need to convert Html pages to pdf files using iTextSharp.

Please help me with using the htmlparser.

Thanks and regards.

- Rupert Waldeck-Nel

I've used iTextSharp in numerous web pages in our intranet site. At that time articles like this did not exist so I had to do a lot of trial and error work (Converting to VBNET nor did conversion sites). This library has saved me many a time and however frustrating it does get at times, I'm glad I found it at the time I did as management would certainly not have understood why they can't get pdf's let alone why they should fork out any money for some library. Furthermore there is another library I came across a while back at the following address

I've worked only in experimental ways with this, and recently returned to iTextSharp when I had the need in project for tables, as I was familiar with tables in this trusty library, returned to a trusty friend. Anyhow maybe someone would prefer PdfSharp dunno, I still stick with iTextSharp.

- Mike

Just wanted to say thanks to you for writing this article. It's all simple information but it's displayed well, and when you're coming at something for the first time it's a massive timesaver. It's things like this that make "the internet" great. :)

- Ken

Thanks for the article! Great help for my first time using itextsharp!

- Denis

Thanks very good article

- Davide

I'm trying to use itextsharp but I don't have Visual Studio nor visual web developer. How can I use it with "manually written" aspx pages?

- junior developer

thanks.this is my life`s first task .
With help of your blog i can complete easily

- Jacob Coens

Hi Mike,

Nice article but it seems that iText is not or no longer free unless the application you are using it in is either non-commercial or open source: "Buying (...) a license is mandatory as soon as you develop commercial activities involving the iText software without disclosing the source code of your own applications. These activities include: offering paid services to customers as an ASP, serving PDFs on the fly in a web application, shipping iText with a closed source product.", as stated on

Recently, I have used PDFSharp, which is free and did what I needed to get done quite easily.


- Sakhi

Thanks for this article....coz it is difficult to find any documentation regarding the iTextSharp

- Maurits

Hi Mike. Great article! Thanks ever so much, i was wondering if it is possible to overwrite files?
Sorry i've you mentioned this before.

- Emmanuel

Helped a lot for starting quickly ! ;-)

- Emmanuel

Good job ! ;-)

- vaishali

beautiful post

- robsta

Hi Mike,

This has been great for me as well, let me know if you take on project work.

- Tung

That great help, thanks alot man!!

- Nguyen

Over 2 years later and your article was the first one that made sense to me. Thank you!

- David

Hi, Mike -
Thanks for a clear and easy-to-follow tutorial (#1). I'm reading 'iText in Action' at the same time, but it makes it so much easier to grasp when seeing coe in C#. Great job!

- NA

iTextSharp, has a previous version that does not include the licensing files. The latest version forces the user to adhere to the licenses and expose their code publically. Please anyone chime in, if you know more than that. I am looking for a previous version, because I can't expose my code publically.

- Mike


You can get the previous version (4.1.6 - the version that all my articles are based on) from Nuget:

- Dylan


Do the itextsharp able to use in VS2010 ?

Best Regards,

- michele

complimenti, questo articolo e tutti gli altri tuoi relativi a iTextSharp sono una manna

grat work! many thanks!


I have edit pdf file using itextsharp.dll but text not showing up. plz help me.

- pavan

Nice article ..its very useful ..thanks

- Vishnu

it is useful code for me

- Lau

Thanks for sharing! ;)

- dan

Hi, great article. Congrats. So, can i open any pdf in a new tab?


- ahmad

Thanks for the great information, is it possible to add background image instead of color to the pdf document?

- Paul K

Thank you very much for this series of articles. Over the past several months, I have used them repeatedly. You have certainly helped me a great deal, and I suspect many others like me too. THANKS!

- John

Very useful.

To add a second page to the document use
doc1.Add(New Paragraph("My second page of PDF"))

On a webforms project after the code creates the PDF usually you use


to display it for printing.

You can use the following to display it in a popup window

Dim filename As String = "HelloWorld2.pdf"
' using a string to hold the file name causes the name to be dynamic

Dim path As String = Server.MapPath("~/PDFs")
' this allows for dynamic save location , it may be advisable to use try,catch to ensure dynamic location exists/is made as required.

document.Save(path & "/" & filename)

Dim url As String = "PDFs/" & filename
Dim s As String = "'" & url + "', 'popup_window', 'width=300,height=450,left=100,top=100,resizable=yes');"
ClientScript.RegisterStartupScript(Me.GetType(), "script", s, True)

The only thing to do is to tell the popup blocker to alow popups for the site

I hope this proves useful in expanding the very useful examples

- priya

very nice.....its save my time

- Anh Huynh

I was successfully create and display PDF file from my localhost but when I move the aspx to the production server I get the error of "Access to the Path is denied"

- Mike

@Ahn Huynh

You need to talk to your hosting company/server admin about giving the IIS AppPool account WRITE access to the location where you want to create and save your PDF files.

- Anh Huynh

I can't get a WRITE access to the online server so I change the method from FileStream to MemoryStream and it works nice.
Thanks for your article! It is an open door for me.

- Terrie

I can't thank you enough for these tutorials. They are well written and extremely helpful!

One question if I may: Using the PDFWriter to add chunks and paragraphs to the document as you show above, how would you make the document READ ONLY? The only examples I've found related to this use the stamper method.

Thank you again!

- Mike


You can use the PdfWriter.SetEncryption method:
PdfWriter writer = PdfWriter.GetInstance(doc1, new FileStream(path + "/PermissionsTest.pdf", FileMode.Create));

writer.SetEncryption(PdfWriter.ENCRYPTION_AES_128, null, "mike", PdfWriter.AllowFillIn | PdfWriter.AllowScreenReaders);

- Fawad

Brilliant! Cheers

- Alan

Great series of articles thanks. Can one of the next ones cover handling form input so that we start from a standard template, insert data and save. This would obviate the need to generate the pdf from scratch.

Recent Comments

Thomas 05/03/2018 00:59
In response to I'm Not Writing A Book On Razor Pages
There's a typo on this page: = true)] should be [BindProperty(SupportsGet = true)]...

Rolf Herbert 04/03/2018 19:25
In response to I'm Not Writing A Book On Razor Pages
So is MS deprecating razor Web Pages..? Is it dead..? I wish they would stop killing things so its...

Borut 17/02/2018 12:59
In response to I'm Not Writing A Book On Razor Pages
Mike, is it possible that Web Pages and Razor Pages "live" together in one web application? I a I...

hrboyce 09/02/2018 04:44
In response to I'm Not Writing A Book On Razor Pages
Mike, First thanks for doing this but I have to ask, any chance you would consider converting one of...

aziz sallam 07/02/2018 10:18
In response to I'm Not Writing A Book On Razor Pages
u are a great man...

Satyabrata Mohapatra 31/01/2018 11:36
In response to I'm Not Writing A Book On Razor Pages
This is a great news!!!! Thanks...

tangdf 30/01/2018 07:25
In response to I'm Not Writing A Book On Razor Pages
=> { o.ConfigureFilter(new IgnoreAntiforgeryTokenAttribute()); }); The extension method does...

Obinna Okafor 30/01/2018 04:02
In response to I'm Not Writing A Book On Razor Pages
Thank you very much. I would like to see a project built from scratch using Razor Pages. And it show...

rachida Dukes 31/10/2017 13:52
In response to Customising Identity in Razor Pages
Thanks again for this wonderful tutorial. I followed all the steps in this section called: Adding...

Rachida 31/10/2017 12:06
In response to Customising Identity in Razor Pages
Thanks very much for this wonderful tutorial, it helped a lot....