Export ASP.Net DataList with Image to PDF using C# and VB.Net

Last Reply 6 months ago By pandeyism

Posted 6 months ago

Hi,

I am not able export a datalist with image to pdf.

Error:

An exception of type 'System.FormatException' occurred in mscorlib.dll but was not handled in user code

Additional information: Input string was not in a correct format.

The  code  is  also attached. Please elp

                        <asp:DataList ID="Datalist9" RepeatColumns="2" runat="server" >
                            <ItemTemplate>
                                <table align="center" width="570px" style="line-height: 25px;">
                                    <tr>
                                        <td valign="top" align="center" style='<%# "background-image:url(http://amer.sehteqtpa.ae/Images/" + Eval("insuranceCompany") + ".png); background-repeat:no-repeat; background-position:center top; padding:20px; height:750px;"%>'>
                                            <table align="center" width="100%" style="line-height: 25px;">
                                                <tr>
                                                    <td align="center" colspan="9" style="height: 50px;"></td>
                                                </tr>
                                                <tr>
                                                    <td align="left"></td>
                                                    <td></td>
                                                    <td colspan="6" align="left"></td>
                                                    <td rowspan="7" align="right" style="padding-left: 10px; padding-top: 5px;" valign="bottom">
                                                    <div
                                                            style="border-radius: 5px; border: 2px solid White; background-color: White; width: 80px;">
                                                            <asp:Image ID="imgPicture" runat="server" CssClass="image" ImageUrl="" Width="80px"
                                                                Height="80px"></asp:Image>
                                                        </div>
                                                    </td>
                                                </tr>
                                                
                                            </table>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td style="height: 15px;"></td>
                                    </tr>
                                </table>
                                <table style="display: none;">
                                    <tr>
                                        <td align="left">Staff No
                                        </td>
                                        <td>:
                                        </td>
                                        <td align="left">
                                            <asp:Label ID="Label6" Text='<%# DataBinder.Eval(Container.DataItem, "Ecode")%>'
                                                runat="server"></asp:Label>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td colspan="3" style="height: 25px;"></td>
                                    </tr>
                                </table>
                            </ItemTemplate>                          
                        </asp:DataList>

 

            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            Datalist9.RenderControl(hw);
            StringReader sr = new StringReader(sw.ToString());
            Document pdfDoc = new Document(PageSize.A2, 7f, 7f, 7f, 0f);
            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
            if (!Directory.Exists(Server.MapPath("~/Documents/Pdf")))
            {
                Directory.CreateDirectory(Server.MapPath("~/Documents/Pdf/"));
            }
            string path_name = Server.MapPath("~/Documents/Pdf/" + "sample1.pdf");

            PdfWriter.GetInstance(pdfDoc, new FileStream(path_name, FileMode.OpenOrCreate));
            //PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
            pdfDoc.Open();
            htmlparser.Parse(sr);
            pdfDoc.Close();

The  error   is  on  the   line

 htmlparser.Parse(sr);

You are viewing reply posted by: pandeyism 6 months ago.
Posted 6 months ago

Hi salini,

Refer below sample.

HTML

<asp:DataList ID="DataList1" RepeatColumns="2" runat="server">
    <ItemTemplate>
        <table>
            <tr>
                <td><div><asp:Image ID="imgPicture" runat="server" CssClass="image" ImageUrl='<%# Eval("Path", GetUrl("{0}")) %>'></asp:Image></div></td>
            </tr>
            <tr>
                <td align="left">Name</td>
                <td>:</td>
                <td><asp:Label ID="Label14" Text='<%# DataBinder.Eval(Container.DataItem, "Name")%>' runat="server"></asp:Label></td>
            </tr>
            <tr>
                <td align="left">Id</td>
                <td>:</td>
                <td colspan="6" align="left"><asp:Label ID="Label7" Text='<%# DataBinder.Eval(Container.DataItem, "Id")%>' runat="server"></asp:Label></td>
            </tr>
        </table>
    </ItemTemplate>
</asp:DataList>
<asp:Button Text="ExportToPdf" runat="server" OnClick="PDF_Export" />

Namespaces

C#

using System.Data;
using System.IO;
using System.Data.SqlClient;
using System.Configuration;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;

VB.Net

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

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString))
        {
            using (SqlCommand cmd = new SqlCommand("select  TOP 2 Id, Name, Path from tblFilespath order by ID", con))
            {
                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    DataTable dt = new DataTable();
                    da.Fill(dt);
                    DataList1.DataSource = dt;
                    DataList1.DataBind();
                }
            }
        }
    }
}

protected string GetUrl(string imagepath)
{
    string[] splits = Request.Url.AbsoluteUri.Split('/');
    if (splits.Length >= 2)
    {
        string url = splits[0] + "//";
        for (int i = 2; i < splits.Length - 1; i++)
        {
            url += splits[i];
            url += "/";
        }
        return url + imagepath;
    }
    return imagepath;
}

protected void PDF_Export(object sender, EventArgs e)
{
    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
    DataList1.RenderControl(hw);
    StringReader sr = new StringReader(sw.ToString());
    Document pdfDoc = new Document(PageSize.A2, 7f, 7f, 7f, 0f);
    HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
    PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
    pdfDoc.Open();
    htmlparser.Parse(sr);
    pdfDoc.Close();
    Response.Write(pdfDoc);
    Response.End();
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        Using con As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("constr").ConnectionString)
            Using cmd As SqlCommand = New SqlCommand("select  TOP 2 Id, Name, Path from tblFilespath order by ID", con)
                Using da As SqlDataAdapter = New SqlDataAdapter(cmd)
                    Dim dt As DataTable = New DataTable()
                    da.Fill(dt)
                    DataList1.DataSource = dt
                    DataList1.DataBind()
                End Using
            End Using
        End Using
    End If
End Sub

Protected Function GetUrl(ByVal imagepath As String) As String
    Dim splits As String() = Request.Url.AbsoluteUri.Split("/"c)
    If splits.Length >= 2 Then
        Dim url As String = splits(0) & "//"
        For i As Integer = 2 To splits.Length - 1 - 1
            url += splits(i)
            url += "/"
        Next
        Return url & imagepath
    End If
    Return imagepath
End Function

Protected Sub PDF_Export(ByVal sender As Object, ByVal e As EventArgs)
    Response.ContentType = "application/pdf"
    Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf")
    Response.Cache.SetCacheability(HttpCacheability.NoCache)
    Dim sw As StringWriter = New StringWriter()
    Dim hw As HtmlTextWriter = New HtmlTextWriter(sw)
    DataList1.RenderControl(hw)
    Dim sr As StringReader = New StringReader(sw.ToString())
    Dim pdfDoc As Document = New Document(PageSize.A2, 7.0F, 7.0F, 7.0F, 0.0F)
    Dim htmlparser As HTMLWorker = New HTMLWorker(pdfDoc)
    PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
    pdfDoc.Open()
    htmlparser.Parse(sr)
    pdfDoc.Close()
    Response.Write(pdfDoc)
    Response.End()
End Sub

Screenshot