Home > Software design >  Programmatically download the QR image
Programmatically download the QR image

Time:02-11

I tried to create a QR code with QRcode.js library. As of the UI, I can manually click on the button download to download it but I would to download automatically without clicking the button.

Base on my code bellow.

function genQR(link_string){
    let qr_code_element = document.querySelector(".qr-code");

      if (link_string != "") {
          if (qr_code_element.childElementCount == 0) {
            generate(qr_code_element, link_string);
          } else {
          qr_code_element.innerHTML = "";
            generate(qr_code_element, link_string);
          }
      } else {
          alert("not valid QR input");
          qr_code_element.style = "display: none";
      }
  }

  function generate(qr_code_element, link_string) {
    qr_code_element.style = "";
    var qrcode = new QRCode(qr_code_element, {
        text: link_string,
        width: 200, 
        height: 200,
        colorDark : "#000000",
        colorLight : "#ffffff",
        correctLevel: QRCode.CorrectLevel.H
    });

    let download = document.createElement("button");
    // qr_code_element.appendChild(download);

    let download_link = document.createElement("a");
    download_link.setAttribute("download", "qr.png");
    download_link.setAttribute("id", "downloadbtn");
    download_link.innerText = "Download";
    // download.appendChild(download_link);

    let qr_code_img = document.querySelector(".qr-code img");
    let qr_code_canvas = document.querySelector("canvas");

    if (qr_code_img.getAttribute("src") == null) {
      setTimeout(() => {
        download_link.setAttribute("href", `${qr_code_canvas.toDataURL()}`);
      }, 300);
    } else {
        setTimeout(() => {
        download_link.setAttribute("href", `${qr_code_img.getAttribute("src")}`);
        }, 300);
    }

    var clickEvent = new MouseEvent("click", {
      "view": window,
      "bubbles": true,
      "cancelable": false
  });
  
  //I expect the below line will automatically download the QR but nothing fires.
  download_link.dispatchEvent(clickEvent);
}

If I use button to click and download by hand will works fine for me but I want to reduce too many steps.

I think I almost done here but failed.

Could anyone show me how to automatic download?

Thank you in advance.

CodePudding user response:

I've had this issue in the past, and I've worked around it by creating a small util function I can invoke upon button pressing. But invoking it directly at the end of your function should have the same result as a user click, effectively automatically downloading the QR code without user input.

export function download(blob, filename) {
  const url = window.URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.style.display = 'none';
  a.href = url;
  a.download = filename
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  window.URL.revokeObjectURL(url);
}

I'm guessing you could try passing generate as the first parameter if the object you're getting is a Blob. Otherwise, you'll probably need to convert it before.

CodePudding user response:

I done my target by adding the source you shared at the bottom of my code and then added this function to convert dataURL to Blob

function dataURItoBlob(dataURI) {
  var byteString = atob(dataURI.split(',')[1]);
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]
var ab = new ArrayBuffer(byteString.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < byteString.length; i  ) {
      ia[i] = byteString.charCodeAt(i);
  }

 var blob = new Blob([ab], {type: mimeString});
  return blob;

}

Thank you very much @Gianmarco Rengucci I rate for you

  • Related