asp.netitextpdfmerger

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


I am having total 9 columns, all are having bytes data. Out of these 9 columns, 7 columns have IMAGE datatype & 1 column have VARBINARY(MAX). These 7 columns have bytes for JPG, and 1 column have bytes for PDF. Finally I need to merge all in single pdf. Error on Highlighted Line

As shown in above image, I have function where I am sending the bytes in List(Of Byte()) variable I am getting length of two columns but it's giving me error on highlighted line Using reader = New PdfReader(p) as "The document has no pages.". What is this error and how should I resolve it?

below is my code:

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

Solution

  • I found solution to this and got it worked as below. Sharing my code

    Import library above as :

    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
    

    Code below will generate JPG bytes stored in Image column to PDF & PDF bytes stored in VARBINARY(MAX) to PDF then merge it all in single PDF file & Download :

    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