Export base64 Barcode image with HTML to PDF C# in ASP.Net

Last Reply 11 days ago By dharmendr

Posted 11 days ago

Hello Forum,

I recently learnt how to convert HTML to PDF with HTML style CSS. However, I encountered TWO ISSUES.

  1. How can I make an image that will be uploaded onto the image control to be rendered in the PDF? Because in the code, it has a complete image path which means that the image is inside the image folder of the project. But in this case image will be uploaded on to the image control
  2. Also, in my invoice the label controls appear well, as expected in the PDF but the gridview width did not cover the PDF width. How can I make the gridview width to cover the width of the PDF? I want to learn how to solve this two issues please.
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
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;
using System.Text;
using iText.Html2pdf;

public partial class AA : System.Web.UI.Page
{
    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();
        }
    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);
        Panel1.RenderControl(hw);
        StringReader sr = new StringReader(sw.ToString());
        Document pdfDoc = new Document();
        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=Panel.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Write(pdfDoc);
        Response.End();
    }

From the code below and in private void BindCardAndQR. In the code, Image4 is the image control to bind QR code

public byte[] GetQRCodeBytes(string url)
{
    QRCodeEncoder encoder = new QRCodeEncoder();
    Bitmap bi = encoder.Encode(url);
    MemoryStream tmpSteam = new MemoryStream();
    bi.Save(tmpSteam, ImageFormat.Jpeg);
    return tmpSteam.ToArray();
}

 

private void BindCardAndQR()
{
    // Bind Image4 for QR code
    byte[] QRBytes = GetQRCodeBytes(Server.MapPath("/IDCard.aspx") + "?Id=" + id);
    Image4.ImageUrl = "data:image/jpg;base64," + Convert.ToBase64String(QRBytes);
}

 

Posted 11 days ago Modified on 8 days ago

Since itextSharp doesn't support base64 string as url for image you need to first save the byte array as file in server folder temporarily and change the url to absolute url and set in image ImageUrl property.

Then after writing the pdf document to the Response class delete the image from server folder.

Check below code.

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        byte[] QRBytes = GetQRCodeBytes(Server.MapPath("/IDCard.aspx") + "?Id=" + id);
        Image1.ImageUrl = "data:image/jpg;base64," + Convert.ToBase64String(QRBytes);
        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 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 Button2_Click(object sender, EventArgs e)
{
    byte[] QRBytes = GetQRCodeBytes(Server.MapPath("/IDCard.aspx") + "?Id=" + id);
    Image1.ImageUrl = "data:image/jpg;base64," + Convert.ToBase64String(QRBytes);
    var imgUrl = Image1.ImageUrl;
    // Write image as file to folder.
    File.WriteAllBytes(Server.MapPath("temp.jpg"), QRBytes);
    // convert and set absolute url in image.
    Image1.ImageUrl = GetUrl("temp.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("~/StyleSheet.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=Panel.pdf");
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.Write(pdfDoc);
    // Delete the temp image.
    File.Delete(Server.MapPath("temp.jpg"));
    Image1.ImageUrl = imgUrl;
    Response.End();
}