Example #1
0
 def test_no_arguments(self):
     try:
         generate_pdf('www.')
     except IOError:
         pass
     else:
         raise AssertionError('Should have raised a IOError')
Example #2
0
 def test_no_arguments(self):
     try:
         generate_pdf('www.')
     except IOError:
         pass
     else:
         raise AssertionError('Should have raised a IOError')
Example #3
0
 def test_no_arguments(self):
     try:
         generate_pdf()
     except TypeError:
         pass
     else:
         raise AssertionError('Should have raised a TypeError')
Example #4
0
 def test_no_arguments(self):
     try:
         generate_pdf()
     except TypeError:
         pass
     else:
         raise AssertionError('Should have raised a TypeError')
Example #5
0
def generateSalesPdf(data):
    template = env.get_template(SALES_REPORT_TEMPLATE)
    template_vars = data
    html_output = template.render(template_vars)
    pdf = pydf.generate_pdf(html_output)
    with open('static/pdf/salesreport.pdf', 'wb') as f:
        f.write(pdf)
Example #6
0
 def get_csa(self):
     Panelist = apps.get_model('api.panelist')
     Member = apps.get_model('api.member')
     Song = apps.get_model('api.song')
     panelists = Panelist.objects.filter(
         kind=Panelist.KIND.official,
         round__session=self.session,
         category__gt=Panelist.CATEGORY.ca,
     ).distinct().order_by(
         'category',
         'person__last_name',
     )
     appearances = self.appearances.order_by('-num', ).prefetch_related(
         'songs', )
     songs = Song.objects.select_related('chart', ).filter(
         appearance__competitor=self, ).prefetch_related(
             'scores',
             'scores__panelist__person',
         ).order_by(
             '-appearance__round__num',
             'num',
         )
     context = {
         'competitor': self,
         'panelists': panelists,
         'appearances': appearances,
         'songs': songs,
     }
     rendered = render_to_string('csa.html', context)
     file = pydf.generate_pdf(rendered)
     content = ContentFile(file)
     return content
    def save(self):
        date = 'Дата'
        lot_number = self.qle_lot_number.text()
        description = 'PSA Calibration Curve SQ201'
        organization = self.qle_organization.text()
        position = self.qle_position.text()
        full_name = self.qle_fullName.text()
        phone = self.qle_phone.text()
        measurementResult = self.lbl_result.text()
        test_type = self.combo_test_type.currentText()

        html = '<h1>Отчет</h1>'
        html += '<p>Дата: {}</p>'.format(date)
        html += '<p>Номер партии теста: {}</p>'.format(lot_number)
        html += '<p>Тип теста: {}</p>'.format(test_type)
        html += '<p>Описание: {}</p>'.format(description)
        html += '<h1>Результаты измерения</h1>'
        html += '<p>{}<p/>'.format(measurementResult)
        html += '<h1>Организация и оператор</h1>'
        html += '<p>Организация: {}</p>'.format(organization)
        html += '<p>Оператор: {}, {}</p>'.format(full_name, position)
        html += '<p>Телефон: {}</p>'.format(phone)
        html += '<h1>Данные калибровки</h1>'
        html += '<p>Серия: {}, срок годности: {}</p>'.format('F12181', 'Дата')
        html += '<p>Файл: {}, надежность: {}</p>'.format('Файл', '92.6%')
        html += '<p>Оператор: {}, {}</p>'.format('ФИО', 'должность')
        html += '<p>Телефон: {}</p>'.format('9999999999')
        pdf = pydf.generate_pdf(html, encoding='utf-8')
        os.chdir('process')
        with open('protocol_result.pdf', 'wb') as f:
            f.write(pdf)
        os.chdir('../')

        self.win_mesurement.deleteLater()
Example #8
0
 def get_variance(self):
     Score = apps.get_model('api.score')
     Panelist = apps.get_model('api.panelist')
     songs = self.songs.order_by('num')
     scores = Score.objects.filter(
         kind=Score.KIND.official,
         song__in=songs,
     ).order_by(
         'category',
         'panelist__person__last_name',
         'song__num',
     )
     panelists = self.round.panelists.filter(
         kind=Panelist.KIND.official,
         category__gt=Panelist.CATEGORY.ca,
     ).order_by(
         'category',
         'person__last_name',
     )
     variances = []
     for song in songs:
         variances.extend(song.dixons)
         variances.extend(song.asterisks)
     variances = list(set(variances))
     context = {
         'appearance': self,
         'songs': songs,
         'scores': scores,
         'panelists': panelists,
         'variances': variances,
     }
     rendered = render_to_string('variance.html', context)
     pdf = pydf.generate_pdf(rendered, enable_smart_shrinking=False)
     content = ContentFile(pdf)
     return content
Example #9
0
    def get(self, request, *args, **kwargs):

        pk = self.kwargs.get("pk")
        invoice = Invoice.objects.get(id=pk)

        context = {
            "order": invoice.order,
            "orderlines":
            invoice.order.orderline_set.all().order_by("product"),
            "invoice": invoice,
            "buyer": invoice.buyer,
            "send_email": False,
            "bank": settings.BANK,
            "branch": settings.BRANCH,
            "branch_code": settings.BRANCH_CODE,
            "swift_code": settings.SWIFT_CODE,
            "account_number": settings.ACCOUNT_NUMBER,
            "account_name": "TURFD",
            "account_type": settings.ACCOUNT_TYPE,
            "email_address": settings.EMAIL_HOST_USER,
            "phone_number": settings.PHONE_NUMBER,
        }
        template = get_template("sales/invoice_email.html")
        html = template.render(
            context)  # Renders the template with the context data.
        pdf = pydf.generate_pdf(
            html,
            page_size="A4",
            margin_left="15mm",
            margin_right="15mm",
            margin_top="15mm",
            margin_bottom="15mm",
            orientation="Landscape",
        )
        return HttpResponse(pdf, content_type="application/pdf")
Example #10
0
def generateDepletedReport(data):
    template = env.get_template(DEPLETED_REPORT_TEMPLATE)
    template_vars = data
    html_output = template.render(template_vars)
    pdf = pydf.generate_pdf(html_output)
    with open('static/pdf/depletedreport.pdf', 'wb') as f:
        f.write(pdf)
Example #11
0
 def test_custom_size(self):
     pdf_content = generate_pdf(
         '<html><body>testing</body></html>',
         page_height='50mm',
         page_width='50mm',
     )
     assert pdf_content[:4] == byteify('%PDF')
Example #12
0
def reporte_pdf(request, id, fecha):

    template = get_template('pdf.html')

    # obtener el reporte que se quiere ver
    r = Reporte.objects.get(id=id)
    context = r.__dict__

    # obtener clientes y chofer de la entrega
    context['clientes'] = r.clientes.all()
    context['chofer'] = r.chofer.nombre

    # renderear la template con el contexto
    html = template.render(context)

    # usar pdfkit si se corre localmente,
    # pydf si esta en produccion (Heroku)
    if settings.DEBUG:
        pdf = pdfkit.from_string(html, False)
    else:
        pdf = pydf.generate_pdf(html)

    # nombre y datos del archivo y la respuesta http
    filename = 'Reporte {id} - {fecha}'.format(id=id, fecha=r.fecha_str)
    response = HttpResponse(pdf, content_type='application/pdf')
    response['Content-Disposition'] = 'filename="{name}.pdf"'.format(
        name=filename)

    return response
Example #13
0
def test_pdf_title():
    pdf_content = generate_pdf('<html><head><title>the title</title></head><body>hello</body></html>')
    assert pdf_content[:4] == b'%PDF'
    text = pdf_text(pdf_content)
    title = 'the title'.encode('utf-16be')
    assert b'\n/Title (\xfe\xff%s)\n' % title in pdf_content
    assert 'hello\n\n\x0c' == text
Example #14
0
    def get_page(self, url):
        response = Response()
        try:

            # Initilized the chrome driver
            print("Initilized the chrome driver")
            chrome_options = webdriver.ChromeOptions()
            chrome_options.add_argument('--no-sandbox')
            chrome_options.add_argument('--window-size=1420,1080')
            chrome_options.add_argument('--headless')
            chrome_options.add_argument('--disable-gpu')
            browser = webdriver.Chrome(chrome_options=chrome_options)

            # browser kibana
            print("browser kibana")
            browser.get(url)
            delay = 10000

            # wait till specific classes appears
            print("wait till specific classes appears")
            WebDriverWait(browser, delay).until(
                EC.presence_of_element_located((By.CLASS_NAME, 'kbn-table')))
            body = browser.find_element_by_class_name(
                "kbn-table").get_attribute('innerHTML')

            # calculate number of pages exists and loop them
            print("calculate number of pages exists and loop them")
            pages = (str(
                browser.find_element_by_class_name(
                    "kuiToolBarText").text).split(" ")[2]).replace(",", "")
            pages = math.ceil(int(pages) / 50) - 1

            print("pages found {}".format(pages))
            for page in range(1, pages):
                browser.execute_script(
                    "document.getElementsByClassName('kuiButton')[1].click()")
                chunk = browser.find_element_by_class_name(
                    "kbn-table").get_attribute('innerHTML').replace(
                        "<tbody>", "")
                body += chunk

            # apply table tags and generate pdf
            print("apply table tags and generate pdf")
            pdf = pydf.generate_pdf("<table>" + body + "</table>")
            with open('out.pdf', 'wb') as f:
                f.write(pdf)

            return json.loads(
                json.dumps((response.get_response(Constants.SUCCESS,
                                                  Constants.SUCCESS))))
        except Exception as e:
            logging.exception(e)

            return abort(
                make_response(
                    jsonify(
                        response.get_response(Constants.SERVER_ERROR,
                                              Constants.SERVER_ERROR)),
                    response.get_code(Constants.SERVER_ERROR)))
Example #15
0
def test_pdf_title():
    pdf_content = generate_pdf(
        '<html><head><title>the title</title></head><body>hello</body></html>')
    assert pdf_content[:4] == b'%PDF'
    text = pdf_text(pdf_content)
    title = 'the title'.encode('utf-16be')
    assert b'\n/Title (\xfe\xff%s)\n' % title in pdf_content
    assert 'hello\n\n\x0c' == text
Example #16
0
def safe_pdf(html, **kwargs):
    """
    Creates a base 64 encoded string representing a pdf which can safely
    be jsonified.
    """
    # Isn't there a more efficient way of doing this, which doesn't increase the
    # string length as much?
    pdf = generate_pdf(html, **kwargs)
    return base64.b64encode(pdf)
Example #17
0
    def handle_commands(self, msg):
        command = msg.split(' ')[0]
        remainder = msg[len(command) + 1:]

        if command == '/sheets':
            self.send_user_list_of_their_sheets()
        elif command == '/open':
            # if sheet exists then open it up and write each new message as a new element
            try:
                if self.session.current_sheet_id != None:
                    self.sender.sendMessage("Closed sheet.")
                self.session.current_sheet_id = self.sheets[remainder]
                self.sender.sendMessage(
                    "Opened sheet '{}' for writing.".format(remainder))
            except:
                self.session.current_sheet_id = self.ph.new_sheet(
                    remainder, self.remote_user_id)
                self.sheets[remainder] = self.session.current_sheet_id
                self.sender.sendMessage(
                    "Created a sheet called '{}' and opened it for writing.".
                    format(remainder))
        elif command == '/close':
            # close current sheet
            self.session.current_sheet_id = None
        elif command == '/delete':
            # delete a sheet
            raise NotImplemented
        elif command == '/show':
            if remainder in self.sheets.keys():
                this_sheet_id = self.sheets[remainder]
            elif len(remainder) == 0:
                this_sheet_id = self.session.current_sheet_id
            else:
                self.sender.sendMessage("No sheet with that name")

            elements = self.ph.get_data_in_sheet(this_sheet_id)

            tl = Timeline("", elements)
            output_filename = str(int(random.random() * 10**6)) + ".pdf"

            pdf = pydf.generate_pdf(tl._getHTML())
            with open(output_filename, 'wb') as f:
                f.write(pdf)

            with open(output_filename, 'rb') as f:
                self.sender.sendDocument(f)

        else:
            # write the message to the currently opened sheet.
            if self.session.current_sheet_id != None:
                self.ph.new_element(command + " " + remainder,
                                    self.session.current_sheet_id)
            else:
                self.sender.sendMessage(
                    "No currently open sheet! Open a sheet for writing with the /open command"
                )
Example #18
0
def generate_jacket():
    rendered = render_template('example_pdf.html', items=request.args)
    try:
        pdf = pydf.generate_pdf(rendered)
        response = make_response(pdf)
        response.headers['Content-Type'] = 'application/pdf'
        response.headers['Content-Disposition'] = 'inline; filename=output.pdf'
        return response
    except:
        return rendered
Example #19
0
def genera_pdf(rutarchivo, resultados):
    """
    genera pdf apoyandose en template chameleon.
    usa lista de dicts q le pasa 'lee_csv'
    """
    pagina_0 = chameleon.PageTemplateFile(template)
    pagina = pagina_0.render(resultados=resultados)
    # print(pagina) #------------------------------------------
    pdf = pydf.generate_pdf(pagina, orientation='Landscape', page_size='A3')
    with open(rutarchivo, 'wb') as f:
        f.write(pdf)
Example #20
0
    def generate_pdf(self, content):
        try:
            name = str(uuid.uuid4()) + ".pdf"
            #pdfkit.from_string(content, name)  # To be used if nothing works
            pdf = pydf.generate_pdf(content)
            with open(name, 'wb') as f:
                f.write(pdf)

            return os.path.abspath(name)
        except Exception as e:
            print(e)
Example #21
0
def pdf():
    try:
        from pydf import generate_pdf
        html = '<h1>This is HTML</h1>'
        pdf_content = generate_pdf(html)
        response = make_response(pdf_content)
        response.headers['Content-Type'] = 'application/pdf'
        response.headers['Content-Disposition'] = 'inline; filename=test.pdf'
        return response
    except Exception:
        exc = traceback.format_exc()
        return Response(exc, content_type='text/plain')
Example #22
0
def pdf():
    try:
        from pydf import generate_pdf
        html = '<h1>This is HTML</h1>'
        pdf_content = generate_pdf(html)
        response = make_response(pdf_content)
        response.headers['Content-Type'] = 'application/pdf'
        response.headers['Content-Disposition'] = 'inline; filename=test.pdf'
        return response
    except Exception:
        exc = traceback.format_exc()
        return Response(exc, content_type='text/plain')
Example #23
0
    def get_variance(self):
        Score = apps.get_model('api.score')
        Panelist = apps.get_model('api.panelist')

        # Songs Block
        songs = self.songs.annotate(
            tot_score=Avg(
                'scores__points',
                filter=Q(
                    scores__panelist__kind=Panelist.KIND.official,
                ),
            ),
        ).order_by('num')
        scores = Score.objects.filter(
            panelist__kind=Panelist.KIND.official,
            song__appearance=self,
        ).order_by(
            'category',
            'panelist__person__last_name',
            'song__num',
        )
        panelists = self.round.panelists.filter(
            kind=Panelist.KIND.official,
            category__gt=Panelist.CATEGORY.ca,
        ).order_by(
            'category',
            'person__last_name',
        )
        variances = []
        for song in songs:
            variances.extend(song.dixons)
            variances.extend(song.asterisks)
        variances = list(set(variances))
        tot_points = scores.aggregate(sum=Sum('points'))['sum']
        context = {
            'appearance': self,
            'songs': songs,
            'scores': scores,
            'panelists': panelists,
            'variances': variances,
            'tot_points': tot_points,
        }
        rendered = render_to_string('reports/variance.html', context)
        pdf = pydf.generate_pdf(
            rendered,
            enable_smart_shrinking=False,
            orientation='Portrait',
            margin_top='5mm',
            margin_bottom='5mm',
        )
        content = ContentFile(pdf)
        return content
Example #24
0
def create_pdf(request):
    order_id = request.GET.get('id')
    order = Order.objects.get(pk=order_id)
    order_html = order.generate_html()
    pdf = pydf.generate_pdf(order_html, encoding='utf-8')
    output_filename = os.path.join(BASE_DIR, 'pdf/checkout.pdf')
    with open(output_filename, 'wb') as f:
        f.write(pdf)
    with open(output_filename, 'rb') as pdf_file:
        response = HttpResponse(pdf_file.read())
        response['Content-Type'] = 'mimetype/submimetype'
        response['Content-Disposition'] = 'attachment; filename=regulation.pdf'
    return response
Example #25
0
def go_sync():
    count = 10
    for i in range(count):
        pdf = generate_pdf(
            html,
            page_size='A4',
            zoom='1.25',
            margin_left='8mm',
            margin_right='8mm',
        )
        print(f'{i:03}: {len(pdf)}')
        file = OUT_DIR / f'output_{i:03}.pdf'
        file.write_bytes(pdf)
    return count
Example #26
0
def go_sync():
    count = 10
    for i in range(count):
        pdf = generate_pdf(
            html,
            page_size='A4',
            zoom='1.25',
            margin_left='8mm',
            margin_right='8mm',
        )
        print(f'{i:03}: {len(pdf)}')
        file = OUT_DIR / f'output_{i:03}.pdf'
        file.write_bytes(pdf)
    return count
def createPdf(url, size='15'):
    filePath = 'files/' + url + '.txt'
    try:
        file = open(filePath, 'r')
        pasteData = file.read()
        file.close()
        pdfFilePath = 'files/' + url + '.pdf'
        pdf = pydf.generate_pdf('<p style="font-size:' + size + 'px">' +
                                pasteData + '</p>')
        with open(pdfFilePath, 'wb') as f:
            f.write(pdf)
            f.close()
        return True
    except Exception as e:
        print(e)
        return False
Example #28
0
 def sadraft(self, request, pk=None):
     session = Session.objects.get(pk=pk)
     panelists = Panelist.objects.filter(
         kind__in=[
             Panelist.KIND.official,
             Panelist.KIND.practice,
         ],
         scores__song__appearance__round__session=session,
     ).select_related('person', ).distinct().order_by(
         'category',
         'person__last_name',
     )
     competitors = session.competitors.filter(
         status=Competitor.STATUS.finished, ).select_related(
             'group', ).prefetch_related(
                 'appearances',
                 'appearances__songs',
                 'appearances__songs__scores',
                 'appearances__songs__scores__panelist',
                 'appearances__songs__scores__panelist__person',
             ).order_by(
                 '-tot_points',
                 '-sng_points',
                 '-per_points',
                 'group__name',
             )
     context = {
         'session': session,
         'panelists': panelists,
         'competitors': competitors,
     }
     rendered = render_to_string('sa.html', context)
     file = pydf.generate_pdf(
         rendered,
         page_size='Letter',
         orientation='Landscape',
     )
     content = ContentFile(file)
     pdf = content
     file_name = '{0}-sa'.format(
         slugify("{0} {1} Session".format(
             session.convention.name,
             session.get_kind_display(),
         )))
     return PDFResponse(pdf, file_name=file_name, status=status.HTTP_200_OK)
Example #29
0
def index():
    if request.method == "GET":
        return render_template("index.html")
    elif request.method == "POST":
        data = get_apod(request.form["date"])
        if "code" in data:
            return "404<br>your requested apod not found in NASA", 404
        html = render_template("result.html",
                               title=data["title"],
                               date=data["date"],
                               image_url=data["url"],
                               explanation=data["explanation"])
        html_footer = "</body></html>"
        pdf = pydf.generate_pdf(html + html_footer)
        with open("static/" + data["date"] + '.pdf', 'wb') as f:
            f.write(pdf)
        return html + "<center><button  onclick=\"window.open('/pdf/" + data[
            "date"] + ".pdf')\">Download as PDF</button></center>" + html_footer
Example #30
0
 def test_extra_arguments(self):
     pdf_content = generate_pdf(
         '<html><body>testing</body></html>',
         quiet=False,
         grayscale=True,
         lowquality=True,
         margin_bottom='20mm',
         margin_left='20mm',
         margin_right='20mm',
         margin_top='20mm',
         orientation='Landscape',
         page_height=None,
         page_width=None,
         page_size='Letter',
         image_dpi='300',
         image_quality='70',
     )
     assert pdf_content[:4] == byteify('%PDF')
Example #31
0
def render_application(request):
    if request.method == "POST":
        form = ApplicationForm(request.POST)
        if form.is_valid():
            model_instance = form.save(commit=False)
            model_instance.timestamp = timezone.now()
            model_instance.save()
            context = model_to_dict(model_instance, fields=[field.name for field in model_instance._meta.fields])
            now = datetime.datetime.now()
            context["reason"] = context["reason"].lower()
            context["year"] = now.year
            context["day"] = now.day
            context["month"] = months[now.month]
            html_string = render_to_string('stud_application.html', context)
            pdf = pydf.generate_pdf(html_string)

            return HttpResponse(pdf, content_type='application/pdf')
    else:
        form = ApplicationForm()
    return render(request, 'home.html', {'form': form})
Example #32
0
 def announcements(self, request, pk=None):
     round = Round.objects.get(pk=pk)
     appearances = round.appearances.filter(draw__gt=0, ).select_related(
         'competitor__group', ).order_by('draw', )
     mt = round.appearances.filter(draw=0, ).select_related(
         'competitor__group', ).order_by('competitor__group__name', )
     contests = round.session.contests.filter(
         num__isnull=False,
         group__isnull=False,
     ).order_by('num')
     if round.kind == round.KIND.finals:
         competitors = round.session.competitors.filter(
             status__in=[
                 Competitor.STATUS.finished,
                 Competitor.STATUS.started,
             ],
             tot_rank__lte=5,
         ).select_related('group', ).order_by('-tot_rank', )
     else:
         competitors = None
     pos = round.appearances.aggregate(sum=Sum('pos'))['sum']
     context = {
         'round': round,
         'appearances': appearances,
         'mt': mt,
         'contests': contests,
         'competitors': competitors,
         'pos': pos,
     }
     rendered = render_to_string('announcements.html', context)
     file = pydf.generate_pdf(rendered)
     content = ContentFile(file)
     pdf = content
     file_name = '{0}-announcements'.format(
         slugify("{0} {1} {2} Announcements".format(
             round.session.convention.name,
             round.session.get_kind_display(),
             round.get_kind_display(),
         )))
     return PDFResponse(pdf, file_name=file_name, status=status.HTTP_200_OK)
Example #33
0
def handout_pdf(request, assignment_id):
    assignment = get_object_or_404(Assignment, pk=assignment_id)
    recipient = assignment.recipient
    team = assignment.team
    context = {
        'recipient': recipient,
        'team': team,
    }
    rendered = render_to_string('app/pdfs/handout.html', context)
    pdf = pydf.generate_pdf(
        rendered,
        enable_smart_shrinking=False,
        orientation='Portrait',
        margin_top='10mm',
        margin_bottom='10mm',
    )
    content = ContentFile(pdf)
    return FileResponse(
        content,
        as_attachment=True,
        filename='rake_up_eagle_handout.pdf',
    )
Example #34
0
    def create_file(self, filetype, **kwargs):
        """Create markdown, HTML and PDF files.
        
        Note that PDF requires a HTML input.
        """
        if kwargs:
            fragment = kwargs["fragment"]
            dirpath = kwargs["dirpath"]
            filename = kwargs["filename"]

        generic_filename = "{dirpath}/{filetype}/{filename}".format(
            dirpath=dirpath, filetype=filetype, filename=filename)
        filepath = generic_filename + "." + filetype

        image_file = "{dirpath}/images/{filename}.png".format(
            dirpath=dirpath, filename=filename)
        qr_image_file = self.make_qr_code(fragment)
        qr_image_file.save(image_file)

        d = {
            'label': self.label,
            'timestamp': datetime.datetime.now().strftime("%d-%b-%Y %H:%M:%S"),
            'report': self.report,
            'contact_name': self.config['contact']['name'],
            'contact_email': self.config['contact']['email'],
            'fragment': fragment,
            'img_src': image_file
        }
        template_type = "md" if filetype == "md" else "html"
        filein = open("text/fragment." + template_type)
        src = Template(filein.read())
        filein.close()
        content = src.substitute(d)
        if filetype == "pdf":
            pdf = pydf.generate_pdf(content, image_quality=100, image_dpi=1000)
            with open(filepath, 'wb') as f:
                f.write(pdf)
        else:
            self.write_file(filepath, content)
Example #35
0
    def get_sung(self):
        Song = apps.get_model('api.song')
        appearances = self.appearances.filter(draw__gt=0, ).order_by('draw', )
        for appearance in appearances:
            songs = Song.objects.filter(
                appearance__competitor=appearance.competitor,
            ).distinct().order_by(
                'appearance__round__num',
                'num',
            )
            sungs = []
            for song in songs:
                try:
                    title = song.chart.nomen
                except AttributeError:
                    title = "Unknown (Not in Repertory)"
                row = "{0} Song {1}: {2}".format(
                    song.appearance.round.get_kind_display(),
                    song.num,
                    title,
                )
                sungs.append(row)
            appearance.sungs = sungs

        context = {
            'appearances': appearances,
            'round': self,
        }
        rendered = render_to_string('sung.html', context)
        file = pydf.generate_pdf(
            rendered,
            page_size='Letter',
            orientation='Portrait',
            margin_top='5mm',
            margin_bottom='5mm',
        )
        content = ContentFile(file)
        return content
Example #36
0
def handout_pdfs(request):
    assignments = Assignment.objects.order_by('team__name', )
    output = ''
    for assignment in assignments:
        context = {
            'recipient': assignment.recipient,
            'team': assignment.team,
        }
        rendered = render_to_string('app/pdfs/handout.html', context)
        output += '<div class="new-page"></div>' + rendered
    pdf = pydf.generate_pdf(
        output,
        enable_smart_shrinking=False,
        orientation='Portrait',
        margin_top='10mm',
        margin_bottom='10mm',
    )
    content = ContentFile(pdf)
    return FileResponse(
        content,
        as_attachment=True,
        filename='handouts.pdf',
    )
Example #37
0
    def get_csa(self):
        Panelist = apps.get_model('api.panelist')
        Song = apps.get_model('api.song')
        Score = apps.get_model('api.score')

        # Appearancers Block
        group = self.group
        stats = Score.objects.select_related(
            'song__appearance__group',
            'song__appearance__round__session',
            'song__appearance__round',
            'panelist',
        ).filter(
            song__appearance__group=self.group,
            song__appearance__round__session=self.round.session,
            panelist__kind=Panelist.KIND.official,
        ).aggregate(
            max=Max(
                'song__appearance__round__num',
            ),
            tot_points=Sum(
                'points',
            ),
            mus_points=Sum(
                'points',
                filter=Q(
                    panelist__category=Panelist.CATEGORY.music,
                )
            ),
            per_points=Sum(
                'points',
                filter=Q(
                    panelist__category=Panelist.CATEGORY.performance,
                )
            ),
            sng_points=Sum(
                'points',
                filter=Q(
                    panelist__category=Panelist.CATEGORY.singing,
                )
            ),
            tot_score=Avg(
                'points',
            ),
            mus_score=Avg(
                'points',
                filter=Q(
                    panelist__category=Panelist.CATEGORY.music,
                )
            ),
            per_score=Avg(
                'points',
                filter=Q(
                    panelist__category=Panelist.CATEGORY.performance,
                )
            ),
            sng_score=Avg(
                'points',
                filter=Q(
                    panelist__category=Panelist.CATEGORY.singing,
                )
            ),
        )
        appearances = Appearance.objects.select_related(
            'group',
            'round',
            'round__session',
        ).prefetch_related(
            'songs__scores',
            'songs__scores__panelist',
        ).filter(
            group=self.group,
            round__session=self.round.session,
        ).annotate(
            tot_points=Sum(
                'songs__scores__points',
                filter=Q(
                    songs__scores__panelist__kind=Panelist.KIND.official,
                ),
            ),
            mus_points=Sum(
                'songs__scores__points',
                filter=Q(
                    songs__scores__panelist__kind=Panelist.KIND.official,
                    songs__scores__panelist__category=Panelist.CATEGORY.music,
                ),
            ),
            per_points=Sum(
                'songs__scores__points',
                filter=Q(
                    songs__scores__panelist__kind=Panelist.KIND.official,
                    songs__scores__panelist__category=Panelist.CATEGORY.performance,
                ),
            ),
            sng_points=Sum(
                'songs__scores__points',
                filter=Q(
                    songs__scores__panelist__kind=Panelist.KIND.official,
                    songs__scores__panelist__category=Panelist.CATEGORY.singing,
                ),
            ),
            tot_score=Avg(
                'songs__scores__points',
                filter=Q(
                    songs__scores__panelist__kind=Panelist.KIND.official,
                ),
            ),
            mus_score=Avg(
                'songs__scores__points',
                filter=Q(
                    songs__scores__panelist__kind=Panelist.KIND.official,
                    songs__scores__panelist__category=Panelist.CATEGORY.music,
                ),
            ),
            per_score=Avg(
                'songs__scores__points',
                filter=Q(
                    songs__scores__panelist__kind=Panelist.KIND.official,
                    songs__scores__panelist__category=Panelist.CATEGORY.performance,
                ),
            ),
            sng_score=Avg(
                'songs__scores__points',
                filter=Q(
                    songs__scores__panelist__kind=Panelist.KIND.official,
                    songs__scores__panelist__category=Panelist.CATEGORY.singing,
                ),
            ),
        )

        # Monkeypatch
        for key, value in stats.items():
            setattr(group, key, value)
        for appearance in appearances:
            songs = appearance.songs.prefetch_related(
                'scores',
                'scores__panelist',
            ).order_by(
                'num',
            ).annotate(
                tot_score=Avg(
                    'scores__points',
                    filter=Q(
                        scores__panelist__kind=Panelist.KIND.official,
                    ),
                ),
                mus_score=Avg(
                    'scores__points',
                    filter=Q(
                        scores__panelist__kind=Panelist.KIND.official,
                        scores__panelist__category=Panelist.CATEGORY.music,
                    ),
                ),
                per_score=Avg(
                    'scores__points',
                    filter=Q(
                        scores__panelist__kind=Panelist.KIND.official,
                        scores__panelist__category=Panelist.CATEGORY.performance,
                    ),
                ),
                sng_score=Avg(
                    'scores__points',
                    filter=Q(
                        scores__panelist__kind=Panelist.KIND.official,
                        scores__panelist__category=Panelist.CATEGORY.singing,
                    ),
                ),
                tot_points=Sum(
                    'scores__points',
                    filter=Q(
                        scores__panelist__kind=Panelist.KIND.official,
                    ),
                ),
                mus_points=Sum(
                    'scores__points',
                    filter=Q(
                        scores__panelist__kind=Panelist.KIND.official,
                        scores__panelist__category=Panelist.CATEGORY.music,
                    ),
                ),
                per_points=Sum(
                    'scores__points',
                    filter=Q(
                        scores__panelist__kind=Panelist.KIND.official,
                        scores__panelist__category=Panelist.CATEGORY.performance,
                    ),
                ),
                sng_points=Sum(
                    'scores__points',
                    filter=Q(
                        scores__panelist__kind=Panelist.KIND.official,
                        scores__panelist__category=Panelist.CATEGORY.singing,
                    ),
                ),
            )
            for song in songs:
                penalties_map = {
                    10: "†",
                    30: "‡",
                    40: "✠",
                    50: "✶",
                }
                items = " ".join([penalties_map[x] for x in song.penalties])
                song.penalties_patched = items
            appearance.songs_patched = songs
        group.appearances_patched = appearances

        # Panelists
        panelists = Panelist.objects.select_related(
            'person',
        ).filter(
            kind=Panelist.KIND.official,
            round__session=self.round.session,
            round__num=1,
            category__gt=10,
        ).order_by('num')

        # Score Block
        initials = [x.person.initials for x in panelists]

        # Hackalicious
        category_count = {
            'Music': 0,
            'Performance': 0,
            'Singing': 0,
        }
        for panelist in panelists:
            category_count[panelist.get_category_display()] += 1
        songs = Song.objects.filter(
            appearance__round__session=self.round.session,
            appearance__group=self.group,
        ).order_by(
            'appearance__round__kind',
            'num',
        )
        for song in songs:
            scores = song.scores.filter(
                panelist__kind=Panelist.KIND.official,
            ).order_by('panelist__num')
            class_map = {
                Panelist.CATEGORY.music: 'warning',
                Panelist.CATEGORY.performance: 'success',
                Panelist.CATEGORY.singing: 'info',
            }
            items = []
            for score in scores:
                items.append((score.points, class_map[score.panelist.category]))
            song.scores_patched = items

        # Category Block
        categories = {
            'Music': [],
            'Performance': [],
            'Singing': [],
        }
        # panelists from above
        for panelist in panelists:
            item = categories[panelist.get_category_display()]
            item.append(panelist.person.common_name)

        # Penalties Block
        array = Song.objects.filter(
            appearance__round__session=self.round.session,
            appearance__group=self.group,
            penalties__len__gt=0,
        ).distinct().values_list('penalties', flat=True)
        penalties_map = {
            10: "† Score(s) penalized due to violation of Article IX.A.1 of the BHS Contest Rules.",
            30: "‡ Score(s) penalized due to violation of Article IX.A.2 of the BHS Contest Rules.",
            40: "✠ Score(s) penalized due to violation of Article IX.A.3 of the BHS Contest Rules.",
            50: "✶ Score(s) penalized due to violation of Article X.B of the BHS Contest Rules.",
        }
        penalties = sorted(list(set(penalties_map[x] for l in array for x in l)))

        context = {
            'appearance': self,
            'round': self.round,
            'group': group,
            'initials': initials,
            'songs': songs,
            'categories': categories,
            'penalties': penalties,
            'category_count': category_count,
        }
        rendered = render_to_string(
            'reports/csa.html',
            context,
        )
        statelog = self.round.statelogs.latest('timestamp')
        footer = 'Published by {0} at {1}'.format(
            statelog.by,
            statelog.timestamp.strftime("%Y-%m-%d %H:%M:%S %Z"),
        )
        file = pydf.generate_pdf(
            rendered,
            orientation='Portrait',
            margin_top='5mm',
            margin_bottom='5mm',
            footer_right=footer,
            footer_font_name='Encode Sans',
            footer_font_size=8,
        )
        content = ContentFile(file)
        return content
Example #38
0
 def test_extra_kwargs(self):
     pdf_content = generate_pdf(
         '<html><body>testing</body></html>',
         header_right='Page [page] of [toPage]'
     )
     assert pdf_content[:4] == byteify('%PDF')
Example #39
0
def test_bad_arguments():
    with pytest.raises(RuntimeError) as exc_info:
        generate_pdf('hello', foobar='broken')
    assert 'error running wkhtmltopdf, command' in str(exc_info)
Example #40
0
def test_generate_pdf_with_html():
    pdf_content = generate_pdf('<html><body>Is this thing on?</body></html>')
    assert pdf_content[:4] == b'%PDF'
    text = pdf_text(pdf_content)
    assert 'Is this thing on?\n\n\x0c' == text
Example #41
0
 def test_unicode(self):
     pdf_content = generate_pdf(u'<html><body>Schrödinger</body></html>')
     assert pdf_content[:4] == byteify('%PDF')
Example #42
0
 def test_generate_pdf_with_url(self):
     pdf_content = generate_pdf('http://google.com')
     assert pdf_content[:4] == byteify('%PDF')
Example #43
0
 def test_generate_pdf_with_html(self):
     pdf_content = generate_pdf('<html><body>Is this thing on?</body></html>')
     assert pdf_content[:4] == byteify('%PDF')
Example #44
0
    def get_psa(self):
        Score = apps.get_model('api.score')
        Group = apps.get_model('bhs.group')
        # Score block
        group_ids = self.round.appearances.exclude(
            # Don't include advancers or MTs on PSA
            draw__gt=0,
        ).values_list('group__id', flat=True)
        groups = Group.objects.filter(
            id__in=group_ids,
        ).prefetch_related(
            'appearances__songs__scores',
            'appearances__songs__scores__panelist',
            'appearances__round__session',
        ).annotate(
            tot_points=Sum(
                'appearances__songs__scores__points',
                filter=Q(
                    appearances__songs__scores__panelist__kind=Panelist.KIND.official,
                    appearances__round__session=self.round.session,
                ),
            ),
            per_points=Sum(
                'appearances__songs__scores__points',
                filter=Q(
                    appearances__songs__scores__panelist__kind=Panelist.KIND.official,
                    appearances__songs__scores__panelist__category=Panelist.CATEGORY.performance,
                    appearances__round__session=self.round.session,
                ),
            ),
            sng_points=Sum(
                'appearances__songs__scores__points',
                filter=Q(
                    appearances__songs__scores__panelist__kind=Panelist.KIND.official,
                    appearances__songs__scores__panelist__category=Panelist.CATEGORY.singing,
                    appearances__round__session=self.round.session,
                ),
            ),
        ).order_by(
            '-tot_points',
            '-sng_points',
            '-per_points',
        )
        # Monkeypatching
        class_map = {
            Panelist.CATEGORY.music: 'badge badge-warning mono-font',
            Panelist.CATEGORY.performance: 'badge badge-success mono-font',
            Panelist.CATEGORY.singing: 'badge badge-info mono-font',
        }
        for group in groups:
            appearances = group.appearances.filter(
                round__session=self.round.session,
            ).order_by('round__kind')
            for appearance in appearances:
                songs = appearance.songs.order_by(
                    'num',
                ).prefetch_related(
                    'scores',
                    'scores__panelist',
                ).annotate(
                    avg=Avg(
                        'scores__points',
                        filter=Q(
                            scores__panelist__kind=Panelist.KIND.official,
                        ),
                    ),
                    dev=StdDev(
                        'scores__points',
                        filter=Q(
                            scores__panelist__kind=Panelist.KIND.official,
                        ),
                    ),
                    Music=Avg(
                        'scores__points',
                        filter=Q(
                            scores__panelist__kind=Panelist.KIND.official,
                            scores__panelist__category=Panelist.CATEGORY.music,
                        ),
                    ),
                    Performance=Avg(
                        'scores__points',
                        filter=Q(
                            scores__panelist__kind=Panelist.KIND.official,
                            scores__panelist__category=Panelist.CATEGORY.performance,
                        ),
                    ),
                    Singing=Avg(
                        'scores__points',
                        filter=Q(
                            scores__panelist__kind=Panelist.KIND.official,
                            scores__panelist__category=Panelist.CATEGORY.singing,
                        ),
                    ),
                )
                for song in songs:
                    scores2 = song.scores.select_related(
                        'panelist',
                    ).filter(
                        panelist__kind=Panelist.KIND.official,
                    ).order_by('points')
                    out = []
                    for score in scores2:
                        if score.points == 0:
                            score.points = "00"
                        span_class = class_map[score.panelist.category]
                        if score.panelist.person == self.person:
                            span_class = "{0} black-font".format(span_class)
                        out.append((score.points, span_class))
                    song.scores_patched = out
                    panelist_score = song.scores.get(
                        panelist__person=self.person,
                    )
                    category = self.get_category_display()
                    diff = panelist_score.points - getattr(song, category)
                    song.diff_patched = diff
                    pp = song.scores.get(panelist__person=self.person).points
                    song.pp = pp
                appearance.songs_patched = songs
            group.appearances_patched = appearances

        context = {
            'panelist': self,
            'groups': groups,
        }
        rendered = render_to_string(
            'reports/psa.html',
            context,
        )
        statelog = self.round.statelogs.latest('timestamp')
        footer = 'Published by {0} at {1}'.format(
            statelog.by,
            statelog.timestamp.strftime("%Y-%m-%d %H:%M:%S %Z"),
        )
        file = pydf.generate_pdf(
            rendered,
            page_size='Letter',
            orientation='Portrait',
            margin_top='5mm',
            margin_bottom='5mm',
            footer_right=footer,
            footer_font_name='Encode Sans',
            footer_font_size=8,
        )
        content = ContentFile(file)
        return content