简体   繁体   English

将 Blob 数据 (PDF) 从 SQL 数据库转换为 PDF 文件

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

In my Datebase Table the PDFs are saved as Blob Data, example:在我的数据库表中,PDF 保存为 Blob 数据,例如:

在此处输入图像描述

What I'm trying to do now is to create a PDF file out of this data.我现在要做的是从这些数据中创建一个 PDF 文件。

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. pdf 最终被创建,但问题是,我无法打开它。 I get the following (German) message in Adobe Reader:我在 Adobe Reader 中收到以下(德语)消息:

数据库视图

Anyone here an idea or is there something I'm doing wrong?这里有人有想法还是我做错了什么? The file size is ok.文件大小还可以。 It's not 0.不是0。

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 .当我们在 SQL 服务器中存储类似 PDF 文件时,我建议将 PDF 文件转换为字节数组(然后将其放入一个image列,而不是 varmax varbinary(max)

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.老实说,我认为推荐的做法是让文件不在数据库中,而是在本地文件存储或 AWS S3 存储桶等存储服务中,并将位置存储在数据库中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM