[Solved] PDF Document is not printing with QR code image using ITextSharp in ASP.Net

RichardSa
 
on Dec 04, 2022 10:34 PM
Sample_109699.zip
398 Views

Hi dharmendr,

Document not printing along with QR code image.

Does it have to do with the fact that I did not create/add a folder named qrimg?

Is that why it is not printing image on the pdf?

Maybe I need to first save the image in a folder.

Then use the image in ImageUrl with GetUrl function. Then after export to pdf, I delete the file from the folder.

But it thats true, what name will the folder be? Will it be qrimg like in the code?

protected void Export(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 ToAbsoluteUrl(string relativeUrl)
{
    if (string.IsNullOrEmpty(relativeUrl))
    {
        return relativeUrl;
    }
    if (relativeUrl.StartsWith("/"))
    {
        relativeUrl = relativeUrl.Insert(0,"~");
    }
 
    if (!relativeUrl.StartsWith("~/"))
    {
        relativeUrl = relativeUrl.Insert(0,"~/");
    }
 
    var url = HttpContext.Current.Request.Url;
    var port = url.Port != 80 ? (":" + url.Port) : String.Empty;
 
    return String.Format("{0}://{1}{2}{3}", url.Scheme, url.Host, port, VirtualPathUtility.ToAbsolute(relativeUrl));
}
 
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;
}
 
public override void VerifyRenderingInServerForm(Control control)
{
 
}
Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Dec 05, 2022 10:54 PM

Hi RichardSa,

There is no issue in the code.

Its working and image is displaying in the pdf file.

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