Download Invoice Stored in Table in PDF Format

Posted: November 9, 2011 in ASP.Net

Many people store PDF invoices in their tables as binary data.  To extract and save this as a PDF document, you can try the following:
Page1.apsx (Get Invoice)

Microsoft.Practices.EnterpriseLibrary.Data.Sql.SqlDatabase DAL = 
new Microsoft.Practices.EnterpriseLibrary.Data.Sql.SqlDatabase(YourConnectionString);
System.Data.Common.DbCommand dbgCommand = DAL.GetStoredProcCommand("YourProcedureName");
DAL.AddInParameter(dbgCommand, "@InvoiceNo", System.Data.SqlDbType.Int, InvoiceNo);
IDataReader rdr = DAL.ExecuteReader(dbgCommand);
try
{
  System.Text.StringBuilder _sb = new System.Text.StringBuilder();
  while (rdr.Read())
  {
    Session["sInvoiceData"] = rdr["YourInvoiceDataColumn"];
    Session["sInvoiceFilename"] = rdr["YourInvoiceFilenameColumn"].ToString();
    _sb.Append("window.open('Page2.aspx','_self',");
    _sb.Append("'toolbar=0,menubar=0,resizable=yes')");
  }
  ScriptManager.RegisterStartupScript(Page, Page.GetType(), "winOpen", _sb.ToString(), 
  true);
}
finally
{
  rdr.Close();
  rdr.Dispose();
}

Page2.apsx (Download Invoice)

try
{
  Response.ContentType = "application/pdf";
  Response.AddHeader("content-disposition", "attachment; filename=" + 
  Session["sInvoiceFilename"]);
  Response.BinaryWrite((byte[])Session["sInvoiceData"]);
  Session["sInvoiceData"] = null;
  Session["sInvoiceFilename"] = null;
}
catch (System.Threading.ThreadAbortException exThread)
{
  // Do nothing
}
catch (Exception ex)
{
  // Catch exception
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s