Create PDFs in ASP.NET - getting started with iTextSharp

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.Open();

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

doc1.Close();

 

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.Open();

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

doc.Close();

 

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: Sunday, October 12, 2008 11:26 AM
Last Updated: Saturday, April 12, 2014 1:37 PM
Posted by: Mikesdotnetting
Total Views to date: 370263

46 Comments

Friday, March 6, 2009 11:57 AM - Nilesh

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

Wednesday, March 18, 2009 5:43 AM - Kirun

thanks for the nice article

Friday, April 10, 2009 1:53 AM - Wu

Good example for newbie

Monday, October 12, 2009 5:39 AM - jigar

i want to create 2 pages

Monday, October 12, 2009 7:30 AM - Mike

@jigar

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

Monday, October 12, 2009 8:11 PM - 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!

Monday, October 12, 2009 8:35 PM - Mike

@David

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.

Friday, October 16, 2009 7:25 PM - NA

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

Saturday, October 17, 2009 8:41 AM - Mike

@NA

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.

Saturday, October 24, 2009 7:25 PM - NitinK

Nice Article !!!

Saturday, October 31, 2009 12:50 PM - 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");
conv.SavePDF("new.pdf");

Sunday, November 1, 2009 8:58 AM - Mike

@Jason

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

Monday, November 2, 2009 1:56 PM - 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!

Monday, November 2, 2009 7:58 PM - Mike

@Gareth

Nice spot! I didn't notice that option.

Friday, February 12, 2010 6:57 PM - Mike

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

http://www.visualstudiotutorial.net

Monday, February 15, 2010 3:02 PM - Kieran

Thanks for this series of articles, very helpful and informative

Wednesday, February 17, 2010 10:30 PM - Peter Ingraham

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

Thursday, February 18, 2010 9:55 AM - 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.

Wednesday, May 19, 2010 10:57 AM - 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 http://sourceforge.net/projects/pdfsharp/

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.

Friday, July 2, 2010 11:26 AM - 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. :)

Sunday, July 18, 2010 3:29 PM - Ken

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

Thursday, August 5, 2010 3:01 PM - Denis

Thanks very good article

Friday, October 22, 2010 2:01 PM - 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?

Tuesday, November 2, 2010 6:53 AM - junior developer

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

Tuesday, November 9, 2010 2:14 PM - 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 http://www.itextpdf.com/terms-of-use/index.php

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

Regards,
Jacob

Friday, November 26, 2010 5:54 AM - Sakhi

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

Saturday, December 11, 2010 9:16 PM - 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.
Maurits

Friday, April 29, 2011 5:20 PM - Emmanuel

Helped a lot for starting quickly ! ;-)

Friday, April 29, 2011 5:21 PM - Emmanuel

Good job ! ;-)

Sunday, June 12, 2011 2:31 PM - vaishali

beautiful post

Wednesday, July 20, 2011 10:55 AM - robsta

Hi Mike,

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

Wednesday, July 20, 2011 4:40 PM - Tung

That great help, thanks alot man!!

Friday, August 5, 2011 3:53 PM - Nguyen

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

Saturday, March 31, 2012 9:14 PM - 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!

Thursday, September 6, 2012 6:16 PM - 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.

Thursday, September 6, 2012 8:25 PM - Mike

@NA,

You can get the previous version (4.1.6 - the version that all my articles are based on) from Nuget: http://nuget.org/packages/iTextSharp-LGPL.

Thursday, December 6, 2012 4:21 PM - Dylan

Hi,

Do the itextsharp able to use in VS2010 ?

Best Regards,
Dylan

Wednesday, January 9, 2013 1:38 PM - michele

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

grat work! many thanks!

Monday, February 4, 2013 5:45 AM - FALGUNI

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

Wednesday, February 6, 2013 7:17 AM - pavan

Nice article ..its very useful ..thanks

Wednesday, February 27, 2013 11:30 AM - Vishnu

it is useful code for me

Friday, May 10, 2013 4:51 AM - Lau

Thanks for sharing! ;)

Monday, May 27, 2013 8:28 PM - dan

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

Thanks.

Tuesday, July 16, 2013 12:57 PM - ahmad

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

Friday, September 6, 2013 3:11 PM - 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!

Thursday, June 5, 2014 3:13 PM - John

Very useful.

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

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

response.redirect("xxx")

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 = "window.open('" & 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
Add your comment

If you have any comments to make about this article, please use this form to do so. Make sure that your comment relates specifically to the article above. More general comments can be posted through the form on the Contact page.

Please note, all comments are moderated, and some may not be published. The kind of things that will ensure your comment is deleted without ever seeing the light of day are as follows:

  • Not relevant to the article
  • Gratuitous links to your own site or product
  • Anything abusive or libellous
  • Spam
  • Anything in a language I don't understand including gibberish.

I do not pass email addresses on to spammers, so a valid one will assist me in responding to you personally if required.

Recent Comments

Gautam 11/20/2014 8:01 AM
In response to I'm Writing A Book On WebMatrix
Hello Mike, I read your book, loved it! However, I have a few request/suggestions: 1) an example...

Bret Dev 11/19/2014 8:39 PM
In response to The Difference Between @Helpers and @Functions In WebMatrix
Excellent post! One concern - where can you place global @Functions code within an MVC project to Is...

Rob Farquharson 11/19/2014 4:28 PM
In response to iTextSharp - Links and Bookmarks
How can I place text at an absolute position on the page? Also, how can I rotate text?...

Andy 11/17/2014 8:08 PM
In response to MVC 5 with EF 6 in Visual Basic - Sorting, Filtering and Paging
Hello I'm testing your sorting instructions above. This is great and I was able to get it to work...

Gautam 11/17/2014 5:51 PM
In response to WebMatrix - Database Helpers for IN Clauses
Hi Mike, I am very new to programming: In the above example if I want to use a delete button the...

donramon 11/17/2014 3:22 PM
In response to Entity Framework 6 Recipe - Alphabetical Paging In ASP.NET MVC
Congratulations on your new website look and the excellent articles. Thank you!...

Gautam 11/17/2014 11:26 AM
In response to Looking At The WebMatrix WebGrid
Hi Mike, I add the jquery script at the end of my html file.. when ajax attribute is added to the be...

Chet Ripley 11/15/2014 6:57 PM
In response to Adding A New Field
It appears the command is case sensitive. I had the same issue as Cameron. When I changed the to it...

Alvin 11/14/2014 12:49 PM
In response to Razor Web Pages E-Commerce - Adding A Shopping Cart To The Bakery Template Site
Great article Mike! When do you plan to extend the bakery shopping cart beyond this point?...

Gautam 11/14/2014 10:16 AM
In response to Web Pages - Efficient Paging Without The WebGrid
to get the count can we use only the below sql, why to join category and author table var sql =...