def cria_pdf(self, loja):
     from reportlab.pdfgen import canvas
     from reportlab.lib.units import cm
     from reportlab.lib.pagesizes import A4
     from datetime import datetime, timedelta
     import time
     width, height = A4
     c = canvas.Canvas("db/dados.pdf", pagesize=A4)
     data = datetime.now().date()
     c.setFont('Helvetica-Bold', 10)
     c.drawRightString(width - 1.5 * cm, height - 8.2 * cm, str(data))
     c.drawRightString(width - 4 * cm, height - 8.2 * cm,
                       str(data + timedelta(days=5)))
     c.drawRightString(width - 6.5 * cm, height - 8.2 * cm,
                       str(loja.usr.cliente))
     linha = height - 9.3 * cm
     ls = 0.525 * cm
     c.setFont('Helvetica', 8)
     for li in range(loja.carrinho.__len__()):
         aux = loja.carrinho[li]
         c.drawCentredString(1.5 * cm, linha - (li * ls), str(aux.codigo))
         c.drawString(2.4 * cm, linha - (li * ls), str(aux.artigo))
         c.drawRightString(width - 4.85 * cm, linha - (li * ls),
                           str(aux.quantidade))
         c.drawRightString(width - 3.32 * cm, linha - (li * ls),
                           loja.moeda(aux.custo))
         c.drawRightString(width - 2.82 * cm, linha - (li * ls), str('23'))
         c.drawRightString(width - 1.07 * cm, linha - (li * ls),
                           loja.moeda(aux.total()))
     c.drawString(7 * cm, 3.15 * cm,
                  "(c) Copyright 2019 Gonçalo Figueiredo")
     texto = c.beginText(10.8 * cm, height - 2.5 * cm)
     texto.setFont('Helvetica-Bold', 14)
     texto.textLine("Encomenda")
     texto.textLine(' ')
     texto.setFont('Helvetica', 10)
     texto.textLine("Exmo.(s) Sr.(s)")
     texto.textLine(' ')
     texto.setFont('Helvetica-Bold', 10)
     texto.textLine(loja.usr.nome)
     texto.setFont('Helvetica', 10)
     for line in loja.usr.morada.splitlines(False):
         texto.textLine(line.rstrip())
     texto.setFont('Helvetica-Bold', 10)
     texto.textLine(' ')
     texto.textLine('NIF: ' + loja.usr.nif)
     c.drawText(texto)
     total = loja.total()
     mercadorias = total / 1.23
     iva = total - mercadorias
     c.setFont('Helvetica', 10)
     s = 0.53
     b = 5.5
     c.drawRightString(width - 1.0 * cm, (4 * s + b) * cm,
                       loja.moeda(mercadorias))
     c.drawRightString(width - 1.0 * cm, (3 * s + b) * cm, loja.moeda(0))
     c.drawRightString(width - 1.0 * cm, (2 * s + b) * cm, loja.moeda(0))
     c.drawRightString(width - 1.0 * cm, (1 * s + b) * cm, loja.moeda(iva))
     c.drawRightString(width - 1.0 * cm, (0 * s + b) * cm, loja.moeda(0))
     total_items = 0
     for linha in range(loja.carrinho.__len__()):
         total_items += loja.carrinho[linha].quantidade
     c.drawString(3.7 * cm, 8.67 * cm, str(total_items))
     c.setFont('Helvetica', 8)
     c.drawString(2.7 * cm, 6.65 * cm, loja.moeda(mercadorias))
     c.drawString(5.45 * cm, 6.65 * cm, loja.moeda(iva))
     c.setFont('Helvetica-Bold', 18)
     c.drawRightString(width - 1.0 * cm, 4.5 * cm, loja.moeda(total))
     # ----------------- QR CODE ----------------
     t = str(int(time.time() * 100000))
     code = t[10:12] + ' ' + t[12:15] + '/' + t[0:10]
     file = 'F' + t[10:15] + '_' + t[0:10] + '.pdf'
     c.setFont('Helvetica-Bold', 15)
     c.drawRightString(width - 1 * cm, height - 1.5 * cm, str(code))
     import qrcode
     qr = qrcode.QRCode()
     qr.add_data(code)
     img = qr.make_image(fill_color="#005", back_color="#ffe")
     c.drawInlineImage(img,
                       width - 4 * cm,
                       height - 4.6 * cm,
                       width=3 * cm,
                       height=3 * cm)
     # ------------------------------------------
     c.showPage()
     c.save()
     self.merge_pdf(file)
     self.envia_pdf(file, loja.usr.email)
     return file
    def firmar_documento(self, xml_firma, tipo_cfe):
        # URL del WS y su clave en parámetros del sistema
        key_firmar = KEY_URL_TESTING
        if self.es_produccion():
            key_firmar = KEY_URL_PRODUCCION
        sys_cfg = self.env['ir.config_parameter']
        url_firmar = sys_cfg.get_param(key_firmar)
        try:
            client = Client(url_firmar)
        except:
            raise UserError(u'¡ No se pudo conectar !'
                            '\n'
                            u'Intente más tarde.')

        try:
            sign_result = client.service.Execute(xml_firma, tipo_cfe,
                                                 self.number)
            #self.sign_result = client.service.Execute(xml_firma, tipo_cfe, self.number)
            if not self.hay_error(sign_result):
                # Firmado con éxito
                self.carga_datos_firma(tipo_cfe, sign_result)
                # Generacion de QR
                if self.fe_URLParaVerificarQR:
                    # QR tamaño 1

                    qr = qrcode.QRCode(
                        version=1,
                        error_correction=qrcode.constants.ERROR_CORRECT_L,
                        box_size=20,
                        border=4,
                    )
                    qr.add_data(
                        self.fe_URLParaVerificarQR
                    )  # you can put here any attribute SKU in my case
                    qr.make(fit=True)
                    img = qr.make_image()
                    buffer = BytesIO()
                    img.save(buffer, format="PNG")
                    img_str = base64.b64encode(buffer.getvalue())
                    self.qr_img = img_str

            else:
                mensaje = self.get_error(sign_result)
                return (False, mensaje)

            _logger.error(
                "%s",
                "===========================================================")
            _logger.error("%s", xml_firma)
            _logger.error(
                "%s",
                "===========================================================")
            _logger.error("%s", sign_result)
            _logger.error(
                "%s",
                "===========================================================")
        except WebFault:
            print("===================================================")
            print("ERROR: No se pudo consumir el WS de firmar")
            print("===================================================")
            raise UserError(u'¡ Error al intentar firmar !'
                            '\n'
                            u'La firma electrónica no se realizó.')
            # except WebFault, detalle:

        if self.hay_error(sign_result):
            mensaje = self.get_error(sign_result)
            return (False, mensaje)
        else:
            # Firmado con éxito
            return (True, '')
import qrcode
import cv2
import matplotlib.pyplot as plt

qr = qrcode.QRCode(
    version=1,
    error_correction=qrcode.constants.ERROR_CORRECT_L,
    box_size=10,
    border=4,
)

data = 'https://github.com/tassosv/qr-code-image'
qr.add_data(data)
qr.make(fit=True)

img = qr.make_image(fill_color="black", back_color="white")
img.save('git_page.png')

im = cv2.imread('git_page.png')
im_resized = cv2.resize(im, (224, 224), interpolation=cv2.INTER_LINEAR)

plt.imshow(cv2.cvtColor(im_resized, cv2.COLOR_BGR2RGB))
plt.show()
Beispiel #4
0
#  pip3 install qrcode[pil]

import qrcode

# QR positioned on left of the DeepRacer
qr = qrcode.QRCode(
    version=1,
    error_correction=qrcode.constants.ERROR_CORRECT_H,
    box_size=200,
    border=1,
)
qr.add_data('DR: {"wp": 1, "p": "l"}')
img = qr.make_image(fill_color="black", back_color="white")
img.save("deepracer_offroad_qr_images/left_wp1.png")
print(f"Printed QR Code")

# QR positioned on right of the DeepRacer
qr = qrcode.QRCode(
    version=1,
    error_correction=qrcode.constants.ERROR_CORRECT_H,
    box_size=200,
    border=1,
)
qr.add_data('DR: {"wp": 1, "p": "r"}')
img = qr.make_image(fill_color="black", back_color="white")
img.save("deepracer_offroad_qr_images/right_wp1.png")
print(f"Printed QR Code")

# Hairpin Right
qr = qrcode.QRCode(
    version=1,
Beispiel #5
0
    except Exception, e:
        if "username is not unique" in str(e):
            print "ERROR: That username is already taken!"
        else:
            print "ERROR: An unknown error occurred, traceback:"
            print e
    else:
        print "Admin '{}' successfully added".format(username)
        if not otp_secret:
            # Print the QR code for Google Authenticator
            print
            print "Scan the QR code below with Google Authenticator:"
            print
            uri = admin.totp.provisioning_uri(username,
                                              issuer_name="SecureDrop")
            qr = qrcode.QRCode()
            qr.add_data(uri)
            qr.print_ascii(tty=sys.stdout.isatty())
            print
            print "If the barcode does not render correctly, try changing your terminal's font, (Monospace for Linux, Menlo for OS X)."
            print "If you are using iTerm on Mac OS X, you will need to change the \"Non-ASCII Font\", which is your profile's Text settings."
            print
            print "Can't scan the barcode? Enter the shared secret manually: {}".format(
                admin.formatted_otp_secret)
            print


def clean_tmp():
    """Cleanup the SecureDrop temp directory. This is intended to be run as an
    automated cron job. We skip files that are currently in use to avoid
    deleting files that are currently being downloaded."""
Beispiel #6
0
 def print_qrcode(self, code):
     qr = qrcode.QRCode(version=1, border=4)
     qr.add_data(code)
     self.write('\x00')
     self._print_matrix(qr.get_matrix())
Beispiel #7
0
 def _str2qr(self, str):
     qr = qrcode.QRCode()
     qr.border = 1
     qr.add_data(str)
     mat = qr.get_matrix()
     self._printQR(mat)  # qr.print_tty() or qr.print_ascii()
Beispiel #8
0
def _add_user(is_admin: bool = False,
              context: Optional[AppContext] = None) -> int:
    with context or app_context():
        username = _get_username()
        first_name = _get_first_name()
        last_name = _get_last_name()

        print("Note: Passwords are now autogenerated.")
        password = _make_password()
        print("This user's password is: {}".format(password))

        is_hotp = _get_yubikey_usage()
        otp_secret = None
        if is_hotp:
            while True:
                otp_secret = obtain_input(
                    "Please configure this user's YubiKey and enter the "
                    "secret: ")
                if otp_secret:
                    tmp_str = otp_secret.replace(" ", "")
                    if len(tmp_str) != 40:
                        print("The length of the secret is not correct. "
                              "Expected 40 characters, but received {0}. "
                              "Try again.".format(len(tmp_str)))
                        continue
                if otp_secret:
                    break

        try:
            user = Journalist(username=username,
                              first_name=first_name,
                              last_name=last_name,
                              password=password,
                              is_admin=is_admin,
                              otp_secret=otp_secret)
            db.session.add(user)
            db.session.commit()
        except Exception as exc:
            db.session.rollback()
            if "UNIQUE constraint failed: journalists.username" in str(exc):
                print('ERROR: That username is already taken!')
            else:
                exc_type, exc_value, exc_traceback = sys.exc_info()
                print(
                    repr(
                        traceback.format_exception(exc_type, exc_value,
                                                   exc_traceback)))
            return 1
        else:
            print('User "{}" successfully added'.format(username))
            if not otp_secret:
                # Print the QR code for FreeOTP
                print('\nScan the QR code below with FreeOTP:\n')
                uri = user.totp.provisioning_uri(username,
                                                 issuer_name='SecureDrop')
                qr = qrcode.QRCode()
                qr.add_data(uri)
                qr.print_ascii(tty=sys.stdout.isatty())
                print('\nIf the barcode does not render correctly, try '
                      "changing your terminal's font (Monospace for Linux, "
                      'Menlo for OS X). If you are using iTerm on Mac OS X, '
                      'you will need to change the "Non-ASCII Font", which '
                      "is your profile\'s Text settings.\n\nCan't scan the "
                      'barcode? Enter following shared secret manually:'
                      '\n{}\n'.format(user.formatted_otp_secret))
        return 0
Beispiel #9
0
import qrcode
data = "www.baidu.com"
qr = qrcode.QRCode(
    version=4,  # 二维码的实际大小级别(1 - 40)
    error_correction=qrcode.constants.ERROR_CORRECT_L,  # 二维码的容错级别(L,M(默认),Q,H)
    box_size=10,  # 整张二维码图片的大小
    border=5,  # 二维码背景边框宽度
)
qr.add_data(data)
qr.make(fit=True)
img = qr.make_image()
img.save('test.png')  # 将图片保存为png(注意其他格式可能会出现问题)
print("OK")
Beispiel #10
0
    def qr(self,
           content,
           ec=QR_ECLEVEL_L,
           size=3,
           model=QR_MODEL_2,
           native=False,
           center=False,
           impl="bitImageRaster"):
        """ Print QR Code for the provided string

        :param content: The content of the code. Numeric data will be more efficiently compacted.
        :param ec: Error-correction level to use. One of QR_ECLEVEL_L (default), QR_ECLEVEL_M, QR_ECLEVEL_Q or
            QR_ECLEVEL_H.
            Higher error correction results in a less compact code.
        :param size: Pixel size to use. Must be 1-16 (default 3)
        :param model: QR code model to use. Must be one of QR_MODEL_1, QR_MODEL_2 (default) or QR_MICRO (not supported
            by all printers).
        :param native: True to render the code on the printer, False to render the code as an image and send it to the
            printer (Default)
        :param center: Centers the code *default:* False
        :param impl: Image-printing-implementation, refer to :meth:`.image()` for details
        """
        # Basic validation
        if ec not in [QR_ECLEVEL_L, QR_ECLEVEL_M, QR_ECLEVEL_H, QR_ECLEVEL_Q]:
            raise ValueError("Invalid error correction level")
        if not 1 <= size <= 16:
            raise ValueError("Invalid block size (must be 1-16)")
        if model not in [QR_MODEL_1, QR_MODEL_2, QR_MICRO]:
            raise ValueError(
                "Invalid QR model (must be one of QR_MODEL_1, QR_MODEL_2, QR_MICRO)"
            )
        if content == "":
            # Handle edge case by printing nothing.
            return
        if not native:
            # Map ESC/POS error correction levels to python 'qrcode' library constant and render to an image
            if model != QR_MODEL_2:
                raise ValueError(
                    "Invalid QR model for qrlib rendering (must be QR_MODEL_2)"
                )
            python_qr_ec = {
                QR_ECLEVEL_H: qrcode.constants.ERROR_CORRECT_H,
                QR_ECLEVEL_L: qrcode.constants.ERROR_CORRECT_L,
                QR_ECLEVEL_M: qrcode.constants.ERROR_CORRECT_M,
                QR_ECLEVEL_Q: qrcode.constants.ERROR_CORRECT_Q
            }
            qr_code = qrcode.QRCode(version=None,
                                    box_size=size,
                                    border=1,
                                    error_correction=python_qr_ec[ec])
            qr_code.add_data(content)
            qr_code.make(fit=True)
            qr_img = qr_code.make_image()
            im = qr_img._img.convert("RGB")

            # Convert the RGB image in printable image
            self.text('\n')
            self.image(im, center=center, impl=impl)
            self.text('\n')
            self.text('\n')
            return

        if center:
            raise NotImplementedError(
                "Centering not implemented for native QR rendering")

        # Native 2D code printing
        cn = b'1'  # Code type for QR code
        # Select model: 1, 2 or micro.
        self._send_2d_code_data(six.int2byte(65), cn,
                                six.int2byte(48 + model) + six.int2byte(0))
        # Set dot size.
        self._send_2d_code_data(six.int2byte(67), cn, six.int2byte(size))
        # Set error correction level: L, M, Q, or H
        self._send_2d_code_data(six.int2byte(69), cn, six.int2byte(48 + ec))
        # Send content & print
        self._send_2d_code_data(six.int2byte(80), cn, content.encode('utf-8'),
                                b'0')
        self._send_2d_code_data(six.int2byte(81), cn, b'', b'0')