首页 > 解决方案 > 使用 C# 从 SQL Server 数据库显示 PDF

问题描述

我想显示一个.pdf我已经上传到我的 SQL Server 数据库中的内容,但我需要将其显示在表单中并直接从数据库中显示(而不将其保存到我的计算机中)。

我正在使用 SQL Server 2012 和 Visual Studio 2019。

我尝试使用 AxAcroPdf,但我不知道它是如何工作的。

DataTable dt = new DataTable();
SqlCommand show = new SqlCommand("SELECT documento FROM table WHERE p = '" + contentP + "'AND n = '" + contentN + "' AND documento is not null;", con);
SqlDataAdapter adapter = new SqlDataAdapter(show);
adapter.Fill(dt);

if (dt.Rows.Count > 0)
{
   byte[] ap = (byte[])dt.Rows[0]["documento"];
   MemoryStream ms = new MemoryStream(ap);

   var axacropdf = new AcroPDFLib.AcroPDF();
   axacropdf.LoadFile(ap.ToString());
   axacropdf.setShowToolbar(true);
   axacropdf.setView("Fit");
}

标签: c#databasepdfsql-server-2012visual-studio-2019

解决方案


根据我的测试,AcroPDF 似乎不支持加载字节数组以在 winform 中显示 pdf。

我找到了另一种直接从数据库中显示 pdf 的方法。

首先,请尝试安装以下 nuget-> ceTe.DynamicPDF.Viewer.NET

其次,请添加一个pdfviewer从工具箱调用的控件。

第三,您可以尝试以下代码从winform中的字节数组加载pdf。

        string connstr = "connstr";
        SqlConnection connection = new SqlConnection(connstr);
        connection.Open();
        string sql = "select * from PdfReader";
        SqlCommand cmd = new SqlCommand(sql, connection);
        SqlDataAdapter adapter = new SqlDataAdapter(cmd);
        DataTable table = new DataTable();
        adapter.Fill(table);
        if (table.Rows.Count > 0)
        {
            byte[] ap = (byte[])table.Rows[0]["Content"];
            PdfDocument pdfDocument = new PdfDocument(ap);
            pdfViewer1.Open(pdfDocument);
        }

结果:

在此处输入图像描述


推荐阅读