Print Panel with Image from Database using ITextSharp in ASP.Net

RichardSa
 
on Nov 07, 2022 09:48 PM
Sample_406162.zip
1089 Views

I have two buttons. One button sends document to mail and the other button print the document (download as PDF file). They both do these functions but there is something missing.

After preparing a receipt on my web page it automatically generates a QR code for that receipt, which then navigates to next page for printing. When printing, it should print the QR code image alongside the document. That is, the QR code image should be on the document when it prints or when it sends to mail, BUT IT DOES NOT HAVE THE QR CODE WHEN IT PRINTS OR SENDS TO EMAIL.

protected void Button3_Click(object sender, EventArgs e)
{
    SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\Dataregister.mdf;Integrated Security = True");
    con.Open();
    SqlCommand cmd = new SqlCommand();
    cmd.CommandText = "SELECT * FROM InvoiceTable WHERE Invoice_no = '" + Session["InvoiceID"] + "'";
    cmd.Connection = con;
    SqlDataAdapter sda = new SqlDataAdapter();
    DataSet ds = new DataSet();
    sda.SelectCommand = cmd;
    sda.Fill(ds, "detail");
    if (ds.Tables[0].Rows.Count > 0)
    {
        byte[] image = (byte[])ds.Tables[0].Rows[0]["logo"];
        imgFileUpload.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(image);
 
        string fileName = "Invoice" + DateTime.Now.ToString() + ".pdf";
 
        byte[] QRBytes = GetQRCodeBytes(ToAbsoluteUrl("/invoiceverificationtemp.aspx") + "?Id=" + Request.QueryString["InvoiceID"]);
        Image1.ImageUrl = "data:image/jpg;base64," + Convert.ToBase64String(QRBytes);
        var ImgUrl = Image1.ImageUrl;
        var ImagUrl = imgFileUpload.ImageUrl;
        // Write image as file to folder.
        File.WriteAllBytes(Server.MapPath("qrimg.jpg"), QRBytes);
        File.WriteAllBytes(Server.MapPath("logo.jpg"), image);
        // convert and set absolute url in image.
        Image1.ImageUrl = GetUrl("qrimg.jpg");
        imgFileUpload.ImageUrl = GetUrl("logo.jpg");
 
 
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        Panel1.RenderControl(hw);
        StringReader sr = new StringReader(sw.ToString());
        Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 10f);
        PdfWriter PdfWriter = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
        HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
        htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
        ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
        cssResolver.AddCssFile(Server.MapPath("~/css/style2.css"), true);
        IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(pdfDoc, PdfWriter)));
        var worker = new XMLWorker(pipeline, true);
        var xmlParse = new XMLParser(true, worker);
        pdfDoc.Open();
        xmlParse.Parse(sr);
        xmlParse.Flush();
        pdfDoc.Close();
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=" + fileName + ";");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Write(pdfDoc);
        // Delete the temp image.
        File.Delete(Server.MapPath("qrimg.jpg"));
        File.Delete(Server.MapPath("logo.jpg"));
        Image1.ImageUrl = ImgUrl;
        imgFileUpload.ImageUrl = ImagUrl;
        Response.End();
    }
}

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Dec 05, 2022 10:55 PM

Hi RichardSa,

Refer below example.

HTML

<asp:Panel ID="Panel1" runat="server">
    <div class="parent" style="margin-left: auto; margin-right: auto; padding: 10px; display: flex; background-color: #ffffff; border: 1px solid #ccc; width: 100%;">
        <div class="child" id="midcont" style="width: 100%; height: auto; padding: .5rem;">
            <div style="background-color: #DCDFE6; height: 4%;">
                <center>
                    <div class="heading" style="font-size: 11pt; font-weight: bolder; position: center; margin-top: 0%;">
                        <asp:Label ID="Label4" runat="server" Font-Bold="true" Font-Size="11pt" ForeColor="#000066" Text="INVOICE"></asp:Label>
                    </div>
                </center>
            </div>
            <hr />
            <div>
                &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <asp:Label ID="Label3" runat="server" Text="Invoice N°:" Font-Size="10pt" Font-Bold="true"></asp:Label>&nbsp;
                    <asp:Label ID="lblprefix" runat="server" Font-Size="9pt" Text="4107750829"></asp:Label>
            </div>
            <asp:GridView ID="Gridview1" runat="server" Font-Size="10pt" AutoGenerateColumns="False" Style="max-width: 100%" RowStyle-Height="40px" HeaderStyle-ForeColor="#00003D"
                BorderStyle="None" GridLines="None" Height="50px" HeaderStyle-Height="28px" HeaderStyle-BackColor="#D3D9E5">
                <Columns>
                    <asp:BoundField DataField="Item" HeaderText="ITEM DESCRIPTION" ItemStyle-Width="70%" />
                    <asp:BoundField DataField="Qty" HeaderText="QUANTITY" ItemStyle-Width="15%" />
                    <asp:BoundField DataField="Rate" HeaderText="RATE" ItemStyle-Width="19%" />
                    <asp:BoundField DataField="Amount" HeaderText="AMOUNT" ItemStyle-Width="20%" />
                </Columns>
                <HeaderStyle Height="25px" />
            </asp:GridView>
            <hr /><br />
            <div class="pict" style="float: left; margin-left: 5%; margin-bottom: 3%;">
                <asp:Image ID="img1" runat="server" Width="80px" Height="80px" />
            </div>

            <div class="total" style="float: right; width: 240px; font-size: 9pt;">
                <asp:Label ID="Label1" runat="server" Font-Bold="true" Text="TOTAL:"></asp:Label>
                <asp:Label ID="Label17" runat="server" Text="NGN"></asp:Label>&nbsp;
                <asp:Label ID="lblTotal" runat="server" Font-Size="9pt" Text="1215000"></asp:Label>
                <br /><br />
                <asp:Label ID="Label5" runat="server" Font-Bold="true" Text="VAT (%):"></asp:Label>&nbsp;&nbsp;
                    <asp:Label ID="vatlbl" runat="server" Font-Size="9pt" Text="5"></asp:Label>
                <br /><br />
                <div style="background-color: #D3D9E5; height: 30px; width: 100%;">
                    <asp:Label ID="Label6" runat="server" Font-Bold="true" Text="GRAND TOTAL:"></asp:Label>
                    <asp:Label ID="Label18" runat="server" Text="NGN"></asp:Label>&nbsp;<asp:Label ID="lblGrandTotal" runat="server" Font-Size="9pt" Text="1275750"></asp:Label>
                </div>
                <br /><br /><br /><br /><br />
            </div>
            <br /><br /><br /><br />
        </div>
        <br /><br />
    </div>
</asp:Panel>
<br />
<div>
    <asp:Button ID="Button2" runat="server" CssClass="btn btn-primary" Font-Size="Small" BackColor="SteelBlue" Text="Print in PDF" OnClick="Button2_Click" />
</div>

Namespaces

using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
using iTextSharp.tool.xml.html;
using iTextSharp.tool.xml.parser;
using iTextSharp.tool.xml.pipeline.css;
using iTextSharp.tool.xml.pipeline.end;
using iTextSharp.tool.xml.pipeline.html;

Code

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[4] { new DataColumn("Item"), new DataColumn("Qty"),
                                                new DataColumn("Rate"), new DataColumn("Amount") });
        dt.Rows.Add("Supply Of Electrical Equipments", "20", "3000", "60000");
        dt.Rows.Add("Construction of Bore Hole", "2", "350000", "700000");
        dt.Rows.Add("Construction of Fish Pond", "7", "45000", "315000");
        dt.Rows.Add("Purcahse of Water Pump", "2", "70000", "140000");
        Gridview1.DataSource = dt;
        Gridview1.DataBind();
    }
}

public override void VerifyRenderingInServerForm(Control control)
{
        
}

protected void Button2_Click(object sender, EventArgs e)
{
    string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
    using (SqlConnection con = new SqlConnection(conString))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT TOP 1 * FROM tblFiles WHERE ContentType = 'image/jpeg'", con))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
            {
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    Byte[] bytes = (Byte[])dt.Rows[0]["Data"];
                    string base64String = Convert.ToBase64String(bytes);
                    File.WriteAllBytes(Server.MapPath("qrimg.jpg"), bytes);
                    img1.ImageUrl = GetUrl("qrimg.jpg");
                }
            }

        }
    }

    StringWriter sw = new StringWriter();
    HtmlTextWriter hw = new HtmlTextWriter(sw);
    Panel1.RenderControl(hw);
    StringReader sr = new StringReader(sw.ToString());
    Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 10f);
    PdfWriter PdfWriter = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
    HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
    htmlContext.SetTagFactory(Tags.GetHtmlTagProcessorFactory());
    ICSSResolver cssResolver = XMLWorkerHelper.GetInstance().GetDefaultCssResolver(false);
    //cssResolver.AddCssFile(Server.MapPath("~/css/style2.css"), true);
    IPipeline pipeline = new CssResolverPipeline(cssResolver, new HtmlPipeline(htmlContext, new PdfWriterPipeline(pdfDoc, PdfWriter)));
    var worker = new XMLWorker(pipeline, true);
    var xmlParse = new XMLParser(true, worker);
    pdfDoc.Open();
    xmlParse.Parse(sr);
    xmlParse.Flush();
    pdfDoc.Close();
    Response.ContentType = "application/pdf";
    Response.AddHeader("content-disposition", "attachment;filename=test.pdf;");
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.Write(pdfDoc);
    // Delete the temp image.
    File.Delete(Server.MapPath("qrimg.jpg"));
    Response.End();
}

public 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;
}

Screenshot