11 April 2013

Convert GridView to PDF in VB

Are you looking for ways to convert your report in GridView to a  PDF file?

I use iTextSharp and here's my working solution:


Imports System
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Web.UI.WebControls.WebParts
Imports System.Web.UI.HtmlControls
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports iTextSharp.text.html.simpleparser
Imports System.IO
Imports System.Collections
Imports System.Net


Protected Sub btnToPdf1_Click1(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnToPdf1.Click
        Response.ContentType = "application/pdf"
        Response.AddHeader("content-disposition", "attachment;filename=ContactMailingAddress.pdf")
        Response.Cache.SetCacheability(HttpCacheability.NoCache)
        Dim sw As New StringWriter()
        Dim hw As New HtmlTextWriter(sw)
        ContactMailingView.AllowPaging = False
        ContactMailingView.DataBind()
        ContactMailingView.RenderControl(hw)
        Dim sr As New StringReader(sw.ToString())
        Dim pdfDoc As New Document(PageSize.LETTER, 10.0F, 10.0F, 10.0F, 0.0F)
        Dim htmlparser As New HTMLWorker(pdfDoc)
        PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
        Dim pdfHeader As New HeaderFooter(New Phrase(Environment.NewLine + "SMARTCRM Sales Edition " + Environment.NewLine + DateTime.Now), False)
        pdfHeader.Border = Rectangle.NO_BORDER
        pdfDoc.Header = pdfHeader
        pdfDoc.Open()
        htmlparser.Parse(sr)
        pdfDoc.Close()
        Response.Write(pdfDoc)
        Response.End()
    End Sub

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



You should improve this format if you want to use it in your project or production.

No comments:

Post a Comment