locked
uploading PDF or word file and creating QR code for file RRS feed

  • Question

  • User-1994446809 posted

    Hello Forum,

     I created a web form where a pdf file can be uploaded and displayed on the page. After this, there is a button where user will click and the pdf file will be inserted into the database table, at the same time redirect to another page. Upon loading the next page, I want the saved PDF file to be called from the database and be displayed on the web page; a QR code will be created too for the PDF file. So that when the QR code is scanned, it will automatically redirect to the web page where the QR code and PDF file displays. I have been trying to get this done for weeks without success. 

    Please can anyone help me out?

    Here is what I tried

    Table Schema

    Id (int)

    Email (nvarchar MAX)

    Name (nvarchar MAX)

    ContentType (navrchar MAX)

    Data (varbinary MAX)

     

     

     

     

     

     

     

     

     

     

    In the webforms below, PDF file is uploaded in Uploadinvoice.aspx, and the button is clicked to redirect to Invoiceprint.aspx where QR code will be generated in the page load event, and the PDF file will be displayed in Invoiceprint.aspx as well.

    I get the binary data from database in the PDFprint.aspx webform and write it using html object tag with the help of Literal control. id is passed as parameter to the PDFprint.aspx webform for getting the record from database.

    THE ISSUE: When it rediirects to the Invoiceprint.aspx webform, Nothing is displayed and the QR code will not generate too. May I ask for help to resolve this, maybe if there is another way of achieving this?

     Here are my HTML and Codes

    Uploadinvoice.aspx

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <title>page1</title>
         <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
        <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
        <!--[if lt IE 9]>
          <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
          <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
        <![endif]-->
        <link href='https://fonts.googleapis.com/css?family=Comfortaa' rel='stylesheet' />
        <link href='https://fonts.googleapis.com/css?family=Nunito' rel='stylesheet' />
        <!-- Bootstrap CSS CDN -->
        <link href="css/bootstrap.css" rel="stylesheet" />
        <link href="css/bootstrap.min.css" rel="stylesheet" />
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous" />
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.min.css" />
        <!-- Font Awesome JS -->
        <script defer src="https://use.fontawesome.com/releases/v5.0.13/js/solid.js" integrity="sha384-tzzSw1/Vo+0N5UhStP3bvwWPq+uvzCMfrN1fEFe+xBmv1C/AtVX5K0uZtmcHitFZ" crossorigin="anonymous"></script>
        <script defer src="https://use.fontawesome.com/releases/v5.0.13/js/fontawesome.js" integrity="sha384-6OIrr52G08NpOFSZdxxz1xdNSndlD4vdcf/q2myIUVO0VsqaGHJsB0RaBE01VTOY" crossorigin="anonymous"></script>
        <!-- Font Awesome JS -->
        <script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
        <script type="text/javascript" src="https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>
        <script type="text/javascript" src="https://cdn.datatables.net/responsive/1.0.7/js/dataTables.responsive.min.js"></script>
        <script type="text/javascript" src="https://cdn.datatables.net/1.10.9/js/dataTables.bootstrap.min.js"></script>
        <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
     <style type="text/css">
            .wrapper {
                display: flex;
                width: 100%;
                align-items: stretch;
            }
    
            #sidebar {
                min-width: 250px;
                max-width: 250px;
                min-height: 100vh;
            }
    
                #sidebar.active {
                    margin-left: -250px;
                }
    
            a[data-toggle="collapse"] {
                ;
            }
    
            .dropdown-toggle::after {
                display: block;
                ;
                top: 50%;
                right: 20px;
                transform: translateY(-50%);
            }
    
            @media (max-width: 768px) {
                #sidebar {
                    margin-left: -250px;
                }
    
                    #sidebar.active {
                        margin-left: 0;
                    }
            }
    
            body {
                font-family: Constantia;
                background-color: #DCDCDC;
            }
    
            p {
                font-family: 'Poppins', sans-serif;
                font-size: 1.1em;
                font-weight: 300;
                line-height: 1.7em;
                color: #999;
            }
    
            a, a:hover, a:focus {
                color: inherit;
                text-decoration: none;
                transition: all 0.3s;
            }
    
            #sidebar {
                /* don't forget to add all the previously mentioned styles here too */
                background: #355171;
                color: #fff;
                transition: all 0.3s;
            }
    
            #topbar {
                background: #355171;
            }
    
            #sidebar .sidebar-header {
                padding: 20px;
                background: #355171;
                font-size: medium;
                font-family: Nunito;
                margin-top: -8px;
            }
    
            #sidebar ul.components {
                padding: 20px 0;
                border-bottom: 1px solid #47748b;
            }
    
            #sidebar ul p {
                color: #fff;
                padding: 10px;
                font-size: medium;
            }
            #sub-head:hover{
                color:#355171;
            }
            #navbarSupportedContent li a {
                color: #00003D;
                font-family: Constantia;
            }
            #sidebar ul li a {
                padding: 10px;
                font-size: 1.1em;
                display: block;
                font-size: 9pt;
                font-family:Gadugi;
            }
                #sidebar ul li a:hover {
                    color: #9c9ea0;
                    background: #355171;
                }
    
            #sidebar ul li.active > a, a[aria-expanded="true"] {
                color: #97a7ae;
                background: #355171;
            }
    
            ul ul a {
                font-size: 0.9em !important;
                padding-left: 30px !important;
                background: #4682b4;
            }
             #sidebarCollapse {
                background-color: #355171;
                font-size: x-small;
                max-width: 25px;
                min-width: 25px;
                max-height:25px;
                min-height:25px;
            }
    
            #sideCollapse {
                background-color: #355171;
                font-size: x-small;
                max-width: 26px;
                min-width: 26px;
                max-height:26px;
                min-height:26px;
            }
            #content {
                width: 100%;
                font-size: small;
            }
           #center-content {
               margin-right: 50%;
               ;
           }
           #page {
               align-content: center;
               text-align: center;
           }
        </style>
            <style>
            .mid-cont {
                ;
                margin-left: 20%;
            }
             /* canvas container */
            .contentt {
                max-width: 100%;
                ;
                margin: auto;
                height: auto;
                margin-top: 0%;
                /*text-align: center;*/
            }
            .containr-fluid {
                font-size: 9pt;
            }
            #the-canvas{
            }
        </style>
        <script type="text/javascript">
    	$(document).ready(function() { 
    		var $winwidth = $(window).width();
    		$("#the-canvas").attr({
    			width: $winwidth
    		});
    		$(window).bind("resize", function(){ 
    			var $winwidth = $(window).width();
    			$("#the-canvas").attr({
    				width: $winwidth
    			});
    		 });
    	}); 
    </script>
    </head>
    <body style="font-family: Constantia; background-color: #eeeeee;">
        <form id="form1" runat="server" enctype="multipart/form-data" method="POST">
            <div class="wrapper">
                <!-- Sidebar -->
                <nav id="sidebar">
                    <ul class="list-unstyled components">
                        <li>
                            <a><asp:Label ID="createby" runat="server" Text="williams@gmail.com"></asp:Label></a>
                        </li>
                    </ul>
                    <ul class="list-unstyled components">
                        <li>
                            <a href="#">Home</a>
                        </li>
                        <li>
                           <a href="#">Uploads</a>
                        </li>
                        <li>
                            <a href="#">Profile</a>
                        </li>
                    </ul>
                </nav>
                <div id="content" style="font-size: 10pt;">
                    <nav id="topnav" class="navbar navbar-expand-lg navbar-default navbar-inverse navbar-fixed-top" role="navigation" style="background-color: #eeeeee; font-size: small; font-family: Nunito;">
                        <div class="container-fluid">
                            <button type="button" id="sidebarCollapse" class="btn btn-info">
                                <i class="fas fa-align-left"></i>
                                <span class="sr-only">Toggle Navigation</span>
                                <span class="icon-bar"></span>
                                <span class="icon-bar"></span>
                                <span class="icon-bar"></span>
                            </button>
                            &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;
                            <h3 style="font-size: medium; font-weight: bolder; font: bolder; color: #00003D;">Logo</h3>
                            <button class="btn btn-info d-lg-none ml-auto" id="sideCollapse" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                                <i class="fas fa-align-justify"></i>
                            </button>
                            <div class="collapse navbar-collapse" id="navbarSupportedContent">
                                <ul class="nav navbar-nav ml-auto">
                                    <li class="nav-item">
                                        <a class="nav-link" href="Index.aspx" style="font-weight: bolder;">Home</a>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </nav>
                    <hr />
                     <br />
              <div class="line"></div>
               <div class="container" id="centered" style="margin-top: -2%; font-family: Nunito;">
                   <div class="form-horizontal">
                       <div class="mid-cont">
                           <br />
                           <div class="containr-fluid">
                               <asp:FileUpload runat="server" ID="showPreviewBill" />
                               <asp:Button ID="buttonmail" runat="server" CssClass="btn btn-primary navbar-btn" BackColor="SteelBlue" Font-Size="9pt" Text="Submit" OnClick="buttonmail_Click" />
                               <br />
                               <br />
                           </div>
                           <div class="contentt">
                               <canvas id="the-canvas" style="border: 1px solid grey; height: 850px; width: 700px;"></canvas>
                           </div>
                       </div>
                       <asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
                   </div>
               </div>
                    <br />
                    <!-- Footer -->
                    <footer class="page-footer font-small bg-light" style="background-color: #D1D1D1; font-family: Nunito; max-width: 100%; margin-bottom: 0%;">
                        <hr />
                        <div class="footer-copyright text-center py-3" style="font-size: 8pt;">
                         © Copyright <%=DateTime.Now.Year %>&nbsp;&nbsp;&nbsp;<a href="#" style="font-weight:bold; color:#00003D; font-size:10pt;">pixers</a>
                        </div>
                    </footer>
                <!-- Footer -->
            </div>
        </div>
        </form>
        <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.concat.min.js"></script>
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.0.943/pdf.min.js"></script>
    
        <script src="js/bootstrap.min.js"></script>
    
        <script type="text/javascript">
            $(function () {
                $("#showPreviewBill").change(function () {
                    if (this.files && this.files[0]) {
                        var reader = new FileReader();
                        reader.onload = function (e) {
                            showInCanvas(e.target.result);
                        }
                        reader.readAsDataURL(this.files[0]);
                    }
                });
     
                function convertDataURIToBinary(dataURI) {
                    var BASE64_MARKER = ';base64,';
                    var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
                    var base64 = dataURI.substring(base64Index);
                    var raw = window.atob(base64);
                    var rawLength = raw.length;
                    var array = new Uint8Array(new ArrayBuffer(rawLength));
     
                    for (i = 0; i < rawLength; i++) {
                        array[i] = raw.charCodeAt(i);
                    }
                    return array;
                }
     
                function showInCanvas(url) {
                    'use strict';
                    var pdfAsArray = convertDataURIToBinary(url);
                    pdfjsLib.getDocument(pdfAsArray).then(function (pdf) {
                        pdf.getPage(1).then(function (page) {
                            var scale = 1.5;
                            var viewport = page.getViewport(scale);
                            var canvas = document.getElementById('the-canvas');
                            var context = canvas.getContext('2d');
                            canvas.height = viewport.height;
                            canvas.width = viewport.width;
                            var renderContext = {
                                canvasContext: context,
                                viewport: viewport
                            };
                            page.render(renderContext);
                        });
                    });
                }
            });
        </script>
         <script type="text/javascript">
            $(document).ready(function () {
    
                $("#sidebar").mCustomScrollbar({
                    theme: "minimal"
                });
    
                $('#sidebarCollapse').on('click', function () {
                    // open or close navbar
                    $('#sidebar').toggleClass('active');
                    // close dropdowns
                    $('.collapse.in').toggleClass('in');
                    // and also adjust aria-expanded attributes we use for the open/closed arrows
                    // in our CSS
                    $('a[aria-expanded=true]').attr('aria-expanded', 'false');
                });
    
            });
        </script>
    </body>
    </html>

    Uploadinvoice.aspx.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Data;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Diagnostics;
    using System.Drawing;
    using System.Drawing.Imaging;
    using System.IO;
    using System.Data.SqlClient;
    
    public partial class Uploadinvoice : System.Web.UI.Page
    {
        SqlCommand cmd = new SqlCommand();
        SqlDataAdapter sda = new SqlDataAdapter();
        DataSet ds = new DataSet();
        SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\Dataregister.mdf;Integrated Security=True");
        private object Inv;
    
        protected void Page_Load(object sender, EventArgs e)
        {
            con.ConnectionString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\Dataregister.mdf;Integrated Security=True";
            if (!string.IsNullOrEmpty(Request.QueryString["icard"]))
            {
                Session["icard"] = Convert.ToInt32(Request.QueryString["icard"]);
            }
        }
        protected void buttonmail_Click(object sender, EventArgs e)
        {
                string filename = Path.GetFileName(showPreviewBill.PostedFile.FileName);
                string contentType = showPreviewBill.PostedFile.ContentType;
                using (Stream fs = showPreviewBill.PostedFile.InputStream)
                {
                    using (BinaryReader br = new BinaryReader(fs))
                    {
                        byte[] bytes = br.ReadBytes((Int32)fs.Length);
                        using (SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\Dataregister.mdf;Integrated Security=True"))
                        {
                            string query = "INSERT INTO tableinvoice(email, Name, ContentType, Data)" +
                        " VALUES(@email, @Name, @ContentType, @Data); SELECT @@IDENTITY";
                            using (SqlCommand cmd = new SqlCommand(query))
                            {
                                cmd.Connection = con;
                                cmd.Parameters.AddWithValue("@email", createby.Text.Trim());
                                cmd.Parameters.AddWithValue("@Name", filename);
                                cmd.Parameters.AddWithValue("@ContentType", contentType);
                                cmd.Parameters.AddWithValue("@Data", bytes);
                                con.Open();
                                cmd.ExecuteNonQuery();
                                con.Close();
                                Session["paperinv"] = Inv;
                                Response.Redirect("Invoiceprint.aspx");
                            }
                        }
                    }
                }
            }
    }

    PDFprint.aspx

    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Data;
    using System.Data.SqlClient;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    
    public partial class PDFprint : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["Id"] != null)
            {
                string strQuery = "SELECT Name, ContentType, Data FROM tableinvoice where Id=@Id";
                String strConnString = ConfigurationManager.ConnectionStrings["Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\Dataregister.mdf;Integrated Security=True"].ConnectionString;
                using (SqlCommand cmd = new SqlCommand(strQuery))
                {
                    cmd.Parameters.AddWithValue("@Id", Convert.ToInt32(Request.QueryString["Id"]));
                    using (SqlConnection con = new SqlConnection(strConnString))
                    {
                        SqlDataAdapter sda = new SqlDataAdapter();
                        cmd.CommandType = CommandType.Text;
                        DataTable dt = new DataTable();
                        cmd.Connection = con;
                        con.Open();
                        sda.SelectCommand = cmd;
                        sda.Fill(dt);
                        if (dt.Rows.Count > 0)
                        {
                            byte[] bytes = (Byte[])dt.Rows[0]["Data"];
                            Response.Buffer = true;
                            Response.Charset = "";
                            Response.Cache.SetCacheability(HttpCacheability.NoCache);
                            Response.BinaryWrite(bytes);
                            Response.Flush();
                            Response.End();
                        }
                    }
                }
            }
        }
    }

    Invoiceprint.aspx

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <title>QR/Print</title>
         <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
        <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
        <!--[if lt IE 9]>
          <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
          <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
        <![endif]-->
        <link href="css/bootstrap.css" rel="stylesheet" />
        <link href="css/bootstrap.min.css" rel="stylesheet" />
        <!-- Our Custom CSS -->
        <link href="css/style2.css" rel="stylesheet" />
        <!-- Scrollbar Custom CSS -->
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.min.css" />
        <!-- Font Awesome JS -->
        <script defer src="https://use.fontawesome.com/releases/v5.0.13/js/solid.js" integrity="sha384-tzzSw1/Vo+0N5UhStP3bvwWPq+uvzCMfrN1fEFe+xBmv1C/AtVX5K0uZtmcHitFZ" crossorigin="anonymous"></script>
        <script defer src="https://use.fontawesome.com/releases/v5.0.13/js/fontawesome.js" integrity="sha384-6OIrr52G08NpOFSZdxxz1xdNSndlD4vdcf/q2myIUVO0VsqaGHJsB0RaBE01VTOY" crossorigin="anonymous"></script>
        <!-- Font Awesome JS -->
        <script type="text/javascript" src="https://code.jquery.com/jquery-1.12.4.js"></script>
        <script type="text/javascript" src="https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>
        <script type="text/javascript" src="https://cdn.datatables.net/responsive/1.0.7/js/dataTables.responsive.min.js"></script>
        <script type="text/javascript" src="https://cdn.datatables.net/1.10.9/js/dataTables.bootstrap.min.js"></script>
        <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
     <style type="text/css">
            .wrapper {
                display: flex;
                width: 100%;
                align-items: stretch;
            }
    
            #sidebar {
                min-width: 250px;
                max-width: 250px;
                min-height: 100vh;
            }
    
                #sidebar.active {
                    margin-left: -250px;
                }
    
            a[data-toggle="collapse"] {
                ;
            }
    
            .dropdown-toggle::after {
                display: block;
                ;
                top: 50%;
                right: 20px;
                transform: translateY(-50%);
            }
    
            @media (max-width: 768px) {
                #sidebar {
                    margin-left: -250px;
                }
    
                    #sidebar.active {
                        margin-left: 0;
                    }
            }
    
            body {
                font-family: Constantia;
                background-color: #DCDCDC;
            }
    
            p {
                font-family: 'Poppins', sans-serif;
                font-size: 1.1em;
                font-weight: 300;
                line-height: 1.7em;
                color: #999;
            }
    
            a, a:hover, a:focus {
                color: inherit;
                text-decoration: none;
                transition: all 0.3s;
            }
    
            #sidebar {
                /* don't forget to add all the previously mentioned styles here too */
                background: #355171;
                color: #fff;
                transition: all 0.3s;
            }
    
            #topbar {
                background: #355171;
            }
    
            #sidebar .sidebar-header {
                padding: 20px;
                background: #355171;
                font-size: medium;
                font-weight: bold;
                font-family: Nunito;
                margin-top: -8px;
            }
    
            #sidebar ul.components {
                padding: 20px 0;
                border-bottom: 1px solid #47748b;
            }
    
            #sidebar ul p {
                color: #fff;
                padding: 10px;
                font-size: medium;
            }
            #sub-head:hover{
                color:#355171;
            }
            #navbarSupportedContent li a {
                color: #00003D;
                font-family: Constantia;
            }
            #sidebar ul li a {
                padding: 10px;
                font-size: 1.1em;
                display: block;
                font-size: 9pt;
                font-family:Gadugi;
            }
                #sidebar ul li a:hover {
                    color: #9c9ea0;
                    background: #355171;
                }
    
            #sidebar ul li.active > a, a[aria-expanded="true"] {
                color: #97a7ae;
                background: #355171;
            }
    
            ul ul a {
                font-size: 0.9em !important;
                padding-left: 30px !important;
                background: #4682b4;
            }
             #sidebarCollapse {
                background-color: #355171;
                font-size: x-small;
                max-width: 25px;
                min-width: 25px;
                max-height:25px;
                min-height:25px;
            }
    
            #sideCollapse {
                background-color: #355171;
                font-size: x-small;
                max-width: 26px;
                min-width: 26px;
                max-height:26px;
                min-height:26px;
            }
            #content {
                width: 100%;
                font-size: small;
            }
           #center-content {
               margin-right: 50%;
               ;
           }
           #page {
               align-content: center;
               text-align: center;
           }
        </style>
            <style>
            .contentt {
                max-width: 100%;
                ;
                margin: auto;
                height: auto;
                margin-top: 0%;
                margin-left: 2%;
            }
            .print{
                margin: 0 auto;
                
            }
            #Image1 {
                ;
                left: 40px;
                bottom: 60px;
                cursor: move;
                background-color: #fafafa;
                border: solid 1px #00003D;
                font-size: 24px;
                text-align: center;
                backface-visibility:hidden;
                background:unset;
                height:90px;
                width:86px
            }
    
        </style>
    </head>
    <body style="font-family: Constantia; background-color: #eeeeee;">
        <form id="form1" runat="server">
            <div class="wrapper">
                <!-- Sidebar -->
                <nav id="sidebar">
                    <ul class="list-unstyled components">
                        <li>
                            <a><asp:Label ID="Label1" runat="server" Text="williams@gmail.com"></asp:Label></a>
                        </li>
                    </ul>
                    <ul class="list-unstyled components">
                        <li>
                            <a href="#">Home</a>
                        </li>
                        <li>
                           <a href="#">Uploads</a>
                        </li>
                        <li>
                            <a href="#">Profile</a>
                        </li>
                    </ul>
                </nav>
                <div id="content" style="font-size: 10pt;">
                    <nav id="topnav" class="navbar navbar-expand-lg navbar-default navbar-inverse navbar-fixed-top" role="navigation" style="background-color: #eeeeee; font-size: small; font-family: Nunito;">
                        <div class="container-fluid">
                            <button type="button" id="sidebarCollapse" class="btn btn-info">
                                <i class="fas fa-align-left"></i>
                                <span class="sr-only">Toggle Navigation</span>
                                <span class="icon-bar"></span>
                                <span class="icon-bar"></span>
                                <span class="icon-bar"></span>
                            </button>
                            &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;
                            <h3 style="font-size: medium; font-weight: bolder; font: bolder; color: #00003D;">Logo</h3>
                            <button class="btn btn-info d-lg-none ml-auto" id="sideCollapse" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                                <i class="fas fa-align-justify"></i>
                            </button>
                            <div class="collapse navbar-collapse" id="navbarSupportedContent">
                                <ul class="nav navbar-nav ml-auto">
                                    <li class="nav-item">
                                        <a class="nav-link" href="Index.aspx" style="font-weight: bolder;">Home</a>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </nav>
                    <hr />
                     <br />
              <div class="line"></div>
              <asp:Label ID="labelid" runat="server" Text="uid"></asp:Label><asp:Label ID="createby" runat="server" Text="createby"></asp:Label><asp:Label ID="role" runat="server" Text="role"></asp:Label>
               <div class="container" id="centered" style="margin-top: -2%; font-family: Nunito;">
                   <div class="form-horizontal">
                       <h1 style="font-size: small; margin-top: 0%; color: red;">ID Card with QR Code</h1>
                       <hr />
                       <br />
                      <div class="row">
                <asp:Panel ID="printpanel" runat="server">
                    <div class="contentt">
                        <%--<canvas id="the-canvas" style="border: 1px solid black; height: 750px; width: 650px;"></canvas>--%>
                        <asp:Literal ID="ltEmbed" runat="server" />
                        <asp:Image ID="Image1" runat="server" BorderStyle="None" Width="80px" Height="85px" />
                    </div>
                </asp:Panel>
                           <br />
                            &nbsp;&nbsp;
                           <div class="print">
                            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                               <br />
                               <br />
                            <asp:Button ID="btnPrinnt" runat="server" CssClass="btn btn-primary navbar-btn" BackColor="SteelBlue" Font-Size="Small" Text="Send to Mail"/>
                               <br />
                               <br />
                            <asp:Button ID="buttonmail" runat="server" CssClass="btn btn-primary navbar-btn" BackColor="SteelBlue" Font-Size="Small" Text="Download"/>
                       </div>
                       </div>
                   </div>
               </div>
                    <br />
                    <br />
                    <!-- Footer -->
                    <footer class="page-footer font-small bg-light" style="background-color: #D1D1D1; font-family: Nunito; max-width: 100%; margin-bottom: 0%;">
                        <hr />
                        <div class="footer-copyright text-center py-3" style="font-size: 8pt;">
                         © Copyright <%=DateTime.Now.Year %>&nbsp;&nbsp;&nbsp;<a href="#" style="font-weight:bold; color:#00003D; font-size:10pt;">pixers</a>
                        </div>
                    </footer>
                <!-- Footer -->
            </div>
        </div>
        </form>
         <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <!-- Include all compiled plugins (below), or include individual files as needed -->
        <script src="js/bootstrap.min.js"></script>
         <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
         <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
         <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
         <script src="https://cdnjs.cloudflare.com/ajax/libs/malihu-custom-scrollbar-plugin/3.1.5/jquery.mCustomScrollbar.concat.min.js"></script>
     
         <script type="text/javascript">
            $(document).ready(function () {
    
                $("#sidebar").mCustomScrollbar({
                    theme: "minimal"
                });
    
                $('#sidebarCollapse').on('click', function () {
                    // open or close navbar
                    $('#sidebar').toggleClass('active');
                    // close dropdowns
                    $('.collapse.in').toggleClass('in');
                    // and also adjust aria-expanded attributes we use for the open/closed arrows
                    // in our CSS
                    $('a[aria-expanded=true]').attr('aria-expanded', 'false');
                });
    
            });
        </script>
    </body>
    </html>

    Invoiceprint.aspx.cs

     SqlCommand cmd = new SqlCommand();
        SqlDataAdapter sda = new SqlDataAdapter();
        DataSet ds = new DataSet();
        SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\Dataregister.mdf;Integrated Security=True");
        private string imgBytes;
    
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                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\" width=\"650px\" height=\"750px\"></object>";
                ltEmbed.Text = string.Format(embed, ResolveUrl("Invoiceprint.aspx?Id="), id);
    
                //This is where I Bind Image1 control for the QR code generated
                byte[] QRBytes = GetQRCodeBytes(Server.MapPath("~/Invoiceprint.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();
        }

    Wednesday, November 18, 2020 11:59 AM

Answers

  • User-1994446809 posted

    Thanks mgebhard,

    I finally got it. On button click, it will redirect to the page where the literal control will display the PDF file.

        private object Invoice;
    
        protected void Page_Load(object sender, EventArgs e)
        {
            con.ConnectionString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\Dataregister.mdf;Integrated Security=True";
            if (!string.IsNullOrEmpty(Request.QueryString["invoicecard"]))
            {
                Session["invoicecard"] = Convert.ToInt32(Request.QueryString["invoicecard"]);
            }
        }
        protected void buttonmail_Click(object sender, EventArgs e)
        {
            string filename = Path.GetFileName(showPreviewBill.PostedFile.FileName);
            string contentType = showPreviewBill.PostedFile.ContentType;
            using (Stream fs = showPreviewBill.PostedFile.InputStream)
            {
                using (BinaryReader br = new BinaryReader(fs))
                {
                    byte[] bytes = br.ReadBytes((Int32)fs.Length);
                    using (SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\Dataregister.mdf;Integrated Security=True"))
                    {
                        string query = "INSERT INTO tableinvoice(email, Name, ContentType, Data)" +
                    " VALUES(@email, @Name, @ContentType, @Data); SELECT @@IDENTITY";
                        using (SqlCommand cmd = new SqlCommand(query))
                        {
                            cmd.Connection = con;
                            cmd.Parameters.AddWithValue("@email", createby.Text.Trim());
                            cmd.Parameters.AddWithValue("@Name", filename);
                            cmd.Parameters.AddWithValue("@ContentType", contentType);
                            cmd.Parameters.AddWithValue("@Data", bytes);
                            con.Open();
                            cmd.ExecuteNonQuery();
                            object Invoice = cmd.ExecuteScalar();
                            con.Close();
                            Session["paperinv"] = Invoice;
                            Response.Redirect("PDFprint.aspx");
                        }
                    }
                }
            }
        }

    HTML for the redirected page

    <div class="contentt">
                                    <asp:Literal ID="ltEmbed" runat="server"/>
                                    <asp:Image ID="Image1" runat="server" BorderStyle="None" Width="80px" Height="85px" />
                                </div>

    then in the redirected page load event, I have this code that displays the file as well as generate a QR code for the file

     SqlCommand cmd = new SqlCommand();
        SqlDataAdapter sda = new SqlDataAdapter();
        DataSet ds = new DataSet();
        SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\Dataregister.mdf;Integrated Security=True");
        private string imgBytes;
        private object Inv;
    
        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\" width=\"100%\" height=\"auto\"></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);
            }
        }
        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();
        }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, November 27, 2020 10:46 AM

All replies

  • User475983607 posted

    The error is extraordinarily clear. Are you reading the error?  The querystring parameter "id" does not exist.  That means the calling page did not add the querystring parameter.  Rather than dumping all your code on the forum and forcing forum member to weed through the logic, do a little troubleshooting to figure out why the "id" parameter is missing!  

    I did a search in your code and cannot find any redirect or link that calls Invoiceprint which is the Web Form that expects the "Id" parameter.  The only redirect I found in the code is...

    Response.Redirect("page2.aspx");

    It looks like you need take a step back and review your code.

    Wednesday, November 18, 2020 2:02 PM
  • User-1994446809 posted

    Hi mgebhard,

    I'm so sorry about that; I shared the wrong codes and HTML. In my project, I have lots of webforms which I use to test before transferring to my main work, so I mistakenly shared from one of the test webforms.

    I have modified the HTML and Codes in the  thread, please check the right HTML and codes

    Wednesday, November 18, 2020 7:43 PM
  • User475983607 posted

    georgeakpan233

    I'm so sorry about that; I shared the wrong codes and HTML. In my project, I have lots of webforms which I use to test before transferring to my main work, so I mistakenly shared from one of the test webforms.

    I have modified the HTML and Codes in the  thread, please check the right HTML and codes

    The only redirect in the updated code still does not have a querystring not does it point to the page with the error.   

    Response.Redirect("Invoiceprint.aspx");

    I can't find any links to PDFPrint which throws the exception.  I guess you still have not included the actual code?  I recommend basic debugging to figure out why the "Id" is not passed.  You should know what page you where on before receiving the error.

    Wednesday, November 18, 2020 8:15 PM
  • User-1994446809 posted

    I can't find any links to PDFPrint which throws the exception. 

    I understand this. I'll look into it again.

    Wednesday, November 18, 2020 8:38 PM
  • User-1994446809 posted

    Thanks mgebhard,

    I finally got it. On button click, it will redirect to the page where the literal control will display the PDF file.

        private object Invoice;
    
        protected void Page_Load(object sender, EventArgs e)
        {
            con.ConnectionString = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\Dataregister.mdf;Integrated Security=True";
            if (!string.IsNullOrEmpty(Request.QueryString["invoicecard"]))
            {
                Session["invoicecard"] = Convert.ToInt32(Request.QueryString["invoicecard"]);
            }
        }
        protected void buttonmail_Click(object sender, EventArgs e)
        {
            string filename = Path.GetFileName(showPreviewBill.PostedFile.FileName);
            string contentType = showPreviewBill.PostedFile.ContentType;
            using (Stream fs = showPreviewBill.PostedFile.InputStream)
            {
                using (BinaryReader br = new BinaryReader(fs))
                {
                    byte[] bytes = br.ReadBytes((Int32)fs.Length);
                    using (SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\Dataregister.mdf;Integrated Security=True"))
                    {
                        string query = "INSERT INTO tableinvoice(email, Name, ContentType, Data)" +
                    " VALUES(@email, @Name, @ContentType, @Data); SELECT @@IDENTITY";
                        using (SqlCommand cmd = new SqlCommand(query))
                        {
                            cmd.Connection = con;
                            cmd.Parameters.AddWithValue("@email", createby.Text.Trim());
                            cmd.Parameters.AddWithValue("@Name", filename);
                            cmd.Parameters.AddWithValue("@ContentType", contentType);
                            cmd.Parameters.AddWithValue("@Data", bytes);
                            con.Open();
                            cmd.ExecuteNonQuery();
                            object Invoice = cmd.ExecuteScalar();
                            con.Close();
                            Session["paperinv"] = Invoice;
                            Response.Redirect("PDFprint.aspx");
                        }
                    }
                }
            }
        }

    HTML for the redirected page

    <div class="contentt">
                                    <asp:Literal ID="ltEmbed" runat="server"/>
                                    <asp:Image ID="Image1" runat="server" BorderStyle="None" Width="80px" Height="85px" />
                                </div>

    then in the redirected page load event, I have this code that displays the file as well as generate a QR code for the file

     SqlCommand cmd = new SqlCommand();
        SqlDataAdapter sda = new SqlDataAdapter();
        DataSet ds = new DataSet();
        SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\Dataregister.mdf;Integrated Security=True");
        private string imgBytes;
        private object Inv;
    
        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\" width=\"100%\" height=\"auto\"></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);
            }
        }
        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();
        }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, November 27, 2020 10:46 AM