Andreas Utzinger
Andreas Utzinger

Reputation: 402

Converting Blob Data (PDF) from SQL Database to a PDF-File

In my Datebase Table the PDFs are saved as Blob Data, example:

enter image description here

What I'm trying to do now is to create a PDF file out of this data.

My code is like that:

SqlConnection con = new SqlConnection(connectionString);
        con.Open();
        if (con.State == ConnectionState.Open)
        { 
            string query = // fancy SELECTION string goes here... reads only one by the way

            using (SqlCommand command = new SqlCommand(query, con))
            {
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        Byte[] bytes = (Byte[])reader["File BLOB-Contents"];
                        Console.WriteLine(bytes.Length); // prints the correct file size in Bytes
                        using (FileStream fstream = new FileStream(@"C:\Users\myUsername\Desktop\test3.pdf", FileMode.OpenOrCreate, FileAccess.ReadWrite))
                        {
                            fstream.Write(bytes, 0, bytes.Length);
                        }
                    }
                }
            }
        }

The pdf gets created in the end but the problem is, that I can't open it. I get the following (German) message in Adobe Reader:

Database View

Anyone here an idea or is there something I'm doing wrong? The file size is ok. It's not 0.

Upvotes: 0

Views: 3434

Answers (1)

TWong
TWong

Reputation: 101

When we storing something like a PDF file in SQL Server, I would recommend converting the PDF file into a byte array and then put it into a column that is varbinary(max) instead of image.

Honestly, I think the recommended way of doing this is having the file reside not in the DB, but instead in either local file storage or some storage service like an AWS S3 bucket and have the location be stored in the database instead.

Upvotes: 1

Related Questions