#!/usr/bin/env python3 import os.path from qrcode import make as qrcode_make import qrcode.image.svg from svgutils import transform as st from ch_kreuz import swisscross as get_swisscross from ch_kreuz import white as get_white from svgutils.compose import Figure from chardet import detect class qr_rechnung(): data = '' error_correction = None def __init__(self, data=None, textfile=None): if textfile is not None: self.set_data_from_textfile(textfile) def set_data(self, data): self.data = data self.data = data.encode('latin-1') def set_data_from_textfile(self, textfile): with open(textfile, 'rb') as rawdata: charenc = detect(rawdata.read())['encoding'] with open(textfile, 'r', encoding=charenc) as f: self.set_data(f.read()) def write_file(self, filepath, force=False): global qrcode mode = 'w' if force else 'x' try: assert force or not os.path.isfile(filepath) img = qrcode.make( self.data, error_correction=qrcode.constants.ERROR_CORRECT_M, image_factory=qrcode.image.svg.SvgPathImage ) img.save(filepath) except AssertionError: print(f"ERROR: Datei {filepath} existiert bereits.") return 1 qrcode = st.fromfile(filepath) try: assert qrcode.width[-2:] == 'mm' qr_scale = 49.5/float(qrcode.width[:-2]) except AssertionError as e: print(f"ERROR: Ein unerwarteter Fall in der Skallierung.") print(e) return 1 qrr = Figure( '49.5mm', '49.5mm', get_white().getroot(), qrcode.getroot().scale(qr_scale), get_swisscross().getroot() ) qrr.save(filepath) def help(args): return '\n'.join([ '{0}: Ungültige Eingabe', 'Aufruf: {0} TEXTDATEI [SVG-ZIELDATEI]', ]).format(args[0]) def main(args): try: textfile = args[1] except IndexError: print(help(args)) return 1 try: output_format = 'svg' svgfile = args[2] if svgfile[-4:] == '.svg': pass else: svgfile += '.svg' except IndexError: try: assert textfile[-4:] == '.txt' svgfile = textfile[:-4]+'.svg' except AssertionError: print(help(args)) return 1 try: x = qr_rechnung(textfile=textfile) x.write_file(svgfile, force=False) except (PermissionError, FileNotFoundError) as e: print(e) return 1 if output_format == 'svg': return 0 else: print(f"ERROR: Unbekanntes Output_format: {output_format}") return 1 if __name__ == '__main__': import sys sys.exit(main(sys.argv))