PDF Document not printing along with image

Donald Symmons 1,946 Reputation points
2022-11-14T08:59:56.553+00:00

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.

Here is the “print” and “send to mail” buttons code

Print (download PDF document)

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();  
       }  
   }  

Send Document (send to email)

protected void Button1_Click(object sender, EventArgs e)  
   {  
       byte[] QRBytes = GetQRCodeBytes(ToAbsoluteUrl("/invoiceverificationtemp.aspx") + "?Id=" + Request.QueryString["InvoiceID"]);  
       Image1.ImageUrl = "data:image/jpg;base64," + Convert.ToBase64String(QRBytes);  
       var ImgUrl = Image1.ImageUrl;  
       // Write image as file to folder.  
       File.WriteAllBytes(Server.MapPath("qrimg.jpg"), QRBytes);  
       // convert and set absolute url in image.  
       Image1.ImageUrl = GetUrl("qrimg.jpg");  
   
       using (StringWriter sw = new StringWriter())  
       {  
           using (HtmlTextWriter hw = new HtmlTextWriter(sw))  
           {  
               this.Panel1.RenderControl(hw);  
               StringReader sr = new StringReader(sw.ToString());  
               Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);  
               //  HTMLWorker htmlparser = new HTMLWorker(pdfDoc);  
               using (MemoryStream memoryStream = new MemoryStream())  
               {  
                   PdfWriter PdfWriter = PdfWriter.GetInstance(pdfDoc, memoryStream);  
                   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();  
                   byte[] bytes = memoryStream.ToArray();  
                   memoryStream.Close();  
   
                   MailMessage mm = new MailMessage("mannyrchrd@gmail.com", this.TextBox1.Text);  
                   mm.Subject = "INVOICE DOCUMENT";  
                   mm.Body = "Please find Attached Invoice Document";  
                   mm.Attachments.Add(new Attachment(new MemoryStream(bytes), "Invoice.pdf"));  
                   mm.IsBodyHtml = true;  
                   SmtpClient smtp = new SmtpClient();  
                   smtp.Host = "relay-hosting.secureserver.net";  
                   smtp.EnableSsl = false;  
                   System.Net.NetworkCredential NetworkCred = new System.Net.NetworkCredential();  
                   NetworkCred.UserName = "mannyrchrd@gmail.com";  
                   NetworkCred.Password = "******************";  
                   smtp.UseDefaultCredentials = true;  
                   smtp.Credentials = NetworkCred;  
                   smtp.Port = 25;  
                   smtp.Send(mm);  
               }  
           }  
       }  
       Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Script", "alert('Document Sent!');", true);  
   }  
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
1,491 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
8,244 questions
{count} votes

2 answers

Sort by: Most helpful
  1. AgaveJoe 22,796 Reputation points
    2022-11-14T19:30:19.64+00:00

    The first code block, Button3_Click, tries to download a PDF. The download part is clear but the bulk of the code is either nonsensical or incomplete. Why is Image1.ImageUrl assigned three different times? I get the feeling you expect the code to refresh the browser and download a PDF which is not possible. You can either download a PDF or update the browser not both in one response stream.

    Also, it seems you expect the ASPX page's response stream to magically generate a properly formatted PDF. If the QR code and logo are missing then the problem is you do not understand the 3rd party PDF library you decided to use in this project.

    Create a simple test to learn how to add an image then use the same pattern in the code.


  2. Lan Huang-MSFT 15,296 Reputation points Microsoft Vendor
    2022-11-16T08:36:01.787+00:00

    Hi @Donald Symmons ,
    I think it is possible to generate a QR code directly on the html page, and then generate a pdf of the entire page.
    When you finally send an email, you only need to send the pdf. Because the QR code is already included in the pdf.
    You can refer to the following example:
    code behind: 260855-2.txt
    260823-image.png


       <div id="print" runat="server">    
        <h1>About Raj Kumar</h1>    
             <div>    
                  <table>    
                      <tr>    
                          <td>    
                              <img src="https://www.c-sharpcorner.com/UploadFile/MinorCatImages/asp-dot-net-programming_060516203.png.ashx?width=64&height=64" height="100" width="120" />    
                          </td>    
                          <td></td>    
                     </tr>    
                     <tr>    
                         <td>Name: </td>    
                         <td>TEST1</td>    
                     </tr>    
                     <tr>    
                          <td>Designation: </td>    
                         <td>TEST2</td>    
                     </tr>    
                     <tr>    
                          <td>Work Experience: </td>    
                          <td>9 Years in IT</td>    
                     </tr>    
                     <tr>    
                          <td>About: </td>    
                         <td>TEST</td>    
                     </tr>    
                     <tr>    
                         <td>Location: </td>    
                        <td>New Delhi INDIA</td>    
                     </tr>    
                 </table>    
            </div>    
        </div>    
        <div>    
            <asp:Button ID="btnCreatePDF" runat="server" Text="Create PDF" OnC lick="btnCreatePDF_Click" />    
        </div>     
    

    260726-image.png
    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments