datagrid output to pdf

dubsdj

New member
Joined
Mar 8, 2017
Messages
2
Programming Experience
3-5
Hi I'm trying to write my datagrid view to a pdf. I have done the following code but it just says the document is empty. Any idea?
        Response.ContentType = "application/pdf"
        Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf")
        Response.Cache.SetCacheability(HttpCacheability.NoCache)
        Dim sw As New StringWriter()
        Dim hw As New HtmlTextWriter(sw)
               
        DataGrid1.AllowPaging = False
        DataGrid1.DataBind()
        DataGrid1.RenderControl(hw)
        
        Dim sr As New StringReader(sw.ToString())
        Dim pdfDoc As New Document(PageSize.A4, 10.0F, 10.0F, 10.0F, 0.0F)
        Dim htmlparser As New HTMLWorker(pdfDoc)
        PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
        pdfDoc.Open()
        htmlparser.Parse(sr)
        pdfDoc.Close()
        Response.Write(pdfDoc)
        Response.End()
 
You should check what 'sw.ToString()' produces but I'd guess that your 'HtmlTextWriter' is not being flushed. I would suggest that you dispose objects like that as soon as you're done with them, which will ensure that they can't interfere with subsequent code. You should employ 'Using' blocks to create an destroy disposable objects. In your case, I'd rewrite your code like this:
Using sw As New StringWriter()
    Using hw As New HtmlTextWriter(sw)
        DataGrid1.AllowPaging = False
        DataGrid1.DataBind()
        DataGrid1.RenderControl(hw)
    End Using

    Using sr As New StringReader(sw.ToString())
        Dim pdfDoc As New Document(PageSize.A4, 10.0F, 10.0F, 10.0F, 0.0F)
        Dim htmlparser As New HTMLWorker(pdfDoc)
        PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
        pdfDoc.Open()
        htmlparser.Parse(sr)
        pdfDoc.Close()
        Response.Write(pdfDoc)
        Response.End()
    End Using
End Using
You may be able to employ a 'using' block for 'pdfDoc' and/or 'htmlparser' too, but I'm not familiar with those types. Any disposable object that is only used within a closed scope like that should be created and destroyed that way.
 
Back
Top