diff --git a/changelog.d/2887.added.md b/changelog.d/2887.added.md new file mode 100644 index 0000000000..28c12cd66b --- /dev/null +++ b/changelog.d/2887.added.md @@ -0,0 +1 @@ +Add functionality to create QR codes to a given url \ No newline at end of file diff --git a/python/nav/web/seeddb/utils/generate_qr_code.py b/python/nav/web/seeddb/utils/generate_qr_code.py new file mode 100644 index 0000000000..524c28476d --- /dev/null +++ b/python/nav/web/seeddb/utils/generate_qr_code.py @@ -0,0 +1,55 @@ +# -*- coding: utf-8 -*- +# +# Copyright (C) 2024 Sikt +# +# This file is part of Network Administration Visualized (NAV). +# +# NAV is free software: you can redistribute it and/or modify it under the +# terms of the GNU General Public License version 3 as published by the Free +# Software Foundation. +# +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS +# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more +# details. You should have received a copy of the GNU General Public License +# along with NAV. If not, see . +# + +import base64 +import io +import os + +import nav.web + +import qrcode +from PIL import ImageDraw, ImageFont + + +def generate_qr_code(url: str, name: str = "") -> str: + """ + Generate a QR code from a given url, and, if given, adds the name below as a + caption + + Returns the generated image as a byte string + """ + # Creating QR code + qr = qrcode.QRCode(box_size=20) + qr.add_data(url) + img = qr.make_image() + draw = ImageDraw.Draw(img) + + # Adding the name as caption + if name: + W, H = img.size + font_dir = os.path.dirname(nav.web.__file__) + font = ImageFont.truetype(os.path.join(font_dir, "static/fonts/OS600.woff"), 50) + w = font.getlength(name) + draw.text(((W - w) / 2, H * 0.9), text=name, font=font, fill="black") + + # Turning image into byte string + data = io.BytesIO() + img.save(data, "JPEG") + encoded_img_data = base64.b64encode(data.getvalue()) + out = encoded_img_data.decode('utf-8') + + return out diff --git a/requirements/base.txt b/requirements/base.txt index 4af7fd589e..fbb564dc24 100644 --- a/requirements/base.txt +++ b/requirements/base.txt @@ -9,7 +9,9 @@ pyaml twisted~=23.8.0 # last version that still supports Python 3.7 networkx==2.6.3 +# Cannot be removed as long as qrcode is included Pillow>3.3.2 +qrcode>7.4 pyrad==2.1 sphinx==5.3.0 sphinxcontrib-programoutput==0.17 diff --git a/tests/unittests/web/generate_qr_code_test.py b/tests/unittests/web/generate_qr_code_test.py new file mode 100644 index 0000000000..f4acce99ef --- /dev/null +++ b/tests/unittests/web/generate_qr_code_test.py @@ -0,0 +1,6 @@ +from nav.web.seeddb.utils.generate_qr_code import generate_qr_code + + +def test_generate_qr_code_returns_string(): + qr_code = generate_qr_code(url="www.example.com", name="buick.lab.uninett.no") + assert isinstance(qr_code, str)