LinqPad – Get Pdf from binary column
A friend asked me to share this technique (which rocks!) for a simple way to pull a pdf from a table without writing an application to do it. It has saved me a lot of time when I need to get to a stored pdf quickly.
LinqPad (which if you do any Linq, and in this case even if you just need to get to a binary object) is a must-have program that allows you to do this.
Here is the simple code snippet that pulls the pdf, saves it to a file, and opens it. You have to connect your database on the top right, and select “C# Statements” in the middle drop down list:
string id = "60821 003"; string dir = "C:\\TempDocs"; // create output directory Directory.CreateDirectory(dir); // create output filename string outputPDFFile = Path.Combine(dir, id + ".pdf"); // find the record we want (you have to be connected // to the database you want to search, and // PDFDocuments below must match the table you are pulling data from var mypdf = (from q2 in PDFDocuments where q2.PrintBatchId == id select q2); // above returns only one record, so below I use SingleOrDefault to get that record. // otherwise here you could iterate through the records... // the ".Pdf portion pf this is the column name of the pdf binary data in the table File.WriteAllBytes(outputPDFFile, mypdf.SingleOrDefault().Pdf.ToArray()); // this part opens up the pdf for viewing / verifying I have the right one System.Diagnostics.Process proc = new System.Diagnostics.Process(); proc.EnableRaisingEvents = false; proc.StartInfo.FileName = outputPDFFile; proc.Start();