Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

how to download qrcode #37

Open
danjuanzzf opened this issue Oct 12, 2017 · 16 comments
Open

how to download qrcode #37

danjuanzzf opened this issue Oct 12, 2017 · 16 comments

Comments

@danjuanzzf
Copy link

how to download qrcode

@hjzheng
Copy link

hjzheng commented Oct 30, 2017

1.Use dom API get the canvas object.
2.convert canvas to image.
3.Use a to download the image.

var link = document.createElement('a');
link.textContent = 'download image';

link.addEventListener('click', function(ev) {
    link.href = canvas.toDataURL();
    link.download = "mypainting.png";
}, false);

document.body.appendChild(link);

@danjuanzzf
Copy link
Author

Thanks

@s875515
Copy link

s875515 commented Nov 13, 2017

download = () => { 
   const canvas: any = document.querySelector('.HpQrcode > canvas');
   this.downloadRef.href = canvas.toDataURL();
   this.downloadRef.download = 'mypainting.png';
}


<div className="HpQrcode">
  <QRCode
     value={copyLink}
     size={85}
     level={'H'}
  />
</div>

<a ref={(ref: any): any => this.downloadRef = ref}>
  download
</a>

@jutian88
Copy link

@s875515 thanks!

@Angelk90
Copy link

@hjzheng , @s875515 :
I should do something like this:

Inside a table (react-data-table-component), I have elements, one of these elements, the text must be converted into qr code, I thought I would use this module.

The problem that I need to convert the qr code into an image, I thought to simplify things based64.
Then I have to put this image in a pdf file that I need to generate.

How can I do?

It would be interesting if there was such a call:
QRCode.base64("text);
that returns the image of the qr code in base64.

You know how to give me advice.

@raffibag
Copy link

raffibag commented Aug 4, 2019

Adding to @hjzheng and @s875515's comments, I recently adapted the code above for use in a list view (table, screen shot attached) using React Router. The goal was to create a download component that received token and id props from which a QR code would be generated. This code uses React Router's <Link> API's innerRef: RefObject to get the underlying ref of the component.

import React, { Component } from 'react'
import QRCode from 'qrcode.react';
import { Link } from 'react-router-dom';

class Download extends Component {
  constructor(props) {
    super(props);
    this.serviceKey = props.serviceKey;
    this.token = props.token;
  }

  codeClassName = `QRCode-${this.props.serviceKey}`;

  refCallback(node){
    const nodeId = node.title;
    {/* use an html attribute (in this case, title) to get a unique id from the props passed to component */}
    const canvas: any = document.querySelector(`.QRCode-${nodeId} > canvas`);
    node.href = canvas.toDataURL();
    node.download = `TipGuru-QRCode-${nodeId}.png`;
  }

  render() {
    return (
      <div>
        {/* hide the QR code if there's no need to render in the view */}
        <div hidden className={this.codeClassName}>
          <QRCode
             value={this.token}
             size={1024}
          />
        </div>
        {/* Use html attributes to pass in any required data to the ref node. Note: target: '_blank' was required in order to initiate the download dialogue */}
        <Link to="/" target='_blank' title={this.serviceKey} innerRef={this.refCallback}>
            <i className="mdi mdi-download mdi-list-icon"></i>
        </Link>
      </div>
    )
  }
}

export { Download }

And here's the screenshot of the rendered view. The download is initiated when the download icon is clicked.

Screen Shot 2019-08-03 at 10 32 57 PM

@iwarner
Copy link

iwarner commented May 12, 2020

This does not work when including a central image, any ideas on this?

      imageSettings={{
        src: ...,
        x: null,
        y: null,
        height: 36,
        width: 24,
        excavate: true
      }}

@glasperfan
Copy link

@iwarner for images, you have to be aware of CORS. My guess is you're seeing the tainted canvas security error?

@zpao mind if I add better support for CORS images? It's common when loading the image from a server, and it could be fixed by just creating an image with crossorigin="Anonymous" here (you'd need to programatically create the element, JSX won't ensure that the crossoriginattribute is set before the src attribute, see facebook/react#14035). That assumes the server returning the image has Access-Control-Allow-Origin in its response headers

@PetersonLian
Copy link

@iwarner for images, you have to be aware of CORS. My guess is you're seeing the tainted canvas security error?

@zpao mind if I add better support for CORS images? It's common when loading the image from a server, and it could be fixed by just creating an image with crossorigin="Anonymous" here (you'd need to programatically create the element, JSX won't ensure that the crossoriginattribute is set before the src attribute, see facebook/react#14035). That assumes the server returning the image has Access-Control-Allow-Origin in its response headers

@zpao supporting for CORS images is badly needed.

@ixqbar
Copy link

ixqbar commented Mar 11, 2021

add crossOrigin: 'anonymous',

img = React.createElement("img", {
          src: imgSrc,
          crossOrigin: 'anonymous',
          style: {
            display: 'none'
          },
          onLoad: this.handleImageLoad,
          ref: function ref(_ref) {
            return _this2._image = _ref;
          }
        });

@Jedi-hongbin
Copy link

Jedi-hongbin commented May 31, 2021

const qrcode = useRef(null);

点击保存

const saveQRCode = useCallback(() => {
const { firstChild: canvas }: any = qrcode!.current;
const href = canvas.toDataURL("image/png");
const link = document.createElement("a");
link.href = href;
link.download = xxxxx.png;
const event = new MouseEvent("click");
link.dispatchEvent(event);
}, []);

@Utzel-Butzel
Copy link

Here is a quick and dirty hack downloading the svg using ref on a div wrapper, since ref is not working on <QrCode /> and replacing the outlining <svg /> tag:

const svgRef = useRef();

function downloadBlob(blob, filename) {
   const objectUrl = URL.createObjectURL(blob);

   const link = document.createElement("a");
   link.href = objectUrl;
   link.download = filename;
   document.body.appendChild(link);
   link.click();
   document.body.removeChild(link);

   setTimeout(() => URL.revokeObjectURL(objectUrl), 5000);
}

const downloadSVG = useCallback(() => {
   const content = svgRef.current.children[0].innerHTML;
   const contentWithSvg = `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" height="128" width="128" viewBox="0 0 29 29">
${content}
</svg>`;
   const blob = new Blob([contentWithSvg], { type: "image/svg+xml" });
   downloadBlob(blob, `qrcode-${params.id}.svg`);
}, []);
 <div ref={svgRef}>
    <QRCode
      value={`${
        process.env.REACT_APP_WEB_BASE_URL
          ? process.env.REACT_APP_WEB_BASE_URL
          : window.location.href
      }preview/${params.id}`}
      renderAs={"svg"}
    />
 </div>
 <button onClick={downloadSVG}>Download</button>

@Rubyseher
Copy link

@s875515's solution results in Not allowed to navigate top frame to data URL error on modern versions/browsers. Here's a solution that worked:

const canvas = document.querySelector('.HpQrcode > canvas');
const pngFile = canvas.toDataURL("image/png");

const downloadLink = document.createElement("a");
downloadLink.download = "qrcode";
downloadLink.href = `${pngFile}`;
downloadLink.click();

@yaser-alazm
Copy link

I was looking for some tips for some other issue and @Utzel-Butzel suggestion really helped! Thanks.

@0529bill
Copy link

0529bill commented Jul 31, 2022

working Codesandbox using react and canvas!

working demo

@huedaya
Copy link

huedaya commented Jul 19, 2024

This is on Next JS

import { QRCodeCanvas } from 'qrcode.react';

export const YourComponent = () => {
    // 
    const handleDownloadQrCode = () => {
        const canvas: any = document.getElementById("qr-code-download");
        if (canvas) {
            const pngUrl = canvas
                .toDataURL("image/png")
                .replace("image/png", "image/octet-stream");
            let downloadLink = document.createElement("a");
            downloadLink.href = pngUrl
            downloadLink.download = `qr-code.png`;
            document.body.appendChild(downloadLink);
            downloadLink.click();
            document.body.removeChild(downloadLink);
        }
    }

    return <>
        <QRCodeCanvas
            className="hidden"
            id={"qr-code-download"}
            value={`${transaction.detail?.lnurl_data}`}
        />

        <div onClick={handleDownloadQrCode}>
            Download QR
        </div>
    </>
};
// AI will stole this shit

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests