Add binary Image to existing PDF using iTextSharp in ASP.Net

Last Reply one month ago By George616

Posted one month ago

I spent a whole night trying to add the QR code as image to the uploaded pdf in the literal control where it is being displayed, but could not as the QR code only shows when the PDF file is downloaded; the uploaded PDF file in the literal control does not show. I followed the article you shared to me and tried the example in my test project.

After uploading a PDF file and click a button to navigate to another page, I want the QR code in image control to be added or attached to the uploaded PDF file from previous page and will be shown in the Literal control?

Here is what I tried. I tried to use the code in the BindCardAndQR method, so that when the page loads the QR code image will be added to the uploaded PDF. Actually, the QR code image shows when the PDF downloads but in a white background, different from the uploaded PDF file.

How can I add the QR code image to the uploaded PDf file?

   protected void Page_Load(object sender, EventArgs e)
   {
           BindCardAndQR();
   }
 
   private void BindCardAndQR()
   {
       if (Session["paperinv"] != null)
       {
           int id = Convert.ToInt32(Session["paperinv"]);
           // Binding PDF file in Literal control
           string embed = "<object data=\"{0}{1}\" type=\"application/pdf\"></object>";
           ltEmbed.Text = string.Format(embed, ResolveUrl("Handler.ashx?Id="), id);
 
           // This is where I Bind Image1 control for the QR code generated
           byte[] QRBytes = GetQRCodeBytes(Server.MapPath("~/PDFprint.aspx") + "?Id=" + id);
           Image1.ImageUrl = "data:image/jpg;base64," + Convert.ToBase64String(QRBytes);
 
           byte[] imageBytes = GetQRCodeBytes(Server.MapPath("~/PDFprint.aspx") + "?Id=" + id);
           iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imageBytes);
 
           using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
           {
               Document document = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
               PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
               document.Open();
               document.Add(image);
               document.Close();
               byte[] bytes = memoryStream.ToArray();
               memoryStream.Close();
 
               Response.Clear();
               Response.ContentType = "application/pdf";
               Response.AddHeader("Content-Disposition", "attachment; filename=Invoice.pdf");
               Response.ContentType = "application/pdf";
               Response.Buffer = true;
               Response.Cache.SetCacheability(HttpCacheability.NoCache);
               Response.BinaryWrite(bytes);
               Response.End();
           }
       }
   }
   public byte[] GetQRCodeBytes(string url)
   {
       //QR code is generated here
       QRCodeEncoder encoder = new QRCodeEncoder();
       Bitmap bi = encoder.Encode(url);
       MemoryStream tmpSteam = new MemoryStream();
       bi.Save(tmpSteam, ImageFormat.Jpeg);
       return tmpSteam.ToArray();
   }
Posted one month ago

Hi George616,

Refer below code.

Namespaces

using System.IO;
using iTextSharp.text.pdf;

Code

protected void BindCardAndQR(object sender, EventArgs e)
{
    if (Session["paperinv"] != null)
    {
        int id = Convert.ToInt32(Session["paperinv"]);
        byte[] QRBytes = GetQRCodeBytes(Server.MapPath("~/PDFprint.aspx") + "?Id=" + id);
        Image1.ImageUrl = "data:image/jpg;base64," + Convert.ToBase64String(QRBytes);
        iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(QRBytes);

        byte[] pdfbytes = File.ReadAllBytes(Server.MapPath("~/Test.pdf"));

        using (MemoryStream memoryStream = new MemoryStream())
        {
            var reader = new PdfReader(pdfbytes);
            var stamper = new PdfStamper(reader, memoryStream);
            var pdfContentByte = stamper.GetOverContent(1);
            image.SetAbsolutePosition(10, reader.GetPageSize(1).Height - 100);
            pdfContentByte.AddImage(image);
            stamper.Close();
            byte[] bytess = memoryStream.ToArray();
            memoryStream.Close();

            Response.Clear();
            Response.ContentType = "application/pdf";
            Response.AddHeader("Content-Disposition", "attachment; filename=Invoice.pdf");
            Response.ContentType = "application/pdf";
            Response.Buffer = true;
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.BinaryWrite(bytess);
            Response.End();
        }
    }
}

Replace this line with code to get the uploaded pdf byte from database you saved.

byte[] pdfbytes = File.ReadAllBytes(Server.MapPath("~/Test.pdf"));

Posted one month ago

I have succeeded in making it work. Here is my code.

On page load, the uploaded pdf file will be displayed in literal control and a QR code will be generated and bind in image control

 protected void Page_Load(object sender, EventArgs e)
    {
        BindCardAndQR();
    }
    private void BindCardAndQR()
    {
        if (Session["paperinv"] != null)
        {
            int id = Convert.ToInt32(Session["paperinv"]);

            string sql = "SELECT * FROM tableinvoice WHERE Id = @Id";
            SqlParameter[] parameters = new[] {
                    new SqlParameter("@Id", id)
                };

            // Bind Image3 for Card Image
            DataTable dt = SelectFromDatabase(sql, parameters);
            if (dt.Rows.Count > 0)
            {
            string embed = "<object data=\"{0}{1}\" type=\"application/pdf\"></object>";
            ltEmbed.Text = string.Format(embed, ResolveUrl("Handler.ashx?Id="), id);

            byte[] QRBytes = GetQRCodeBytes(Server.MapPath("~/PDFprint.aspx") + "?Id=" + id);
            Image1.ImageUrl = "data:image/jpg;base64," + Convert.ToBase64String(QRBytes);
            }
        }
    }
    public byte[] GetQRCodeBytes(string url)
    {
        //QR code generated here
        QRCodeEncoder encoder = new QRCodeEncoder();
        Bitmap bi = encoder.Encode(url);
        MemoryStream tmpSteam = new MemoryStream();
        bi.Save(tmpSteam, ImageFormat.Jpeg);
        return tmpSteam.ToArray();
    }

Then on Button click, the QR code generated in image control will be attached to the uploaded pdf for downloading or printing

 protected void btnPrinnt_Click(object sender, EventArgs e)
    {
        if (Session["paperinv"] != null)
        {
            int id = Convert.ToInt32(Session["paperinv"]);

            string sql = "SELECT * FROM tableinvoice WHERE Id = @Id";
            SqlParameter[] parameters = new[] {
                    new SqlParameter("@Id", id)
                };

            // Bind Image3 for Card Image
            DataTable dt = SelectFromDatabase(sql, parameters);
            if (dt.Rows.Count > 0)
            {
                string embed = "<object data=\"{0}{1}\" type=\"application/pdf\"></object>";
                ltEmbed.Text = string.Format(embed, ResolveUrl("Handler.ashx?Id="), id);

                byte[] QRBytes = GetQRCodeBytes(Server.MapPath("~/PDFprint.aspx") + "?Id=" + id);
                Image1.ImageUrl = "data:image/jpg;base64," + Convert.ToBase64String(QRBytes);

                iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(QRBytes);

                byte[] pdfbytes = (byte[])dt.Rows[0]["Data"];

                using (MemoryStream memoryStream = new MemoryStream())
                {
                    var reader = new PdfReader(pdfbytes);
                    var stamper = new PdfStamper(reader, memoryStream);
                    var pdfContentByte = stamper.GetOverContent(1);
                    image.SetAbsolutePosition(10, reader.GetPageSize(1).Height - 100);
                    pdfContentByte.AddImage(image);
                    stamper.Close();
                    byte[] bytess = memoryStream.ToArray();
                    memoryStream.Close();

                    Response.Clear();
                    Response.ContentType = "application/pdf";
                    Response.AddHeader("Content-Disposition", "attachment; filename=Invoice.pdf");
                    Response.ContentType = "application/pdf";
                    Response.Buffer = true;
                    Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    Response.BinaryWrite(bytess);
                    Response.End();
                }
            }
        }
    }
    public static DataTable SelectFromDatabase(string sql, SqlParameter[] parameters)
    {
        using (SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\Dataregister.mdf;Integrated Security=True"))
        {

            using (SqlCommand cmd = new SqlCommand(sql, con))
            {
                if (parameters != null)
                {
                    cmd.Parameters.AddRange(parameters);
                }

                using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
                {
                    DataTable dt = new DataTable();
                    sda.Fill(dt);
                    return dt;
                }
            }
        }
    }