ASP.NET 将字节合并到单个 PDF 文档时出现 PdfReader 异常 "The document has no pages."

ASP.NET PdfReader Exception While Merging Bytes to Single PDF Document "The document has no pages."

我总共有 9 列,所有列都有字节数据。在这 9 列中,7 列具有 IMAGE 数据类型,1 列具有 VARBINARY(MAX)。这 7 列有 JPG 的字节,1 列有 PDF 的字节。最后我需要将所有内容合并到一个 pdf 中。

如上图所示,我有一个函数,我在 List(Of Byte()) 变量中发送字节我得到两列的长度,但它在突出显示的行 Using reader = New PdfReader(p) 上给我错误“文档没有页面。”。这是什么错误,我应该如何解决?

下面是我的代码:

Dim mergedpdf as byte() = nothing,listoffilebytes As List(Of Byte()) = New List(Of Byte())(), schoolname As String = ""

    Protected Sub Button1_Click(sender As Object, e As EventArgs)
        MergeandDownload(3)
    End Sub

    Sub MergeandDownload(ByVal regid As Integer)
        Using conn As New SqlConnection(constr)
            Try
                Using cmd As New SqlDataAdapter("SELECT b.schoolname,(case when a.[building] is null then '' else a.[building] end) AS building,a.[fire],a.[pollution],a.[chemical],a.[municipality],a.[traffic],a.[bylaws],a.[building_sketch],(case when a.[singlepdf] is null then '' else a.[singlepdf] end) AS singlepdf FROM [reg_documents] a inner join registration_master b on b.reg_schoolid = a.reg_schoolid where a.reg_schoolid = @regid", conn)
                    cmd.SelectCommand.Parameters.AddWithValue("@regid", regid)
                    conn.Open()
                    Using dsset As New DataSet()
                        cmd.Fill(dsset, "tabs")
                        If (dsset.Tables(0).Rows.Count > 0) Then
                            schoolname = dsset.Tables(0).Rows(0)("schoolname").ToString()
                            If (dsset.Tables(0).Rows(0)("building").ToString() <> "") Then                                    
                                listoffilebytes.Add(System.Text.Encoding.ASCII.GetBytes(dsset.Tables(0).Rows(0)("building").ToString()))
                            End If

                            If (dsset.Tables(0).Rows(0)("singlepdf").ToString() <> "") Then                                   
                                listoffilebytes.Add(System.Text.Encoding.ASCII.GetBytes(dsset.Tables(0).Rows(0)("singlepdf").ToString()))
                            End If
                            mergedpdf = concatAndAddContent(listoffilebytes)

                        End If
                    End Using
                End Using
            Catch ex As Exception
            Finally
                If ConnectionState.Open Then
                    conn.Close()
                End If
            End Try
        End Using

        If (mergedpdf.Length() > 0) Then
            Response.Clear()
            Response.Buffer = True
            Response.Charset = ""
            Response.Cache.SetCacheability(HttpCacheability.NoCache)
            Response.ContentType = "application/pdf"
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + schoolname + ".pdf")
            Response.BinaryWrite(mergedpdf)
            Response.Flush()
            Response.End()
        End If

    End Sub

    Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
    End Sub

    Public Shared Function concatAndAddContent(ByVal pdfByteContent As List(Of Byte())) As Byte()
        Using ms = New MemoryStream()
            Using doc = New Document()
                Using copy = New PdfSmartCopy(doc, ms)
                    doc.Open()
                    For Each p In pdfByteContent
                        Using reader = New PdfReader(p)
                            copy.AddDocument(reader)
                        End Using
                    Next
                    doc.Close()
                End Using
            End Using
            Return ms.ToArray()
        End Using
    End Function

我找到了解决这个问题的方法,并且如下所示。分享我的代码

将上面的库导入为:

Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
Imports iTextSharp.text
Imports System.IO
Imports iTextSharp.text.html.simpleparser
Imports iTextSharp.text.pdf
Imports System.Drawing

下面的代码会将存储在图像列中的 JPG 字节生成为 PDF,并将存储在 VARBINARY(MAX) 中的 PDF 字节生成为 PDF,然后将其全部合并到单个 PDF 文件中并下载:

Protected Sub Button1_Click(sender As Object, e As EventArgs)
        MergeandDownload(123)
    End Sub
 
    Sub MergeandDownload(ByVal regid As Integer)
        Using conn As New SqlConnection(constr)
            Try
                Using cmd As New SqlDataAdapter("SELECT b.schoolname,a.building,a.[fire] AS fire,a.[singlepdf] FROM [reg_documents] a inner join registration_master b on b.reg_schoolid = a.reg_schoolid where a.reg_schoolid = @regid", conn)
                    cmd.SelectCommand.Parameters.AddWithValue("@regid", regid)
                    conn.Open()
                    Using dsset As New DataSet()
                        cmd.Fill(dsset, "tabs")
                        If (dsset.Tables(0).Rows.Count > 0) Then
                            schoolname = Server.HtmlEncode(dsset.Tables(0).Rows(0)("schoolname").ToString())
                            Using _ms As New MemoryStream
                                Using _doc As New Document()
                                    Using _copy As New PdfCopy(_doc, _ms)
                                        _doc.Open()
 
                                        If (Not IsDBNull(dsset.Tables(0).Rows(0)("building"))) Then
                                            Dim _reader As PdfReader = New PdfReader(concatAndAddContent3(dsset.Tables(0).Rows(0)("building")))
                                            Dim n As Integer = _reader.NumberOfPages
                                            For _i As Integer = 0 To n - 1
                                                _copy.AddPage(_copy.GetImportedPage(_reader, System.Threading.Interlocked.Increment(_i)))
                                            Next
                                        End If
                                        If (Not IsDBNull(dsset.Tables(0).Rows(0)("fire"))) Then
                                            Dim _reader As PdfReader = New PdfReader(concatAndAddContent3(dsset.Tables(0).Rows(0)("fire")))
                                            Dim n As Integer = _reader.NumberOfPages
                                            For _i As Integer = 0 To n - 1
                                                _copy.AddPage(_copy.GetImportedPage(_reader, System.Threading.Interlocked.Increment(_i)))
                                            Next
                                        End If
                                        If (Not IsDBNull(dsset.Tables(0).Rows(0)("singlepdf"))) Then
                                            Dim _reader As PdfReader = New PdfReader(CType(dsset.Tables(0).Rows(0)("singlepdf"), Byte()))
                                            Dim n As Integer = _reader.NumberOfPages
                                            For _i As Integer = 0 To n - 1
                                                _copy.AddPage(_copy.GetImportedPage(_reader, System.Threading.Interlocked.Increment(_i)))
                                            Next
                                        End If
                                    End Using
                                End Using
                                mergedpdf = _ms.ToArray()
                            End Using
                        End If
                    End Using
                End Using
            Catch ex As Exception
                Response.Write(ex.ToString())
            Finally
                If ConnectionState.Open Then
                    conn.Close()
                End If
            End Try
        End Using
        If (mergedpdf.Length() > 0) Then
            Dim mst As MemoryStream = New MemoryStream(mergedpdf)
            Response.ContentType = "application/pdf"
            Response.AddHeader("content-disposition", "attachment;filename=" & schoolname & "_MergedDoc_" & DateTime.Now.ToString() & ".pdf")
            Response.Buffer = True
            mst.WriteTo(Response.OutputStream)
            Response.[End]()
        End If
    End Sub
 
    Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
    End Sub
 
    Public Function concatAndAddContent3(ByVal _strimgBytes As Byte()) As Byte()
        Using memoryStream As System.IO.MemoryStream = New System.IO.MemoryStream()
            Dim base64 As String = Convert.ToBase64String(_strimgBytes)
            newbytes = Convert.FromBase64String(base64)
            Dim image As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(newbytes)
            Dim document As Document = New Document(PageSize.A4, 0.0F, 0.0F, 0.0F, 0.0F)
            Dim writer As PdfWriter = PdfWriter.GetInstance(document, memoryStream)
            image.SetAbsolutePosition(10.0F, 10.0F)
            image.ScaleAbsolute(500.0F, 800.0F)
            document.Open()
            document.Add(image)
            document.Close()
            newbytes = memoryStream.ToArray()
            memoryStream.Close()
        End Using
        Return newbytes
    End Function