Creating PDF Documents in ASP.Net
This article will quickly show you how to create pdf documents in ASP.Net. To get started go to http://itextsharp.sourceforge.net/ and download the iTextSharp library. Now add the library to your web site. We can now begin creating a pdf document.
Step 1. Add a new web form to your website.
Step 2. Place the following at the top of your code behind file:
using iTextSharp.text;
using iTextSharp.text.pdf;
Step 3. Finally place the following in the Page_Load event handler:
// Start pdf writer
MemoryStream ms = new MemoryStream();
Document document = new Document();
PdfWriter.GetInstance(document, ms);
// Open the document for writing
document.Open();// Add a paragraph
Paragraph paragraph = new Paragraph("Hello World");
document.Add(paragraph);
// Close the document
document.Close();
// Output the file
Response.ContentType = "application/pdf";
Response.Clear();
Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
Response.End();
Obviously this is a very basic example but the iTextSharp is not too well documented for ASP.Net (c#) since it was innitially targetted for Java users.
Below is an example of adding an image to your pdf document (replace the path occordingly):
// Add an image
Image logo = Image.GetInstance(Server.MapPath("~/Images/Image.jpg"));
logo.ScaleAbsolute(100, 16);
document.Add(logo);
The next example shows how you can add a new font and some text which uses that font:
// Arial font
BaseFont arial = BaseFont.CreateFont(Server.MapPath("~/Fonts/Arial.ttf"), BaseFont.WINANSI, BaseFont.EMBEDDED);
// Add a paragraph
Paragraph paragraph = new Paragraph();
paragraph.Add(new Chunk("Text", new Font(arial, 14, Font.NORMAL, new Color(0, 125, 195))));
website.Add(new Chunk("More Text", new Font(arial, 14, Font.NORMAL)));
document.Add(paragraph);
Tables are also very simple to do. To add a table you create an instance of the Table class passing the number of columns you wish your table to have and then add it to the document as you have done above:
Table table = new Table(2); // 2 columns
table.AddCell(new Cell("Row 1: Column: 1"));
table.AddCell(new Cell("Row 1: Column: 2"));
table.AddCell(new Cell("Row 2: Column: 1"));
table.AddCell(new Cell("Row 2: Column: 2"));
document.Add(table);
The final example shows how you can add a new page:
// Add a new page
document.NewPage();
I hope this helps you grasp the basics of creating pdf documents in asp.net.