Results 1 to 3 of 3

Thread: datagrid output to pdf

  1. #1
    dubsdj is offline VB.NET Forum Newbie
    .NET Framework
    .NET 4.5
    Join Date
    Mar 2017
    Posts
    2
    Reputation
    0

    datagrid output to pdf

    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()

  2. #2
    jmcilhinney's Avatar
    jmcilhinney is offline VB.NET Forum Moderator
    .NET Framework
    .NET 4.0
    Join Date
    Aug 2004
    Location
    Sydney, Australia
    Posts
    13,801
    Reputation
    1705
    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.

  3. #3
    dubsdj is offline VB.NET Forum Newbie
    .NET Framework
    .NET 4.5
    Join Date
    Mar 2017
    Posts
    2
    Reputation
    0
    Thank you I will try this

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •