papnkukn / qrcode-svg

A simple QR Code generator in pure JavaScript / node.js library
MIT License
442 stars 92 forks source link

save QR as jpeg or pdf #30

Open hubono opened 1 year ago

hubono commented 1 year ago

Hi, Can you add the function to save the generated QR as PDF or Jpeg

cc46808 commented 7 months ago

Hi, Can you add the function to save the generated QR as PDF or Jpeg

@hubono JPG and PDF

<button id="saveJpgBtn" class="btn btn-primary">Save as JPG</button>
<button id="savePdfBtn" class="btn btn-secondary">Save as PDF</button>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.3.1/jspdf.umd.min.js"></script>

<script>
function saveQRCode(format) {
    const svgElement = document.querySelector('svg');
    if (!svgElement) {
        console.error('SVG Element is not defined');
        return;
    }

    const canvas = document.createElement('canvas');
    canvas.width = svgElement.clientWidth;
    canvas.height = svgElement.clientHeight;
    const ctx = canvas.getContext('2d');
    const img = new Image();
    const svgBlob = new Blob([new XMLSerializer().serializeToString(svgElement)], {type: 'image/svg+xml;charset=utf-8'});
    const url = URL.createObjectURL(svgBlob);

    img.onload = function() {
        ctx.drawImage(img, 0, 0);
        URL.revokeObjectURL(url); // Clean up the URL object

        if (format === 'JPG') {
            // Process and save as JPG
            const jpegUrl = canvas.toDataURL('image/jpeg');
            const downloadLink = document.createElement('a');
            downloadLink.href = jpegUrl;
            downloadLink.download = 'qrcode.jpg';
            document.body.appendChild(downloadLink);
            downloadLink.click();
            document.body.removeChild(downloadLink);
        } else if (format === 'PDF') {
            // Process and save as PDF using jsPDF
            const pdf = new jspdf.jsPDF({
                orientation: 'p',
                unit: 'px',
                format: [canvas.width, canvas.height]
            });
            pdf.addImage(canvas.toDataURL('image/jpeg', 1.0), 'JPEG', 0, 0, canvas.width, canvas.height);
            pdf.save('qrcode.pdf');
        }
    };

    img.src = url;
}

document.getElementById('saveJpgBtn').addEventListener('click', () => saveQRCode('JPG'));
document.getElementById('savePdfBtn').addEventListener('click', () => saveQRCode('PDF'));
</script>

This code does the following:

Make sure the SVG element you want to convert is correctly selected by document.querySelector('svg'), and adjust as necessary for your specific use case.