Tuesday, June 10, 2008

PDF Read, Binary Save

To read a pdf file and store it as an image in DB..

string path = @"\test.pdf";

// Open the stream and read it..
using (FileStream fs1 = File.Open(path, FileMode.Open))
{
byte[] b = new byte[fs1.Length];
while (fs1.Read(b, 0, b.Length) > 0)
{
SqlConnection conn = new SqlConnection();
string env = System.Configuration.ConfigurationManager.AppSettings["KeyValue"];
conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings[env].ConnectionString;

SqlCommand command = new SqlCommand("dbo.save_pdf", conn);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("@pdf", b);
try
{
conn.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
conn.Close();
}
}

}

To read an Image from DB and display it in a browser...a very crude way to do, but works!

DataSet ds = _PDF.readPDf(1);
byte[] b = (byte[])ds.Tables[0].Rows[0][9];
System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(b);
memoryStream.Position = 0;
Response.ContentType = "application/pdf"; //Instead of pdf, if mentioned doc, then a doc
will open..
Response.BinaryWrite(b);
Response.End();

No comments: