PDF Exports with ASP.NET

I’ve been playing with the free PDF library iTextSharp with ASP.NET and I wanted to create a PDF document on the fly & send it to the browser via ASP.NET. iTextSharp only comes with C# console demo apps (some of which don’t work) that only write PDFs to files.

So, here’s a little ASP.NET Hello World PDF sample that you can use to get started with generating free PDFs using ASP.NET:

// other using statements goes here
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.xml;
using iTextSharp.text.html;

// standard ASP.NET code goes here, then in Page_load…

protected void Page_Load(object sender, EventArgs e)
{
// create a new memory stream to hold the document
MemoryStream m = new MemoryStream();

// create a new PDF document
Document document = new Document(PageSize.A4.Rotate(), 10, 10, 10, 10);
PdfWriter.GetInstance(document, m);

// open the document
document.Open();

// add some content
document.Add(new Paragraph(“Hello world”));

// close the document
document.Close();

// send the PDF to the browser
Response.Clear();
Response.Buffer = true;
Response.ContentType = “application/pdf”;
Response.BinaryWrite(m.ToArray());

// release the stream
m.Dispose();

// end
Response.End();
}

 

0