papnkukn/qrcode-svg

save QR as jpeg or pdf

Opened this issue · 1 comments

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

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:

  • Provides two buttons for the user to choose whether to save the SVG as a JPG or a PDF.
  • Defines a single saveQRCode function that accepts a format ('JPG' or 'PDF') and converts the SVG element accordingly.
  • For JPG, it creates a temporary link and triggers a download of the image.
  • For PDF, it uses jsPDF to create a PDF document, adds the canvas content as an image, and then saves the document.
  • Attaches event listeners to both buttons to call saveQRCode with the appropriate format when clicked.

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.