DEV Community

Cover image for Building a Dynamic QR Code Generator with JavaScript and QRCode.js
Ezhill Ragesh
Ezhill Ragesh

Posted on

Building a Dynamic QR Code Generator with JavaScript and QRCode.js

In today’s digital age, QR codes have become an integral part of our lives. Whether it’s for business, marketing, or just sharing information, creating QR codes on the fly can be incredibly useful. In this guide, we’ll walk through the process of getting started with JavaScript to dynamically generate QR codes. You don’t need to be a coding expert — we’ll break it down into simple steps.

Dive Directly into code : https://github.com/ezhillragesh/filetoQR

Setting Up Your HTML File

Begin by creating a basic HTML file. Make sure you have a file input element to allow users to upload text files. This will serve as the source for generating QR codes.

<input type=”file” id=”#input-text">
<div class="qr-code-container">

  <div id="qr-code" class="qr-code" style="display: none;"></div>
  <button id="button" type="submit" class="button generate-button">Generate QR Code</button>

 <button id="downloadAll" type="submit" class="button download">Download</button>
</div>
Enter fullscreen mode Exit fullscreen mode

Reading Your File Content

Next, let’s write a JavaScript function to read the content of the uploaded text file. We’ll use the FileReader API for this.

function getFile(target) {
    const input = target;
    if ('files' in input && input.files.length > 0) {
        placeFileContent(
            document.getElementById('input_text'),
            input.files[0])
    }
}

function placeFileContent(target, file) {
    readFileContent(file).then(content => {
        target.value = content;
    }).catch(error => console.log(error));
}

function readFileContent(file) {
    const reader = new FileReader();
    return new Promise((resolve, reject) => {
        reader.onload = event => resolve(event.target.result);
        reader.onerror = error => reject(error);
        reader.readAsText(file);
    });
}
Enter fullscreen mode Exit fullscreen mode

Generating QR Codes Dynamically

Function Parameters:

user_input: This parameter represents the user's input, typically a string of text. It is expected to be the content that needs to be encoded into QR codes.

QR Code Chunking:

The function begins by defining a chunk size (currently set to 300 characters). It then retrieves the user’s input text.

Clearing Existing Content:

The function starts by clearing any existing QR codes and information messages on the webpage. This ensures a clean slate for the new QR code generation.

Creating Row Containers:

It initializes a row container using the createRowContainer function. This container is a div element that will hold a row of QR codes.

Iterating Through Text:

The function then iterates through the input text in chunks determined by the chunk size. For each chunk, it generates a QR code using the generateQRCode function.

The Chunk size set to 300 becuase a QR code can oly be read if it has ≥300 Chars, But the QR code can store upto 1250+ Chars.

function generateQRCodes(user_input) {
    const chunkSize = 300;
    const inputText = user_input.value;


    document.querySelector("#qr-code").innerHTML = "";
    document.getElementById("info").innerHTML = "";


    let rowContainer = createRowContainer();

    let qrCounter = 0; 

    for (let i = 0; i < inputText.length; i += chunkSize) {
        let chunk = inputText.substring(i, i + chunkSize);
        generateQRCode(rowContainer, chunk);

        qrCounter++;

        if (qrCounter === 5) {

            rowContainer = createRowContainer();
            qrCounter = 0; 
        }
    }



}
Enter fullscreen mode Exit fullscreen mode

Next let’s make a function that generates a QR code and appends it to a specified row container on the webpage.

function generateQRCode(rowContainer, text) {
    var qrContainer = document.createElement("div");
    qrContainer.classList.add("inline-block", "mx-4");

    var qrcode = new QRCode(qrContainer, {
        text: text,
        width: 180,
        height: 180,
        colorDark: "#000000",
        colorLight: "#ffffff",
        correctLevel: QRCode.CorrectLevel.H
    });

    rowContainer.appendChild(qrContainer);
}
Enter fullscreen mode Exit fullscreen mode

How it Works ?

**Container Creation: **Creates a new div element (qrContainer) to hold the QR code. Applies styling classes for proper layout.

**QR Code Generation: **Utilizes the QRCode.js library to create a QR code inside the qrContainer. Configures the QR code properties, including the provided text, dimensions, and color options.(You can modify this according to your choice)

**Appending to Row: **Appends the generated qrContainer (containing the QR code) to the specified rowContainer.

Now we are all set we have genrated the QR code from the text file. But we are missing something, Yeah that’s right we need to download the generated QR code.

Download All QR Codes

The downloadAll function facilitates the bulk download of QR codes generated on the webpage.

function downloadAll() {
    var qrContainers = document.querySelectorAll("#qr-code > .row-container");

    qrContainers.forEach((rowContainer, rowIndex) => {
        var qrCodes = rowContainer.querySelectorAll("canvas");

        qrCodes.forEach((canvas, colIndex) => {
            var link = document.createElement("a");
            link.setAttribute("download", `qr_code_${rowIndex + 1}_${colIndex + 1}.png`);
            link.href = canvas.toDataURL();
            link.click();
        });
    });
}
Enter fullscreen mode Exit fullscreen mode

Selection of Containers:

The function starts by selecting all row containers within the #qr-code element, which hold the generated QR codes.

Iteration through Rows and Columns:

It iterates through each row container, extracting individual QR codes represented by canvas elements.

Dynamic Link Generation:

For each QR code, the function creates a dynamic download link with a filename based on the row and column indices.

Setting Link Attributes:

The link is set to download the QR code as a PNG file and is assigned the data URL of the canvas image.

Automated Click Trigger:

The function triggers a click event on the dynamically generated link, initiating the download process for each QR code.

Map the Functions to our button

btn.addEventListener("click", () => {
    let user_input = document.querySelector("#input_text");
    if (user_input.value !== "") {
        document.querySelector("#qr-code").style = "";
        generateQRCodes(user_input);
    } else {
        document.querySelector("#qr-code").style = "display: none";
        console.log("not valid input");
    }
    let downloadAllBtn = document.getElementById("downloadAll") 
    downloadAllBtn.addEventListener("click", downloadAll);

});
Enter fullscreen mode Exit fullscreen mode

In wrapping up this journey into the world of dynamic QR code generation using JavaScript, you’ve learned how to empower your web applications with a user-friendly tool for encoding information into QR codes on the fly. By simply uploading text files or entering text, you can quickly generate QR codes that cater to various applications, from sharing links to facilitating efficient data transfer.

Feel free to explore the live demonstration of this project hosted at **FileToQR.** Witness firsthand how the integration of JavaScript, QRCode.js.

Your feedback is invaluable, and I’d love to hear your thoughts! Connect with me on Twitter for updates, questions, or to share your experiences with this QR code generation project. Thank you for joining me on this coding adventure, and

Happy Coding! 🚀🌐

Top comments (0)