[Drupal 8] How to generate QR code from text in a Drupal site?

May 09, 2016 - 07:45

Using composer, add the required libraries. For generating a QR code for a text in drupal 8, follow the steps below.

  1. Install the phpqrcode library using composer.
    composer require aferrandini/phpqrcode
  2. In your custom module, create a php file, inside the 'src' folder (example: QrCodeGenerate.php) for handling the QRcode generation.
  3. Create a class say QrCodeGenerate. Place the following code in the class 'QrCodeGenerate'.
    
          public function generateQrCodes($qr_text) {
          // The below code will automatically create the path for the img.
          $path = '';
          $directory = "public://Images/QrCodes/";
          file_prepare_directory($directory, FILE_MODIFY_PERMISSIONS | FILE_CREATE_DIRECTORY);
          // Name of the generated image.
          $qrName = 'myQrcode'.
          $uri = $directory . $qrName . '.png'; // Generates a png image.
          $path = drupal_realpath($uri);
          // Generate QR code image.
          \PHPQRCode\QRcode::png($qr_text, $path, 'L', 4, 2);
          return $path;
        }
        
  4. Add use \Drupal\file\Entity\File; in your php file.

Now you can use the function generateQrCodes() to generate a QR code image from anywhere in your project. Hope that helps.