ant-design/components/qr-code/demo/download.tsx
kiner-tang d8c98e18ab
demo: Add svg qrcode download demo (#49553)
* feat: add download qrcode when render type is svg

* feat: optimize code

* feat: optimize code

* feat: optimize code

* feat: optimize code
2024-06-22 17:33:06 +08:00

59 lines
1.7 KiB
TypeScript

import React from 'react';
import { Button, QRCode, Segmented, Space } from 'antd';
import type { QRCodeProps } from 'antd';
function doDownload(url: string, fileName: string) {
const a = document.createElement('a');
a.download = fileName;
a.href = url;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
const downloadCanvasQRCode = () => {
const canvas = document.getElementById('myqrcode')?.querySelector<HTMLCanvasElement>('canvas');
if (canvas) {
const url = canvas.toDataURL();
doDownload(url, 'QRCode.png');
}
};
const downloadSvgQRCode = () => {
const svg = document.getElementById('myqrcode')?.querySelector<SVGElement>('svg');
const svgData = new XMLSerializer().serializeToString(svg!);
const blob = new Blob([svgData], { type: 'image/svg+xml;charset=utf-8' });
const url = URL.createObjectURL(blob);
doDownload(url, 'QRCode.svg');
};
const App: React.FC = () => {
const [renderType, setRenderType] = React.useState<QRCodeProps['type']>('canvas');
return (
<Space id="myqrcode" direction="vertical">
<Segmented
options={['canvas', 'svg']}
onChange={(val) => setRenderType(val as QRCodeProps['type'])}
/>
<div>
<QRCode
type={renderType}
value="https://ant.design/"
bgColor="#fff"
style={{ marginBottom: 16 }}
icon="https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg"
/>
<Button
type="primary"
onClick={renderType === 'canvas' ? downloadCanvasQRCode : downloadSvgQRCode}
>
Download
</Button>
</div>
</Space>
);
};
export default App;