Generate PDF documents on the fly using ASP.NET and iTextSharp
by
on May 13th, 2010 at 05:53 PM (3313 Views)
As part of a project I'm working on, I have the need to generate PDF documents "on the fly" and then render them back to the browser.
I was already aware of a dll module that provided this functionality, available at iTextSharp | Get iTextSharp at SourceForge.net so I thought I'd post a quick blog about how to get it working.
Firstly, you need to place the .dll file in the bin directory of your application / website.
I then created a new .aspx page, the content of which was just
The code behind was like this:-Code:<%@ Page Language="C#" CodeFile="invoicepdf.aspx.cs" Inherits="_invoicepdf" %>
Text can be added to the PDF using a variety of methods. They include:-Code:using System; using System.Web; using System.IO; using iTextSharp.text; using iTextSharp.text.pdf; public partial class _invoicepdf : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // Create instance of a new document Document doc = new Document(PageSize.A4, 10, 10, 50, 50); // Change the content type to application/pdf !Important HttpContext.Current.Response.ContentType = "application/pdf"; // Get Instance of pdfWriter to be able to create the document in the OutputStream PdfWriter.GetInstance(doc, HttpContext.Current.Response.OutputStream); // Open the document to be able to write to it doc.Open(); // Create a simple paragraph to add to the document Paragraph para = new Paragraph("This is a paragraph"); // Add the paragraph to the document doc.Add(para); // Close the document, rendering it to the browser doc.Close(); } }
Chunk
Paragraph
Phrase
You can also apply fonts and styles to an instance of each of these objects to use italics, underline etc.









Email Blog Entry