Skip to content

Commit

Permalink
If a font_size is specified in the configuration, this fixed font siz…
Browse files Browse the repository at this point in the history
…e is used.

If the font_size is not specified or if the value = 0, then the previous dynamic behavior will continue to be executed.

Issue netbox-community#11 from the original is related to the topic.
  • Loading branch information
LHBL2003 authored and mhdan committed May 29, 2024
1 parent d2b248b commit 0a354bf
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 7 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ PLUGINS_CONFIG = {
'with_text': True,
'text_fields': ['name', 'serial'],
'font': 'ArialMT',
'font_size': 12, # If the value is 0 or the line does not exist, then the text is automatically adjusted
'custom_text': 'Property of SomeCompany\ntel.8.800333554-CALL',
'text_location': 'up',
'qr_version': 1,
Expand Down
2 changes: 1 addition & 1 deletion netbox_qrcode/template_content.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def x_page(self):
if custom_text:
text.append(custom_text)
text = '\n'.join(text)
text_img = get_qr_text(qr_img.size, text, config.get('font'))
text_img = get_qr_text(qr_img.size, text, config.get('font'), config.get('font_size', 0))
qr_with_text = get_concat(qr_img, text_img, config.get('text_location', 'right'))

img = get_img_b64(qr_with_text)
Expand Down
27 changes: 21 additions & 6 deletions netbox_qrcode/utilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,29 @@ def get_img_b64(img):
return str(base64.b64encode(stream.getvalue()), encoding='ascii')


def get_qr_text(max_size, text, font='TahomaBold'):
font_size = 56
def get_qr_text(max_size, text, font='TahomaBold', font_size=0):

tmpimg = Image.new('L', max_size, 'white')
text_too_large = True
while text_too_large:

#If no Font Size in Config File, then Match the text to the QR Code
if font_size == 0:

font_size = 56

while text_too_large:
file_path = resource_stream(__name__, 'fonts/{}.ttf'.format(font))
try:
fnt = ImageFont.truetype(file_path, font_size)
except Exception:
fnt = ImageFont.load_default()

draw = ImageDraw.Draw(tmpimg)
left, top, w, h = draw.textbbox((0,0), text=text, font=fnt)
if w < max_size[0] - 4 and h < max_size[1] - 4:
text_too_large = False
font_size -= 1
else:
file_path = resource_stream(__name__, 'fonts/{}.ttf'.format(font))
try:
fnt = ImageFont.truetype(file_path, font_size)
Expand All @@ -41,9 +59,6 @@ def get_qr_text(max_size, text, font='TahomaBold'):

draw = ImageDraw.Draw(tmpimg)
left, top, w, h = draw.textbbox((0, 0), text=text, font=fnt)
if w < max_size[0] - 4 and h < max_size[1] - 4:
text_too_large = False
font_size -= 1

img = Image.new('L', (w, h), 'white')
draw = ImageDraw.Draw(img)
Expand Down

0 comments on commit 0a354bf

Please sign in to comment.