Exemplo n.º 1
0
 def generar_reporte(self):
     reporte_seguro = Reporteseguro.objects.get(id=self.id_reporte_seguro)
     print("{} {} {}".format(reporte_seguro.gestion, reporte_seguro.mes,
                             reporte_seguro.id))
     agenda_servicio = Agendaserv.objects.filter(
         fecha__year=reporte_seguro.gestion,
         fecha__month=reporte_seguro.mes,
         agenda__tipo=1,
         agenda__seguro=reporte_seguro.seguro.id,
         agenda__deleted=False)
     print(len(agenda_servicio))
     response = HttpResponse(content_type='application/pdf')
     pdf_name = "informe_{}-{}-{}.pdf".format(
         reporte_seguro.seguro.nombre, reporte_seguro.gestion,
         reporte_seguro.mes)  # llamado clientes
     response['Content-Disposition'] = 'inline; filename=%s' % pdf_name
     buffer = BytesIO()
     doc = BaseDocTemplate(buffer, pagesize=letter)
     frame0 = Frame(doc.leftMargin,
                    doc.bottomMargin,
                    doc.width,
                    doc.height,
                    showBoundary=0,
                    id='normalBorde')
     doc.addPageTemplates([
         PageTemplate(id='principal',
                      frames=frame0,
                      onPage=self.__encabezado),
     ])
     estilo = getSampleStyleSheet()
     estilo.add(
         ParagraphStyle(name="Titulo",
                        alignment=TA_CENTER,
                        fontSize=10,
                        fontName="Helvetica-Bold"))
     estilo.add(
         ParagraphStyle(name="Titulod",
                        alignment=TA_RIGHT,
                        fontSize=10,
                        fontName="Helvetica-Bold"))
     estilo.add(
         ParagraphStyle(name="Parrafo",
                        alignment=TA_JUSTIFY,
                        fontSize=8,
                        fontName="Helvetica"))
     estilo.add(
         ParagraphStyle(name="Parrafod",
                        alignment=TA_RIGHT,
                        fontSize=8,
                        fontName="Helvetica"))
     estilo.add(
         ParagraphStyle(name="Parrafoc",
                        alignment=TA_CENTER,
                        fontSize=8,
                        fontName="Helvetica"))
     estilo.add(
         ParagraphStyle(name="Tituloc1",
                        alignment=TA_CENTER,
                        fontSize=14,
                        leading=22,
                        fontName="Helvetica-Bold"))
     estilo.add(
         ParagraphStyle(name="Tituloc2",
                        alignment=TA_CENTER,
                        fontSize=12,
                        leading=22,
                        fontName="Helvetica-Bold"))
     story = []
     story.append(
         Paragraph("{}".format(reporte_seguro.seguro.nombre),
                   estilo['Tituloc1']))
     story.append(
         Paragraph(
             "{}-{}".format(reporte_tag.mesliteral(reporte_seguro.mes),
                            reporte_seguro.gestion), estilo['Tituloc2']))
     self.__detalle(story, estilo, agenda_servicio)
     doc.build(story)
     pdf = buffer.getvalue()
     buffer.close()
     response.write(pdf)
     return response
Exemplo n.º 2
0
    def getStatTime(self, type):
        d = self.stats.getProgress('time')
        max = d[0]
        items = []
        h = 4 * cm  # max height

        if type == "frames":
            # header time
            items.append(
                Frame(1 * cm,
                      19.3 * cm,
                      19 * cm,
                      1 * cm,
                      leftPadding=0,
                      rightPadding=0,
                      id='normal',
                      showBoundary=0))

            for k in d:
                if k == 0:
                    continue
                items.append(
                    Frame(1.67 * cm + (k - 1) * 21,
                          14.8 * cm,
                          6, (len(d[k]["visitors"]) * h / max["max_u"]) + 16,
                          leftPadding=0,
                          rightPadding=0,
                          id='normal',
                          showBoundary=0))  # row 1
                items.append(
                    Frame(1.67 * cm + (k - 1) * 21 + 6,
                          14.8 * cm,
                          6, (len(d[k]["different"]) * h / max["max_p"]) + 16,
                          leftPadding=0,
                          rightPadding=0,
                          id='normal',
                          showBoundary=0))  # row 1
                items.append(
                    Frame(1.67 * cm + (k - 1) * 21 + 12,
                          14.8 * cm,
                          6, (len(d[k]["items"]) * h / max["max"]) + 16,
                          leftPadding=0,
                          rightPadding=0,
                          id='normal',
                          showBoundary=0))  # row 1

            items.append(
                Frame(1 * cm,
                      13.2 * cm,
                      19 * cm,
                      2 * cm,
                      leftPadding=0,
                      rightPadding=0,
                      id='normal',
                      showBoundary=0))  # legend
            # value table
            items.append(
                Frame(1 * cm,
                      1.0 * cm,
                      19 * cm,
                      12.5 * cm,
                      leftPadding=0,
                      rightPadding=0,
                      id='normal',
                      showBoundary=0))

        if type == "data":
            items.append(
                Paragraph(t(self.language, "edit_stats_spreading_time"),
                          self.chartheader))

            for k in d:
                if k == 0:
                    continue
                items.append(
                    PdfImage(config.basedir + "/web/img/stat_baruser_vert.png",
                             width=6,
                             height=len(d[k]["visitors"]) * h / max["max_u"] +
                             1))
                items.append(FrameBreak())
                items.append(
                    PdfImage(config.basedir + "/web/img/stat_barpage_vert.png",
                             width=6,
                             height=len(d[k]["different"]) * h / max["max_p"] +
                             1))
                items.append(FrameBreak())
                items.append(
                    PdfImage(config.basedir + "/web/img/stat_bar_vert.gif",
                             width=6,
                             height=len(d[k]["items"]) * h / max["max"] + 1))
                items.append(FrameBreak())

            t_data = []
            for i in range(0, 24):
                im = PdfImage(config.basedir + "/web/img/stat_hr" +
                              str(i % 12 + 1) + ".png",
                              width=14,
                              height=14)
                p = Paragraph((str(i) + "-" + str(i + 1)), self.bv)
                t_data.append([p, im])

            tb = Table([t_data], 24 * [21], [40])
            tb.setStyle(
                TableStyle([
                    ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                    ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                    ('INNERGRID', (0, 0), (-1, -1), 1, colors.black),
                    ('BOX', (0, 0), (-1, -1), 1, colors.black),
                    ('FONTNAME', (0, 0), (-1, -1), 'Helvetica'),
                    ('FONTSIZE', (0, 0), (-1, -1), 7),
                ]))
            items.append(tb)

            t_data = [['%02d:00-%02d:00' % (i, i + 1)] for i in range(0, 24)]
            for k in d:
                if k == 0:
                    continue
                t_data[k - 1] += [len(d[k][key]) for key in d[k].keys()]
            t_data = [[
                t(self.language, "edit_stats_daytime"),
                t(self.language, "edit_stats_diffusers").replace(
                    "<br/>", "\n"),
                t(self.language, "edit_stats_pages"),
                t(self.language, "edit_stats_access")
            ]] + t_data

            tb = Table(t_data, 4 * [70], [25] + [13] * 24)
            tb.setStyle(
                TableStyle([
                    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                    ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                    ('INNERGRID', (0, 0), (-1, -1), 1, colors.black),
                    ('BOX', (0, 0), (-1, -1), 1, colors.black),
                    ('FONTNAME', (0, 0), (-1, -1), 'Helvetica'),
                    ('FONTSIZE', (0, 0), (-1, -1), 7),
                    ('BACKGROUND', (1, 0), (1, 0), colors.HexColor('#fff11d')),
                    ('BACKGROUND', (2, 0), (2, 0), colors.HexColor('#2ea495')),
                    ('BACKGROUND', (3, 0), (3, 0), colors.HexColor('#84a5ef')),
                ]))
            items.append(tb)
        return items
Exemplo n.º 3
0
class TicketPDF:
    """
    Generate pdf of a Ticket.
    """
    # generate the paths for the files used.
    base_dir = os.path.dirname(os.path.abspath(__file__))
    font_file = os.path.join(base_dir, 'assets', 'Verdana.ttf')
    font_file_bold = os.path.join(base_dir, 'assets', 'VerdanaBold.ttf')
    background_image = os.path.join(base_dir, 'assets', 'prosfora.jpg')
    dh_logo = os.path.join(base_dir, 'assets', 'dhlogo.jpg')
    # default font
    font = 'Verdana'
    base_color = Color(0, 0.6, 0.8, 1)
    # paragraph styles
    styles = getSampleStyleSheet()
    styleN = styles['Normal']
    styleH = styles['Heading1']
    styleH2 = styles['Heading3']
    styleB = styles['BodyText']
    # change the font of the styles
    styleH.fontName = font
    styleH2.fontName = font
    styleN.fontName = font
    styleB.fontName = font
    # change the heading1 style
    styleH.borderWidth = 1
    styleH.borderColor = Color(0, 0.6, 0.8, 1)
    styleH.fontSize = 14
    styleH.alignment = 1
    # story lists for the frames
    story = []
    # create the frames
    htwelve = PAGE_HEIGHT / 12
    info_frame_left = Frame(0, htwelve * 9, PAGE_WIDTH/2, (PAGE_HEIGHT / 12) * 1.4, leftPadding=30)
    info_frame_right = Frame(PAGE_WIDTH / 2, htwelve * 9, PAGE_WIDTH / 2, htwelve * 1.4, leftPadding=30)
    left_frame = Frame(0, htwelve * 6, PAGE_WIDTH / 2, htwelve * 3, leftPadding=30)
    right_frame = Frame(PAGE_WIDTH / 2, htwelve * 6, PAGE_WIDTH / 2, htwelve * 3, leftPadding=30)
    actions_frame = Frame(0, htwelve * 4, PAGE_WIDTH, htwelve * 2, leftPadding=30)
    parts_frame = Frame(0, 0, PAGE_WIDTH, htwelve * 4, leftPadding=30)

    def __init__(self, ticket):
        # Generate the response object and set the contant type
        self.response = HttpResponse(content_type='application/pdf')
        # Change the disposition of the pdf file
        self.response['Content-Disposition'] = 'inline; filename="ticket.pdf"'
        # register the font to the pdf class
        pdfmetrics.registerFont(TTFont('Verdana', self.font_file))
        pdfmetrics.registerFont(TTFont('VerdanaBold', self.font_file_bold))
        # get the ticket passed to the class.
        self.ticket = ticket

    def print_client_info(self):
        """
        Prints the client info to the pdf
        """
        self.story.append(
            Paragraph('Πληροφορίες Πελάτη', self.styleH)
        )
        self.story.append(
            Paragraph('<font color=(0,0.6,0.8)>Πελάτης: </font>{0}'.format(self.ticket.client.full_name()), self.styleN)
        )
        self.story.append(
            Paragraph('<font color=(0,0.6,0.8)>Σταθερό: </font>{0}'.format(self.ticket.client.landline()), self.styleN)
        )
        self.story.append(
            Paragraph('<font color=(0,0.6,0.8)>Κινητό: </font>{0}'.format(self.ticket.client.mobile_phone()), self.styleN)
        )
        self.story.append(
            Paragraph('<font color=(0,0.6,0.8)>Service ID: </font>{0}'.format(self.ticket.id), self.styleN)
        )
        self.story.append(FrameBreak())

    def print_device_info(self):
        """
        Prints the device info to the pdf
        """
        self.story.append(
            Paragraph('Πληροφορίες Συσκευής', self.styleH)
        )
        self.story.append(
            Paragraph('<font color=(0,0.6,0.8)>Ημερομηνία Εισαγωγής: </font>{0}'.format(self.ticket.admission_date.strftime("%d-%m-%Y")), self.styleN)
        )
        self.story.append(
            Paragraph('<font color=(0,0.6,0.8)>Ημερομηνία Εξαγωγής: </font>{0}'.format(self.ticket.discharge_full_date()), self.styleN)
        )
        self.story.append(
            Paragraph('<font color=(0,0.6,0.8)>Συσκευή: </font>{0}'.format(self.ticket.device.model), self.styleN)
        )
        self.story.append(
            Paragraph('<font color=(0,0.6,0.8)>S/N: </font>{0}'.format(self.ticket.device.serial_number), self.styleN)
        )
        self.story.append(FrameBreak())

    def print_problem(self):
        """
        Print the problem of the ticket
        """
        self.story.append(
            Paragraph('Περιγραφή Προβήματος', self.styleH)
        )
        self.story.append(
            Paragraph(self.ticket.problem, self.styleB)
        )
        self.story.append(FrameBreak())

    def print_diagnosis(self):
        """
        Print the diagnosis of the ticket
        """
        self.story.append(
            Paragraph('Διάγνωση Προβλήματος', self.styleH)
        )
        self.story.append(
            Paragraph(self.ticket.diagnosis, self.styleB)
        )
        self.story.append(FrameBreak())

    def print_actions(self):
        """
        Print the actions of the ticket
        """
        self.story.append(
            Paragraph('Ενέργειες Τεχνικού', self.styleH)
        )
        self.story.append(
            Paragraph(self.ticket.actions, self.styleB)
        )
        self.story.append(FrameBreak())

    def print_parts(self):
        """
        Prints the table of the used parts.
        """
        self.story.append(
            Paragraph('Ανταλλακτικά', self.styleH)
        )
        heading = [['Ανταλλακτικό', 'Serial Number', 'Τιμή']]
        parts = [[x.part.part, x.serial_number, "{0} €".format(x.charge)] for x in self.ticket.charges.all()]
        prices = [
            ['', 'Σύνολο Ανταλλακτικών', "{0} €".format(self.ticket.parts_cost())],
            ['', 'Σύνολο Εργασίας', "{0} €".format(self.ticket.work_charge)],
            ['', 'Τελικό Σύνολο', "{0} €".format(self.ticket.total_cost())]
        ]
        data = heading + parts + prices
        # set the table style
        tstyle = TableStyle([
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
            ('FONT', (0, 0), (-1, -1), self.font),
            ('TEXTCOLOR', (0, 0), (2, 0), self.base_color),
            ('FONT', (0, 0), (2, 0), 'VerdanaBold'),
            ('FONTSIZE', (0, 0), (2, 0), 12),
            ('LINEABOVE', (0, 1), (2, 1), 1, self.base_color),
            ('TEXTCOLOR', (-2, -3), (-2, -2), self.base_color),
            ('TEXTCOLOR', (-2, -1), (-1, -1), self.base_color),
            ('FONT', (-2, -1), (-1, -1), 'VerdanaBold'),
            ('FONTSIZE', (-2, -3), (-1, -2), 12),
            ('FONTSIZE', (-2, -1), (-1, -1), 14),
        ])
        table = Table(data, colWidths=[((PAGE_WIDTH / 12) * 10) / 3] * 3)
        table.setStyle(tstyle)
        self.story.append(table)

    @staticmethod
    def build_page(canvas, doc):
        canvas.saveState()
        canvas.drawImage(TicketPDF.background_image, 0, 0)
        canvas.drawImage(TicketPDF.dh_logo, 50, 750, 200, 80, True, 'c')
        canvas.setFont(TicketPDF.font, 18)
        canvas.drawString(350, 780, "Παραστατικό Service")
        # print the dividing line
        # TicketPDF.draw_line(730)
        canvas.setFont(TicketPDF.font, 16)
        canvas.restoreState()

    def render(self):
        """
        Render the file and return the HttpResponse with the file.
        :return: HttpResponse
        """
        doc = BaseDocTemplate(
            self.response,
            title="{0} - ServiceID {1}".format(self.ticket.client.full_name(), self.ticket.id),
            author='Digital Horizon'
        )
        doc.addPageTemplates([
            PageTemplate(
                frames=[
                    self.info_frame_left,
                    self.info_frame_right,
                    self.left_frame,
                    self.right_frame,
                    self.actions_frame,
                    self.parts_frame
                ], onPage=TicketPDF.build_page
            )
        ])
        self.print_client_info()
        self.print_device_info()
        self.print_problem()
        self.print_diagnosis()
        self.print_actions()
        self.print_parts()
        doc.build(self.story)
        return self.response
Exemplo n.º 4
0
    def getStatTop(self, type, namecut=0):
        # frames
        items = []
        d = self.stats.getIDs()
        max = float(d[0][1])
        if max == 0:
            max += 1
        if type == "frames":
            items.append(
                Frame(1 * cm,
                      24.0 * cm,
                      19 * cm,
                      1 * cm,
                      leftPadding=0,
                      rightPadding=0,
                      id='normal',
                      showBoundary=0))  # header
            for i in range(0, 45):
                if i < len(d):
                    items.append(
                        Frame(1 * cm, (22.9 - (i * 0.5)) * cm,
                              8 * cm,
                              25,
                              leftPadding=0,
                              rightPadding=0,
                              id='normal',
                              showBoundary=0))  # label
                    items.append(
                        Frame(9 * cm, (23.0 - (i * 0.5)) * cm,
                              d[i][1] * 280 / max,
                              25,
                              leftPadding=0,
                              rightPadding=0,
                              id='normal',
                              showBoundary=0))  # bar
                    items.append(
                        Frame(9 * cm + (d[i][1] * 280 / max) + 5,
                              (22.9 - (i * 0.5)) * cm,
                              40,
                              25,
                              leftPadding=0,
                              rightPadding=0,
                              id='normal',
                              showBoundary=0))  # number

        # data
        if type == "data":
            items.append(
                Paragraph(t(self.language, "edit_stats_access"),
                          self.chartheader))
            items.append((FrameBreak()))

            for i in range(0, 45):
                if i < len(d):
                    try:
                        nodename = tree.getNode(d[i][0]).getName()
                        suffix = " (" + str(d[i][0]) + ")"
                        n = nodename + suffix
                        if namecut > 0 and len(n) > namecut:
                            delta = len(n) - namecut
                            new_length = len(nodename) - delta - 3
                            n = nodename[0:new_length] + "..." + suffix
                    except:
                        n = str(d[i][0])
                    items.append(Paragraph(n, self.bv))
                    items.append((FrameBreak()))
                    items.append(
                        PdfImage(config.basedir + "/web/img/stat_bar.png",
                                 width=d[i][1] * 280 / max,
                                 height=10))
                    items.append((FrameBreak()))
                    items.append(Paragraph(str(d[i][1]), self.bv))
                    items.append((FrameBreak()))
        return items
Exemplo n.º 5
0
    def getStatDate(self, type):
        items = []
        d = self.stats.getProgress()
        max = d[0]

        if type == "frames":
            # header date
            items.append(
                Frame(1 * cm,
                      26.0 * cm,
                      19 * cm,
                      1 * cm,
                      leftPadding=0,
                      rightPadding=0,
                      id='normal',
                      showBoundary=0))
            x = (32 -
                 len(d)) * 8  # add left space if month with less than 31 days

            for k in d:
                if k == 0:
                    continue
                items.append(
                    Frame(1 * cm + (k - 1) * 17 + 9 + x,
                          18.9 * cm,
                          5,
                          len(d[k]["visitors"]) * (6 * cm) / max["max_u"] + 16,
                          leftPadding=0,
                          rightPadding=0,
                          id='normal',
                          showBoundary=0))  # col 1
                items.append(
                    Frame(1 * cm + (k - 1) * 17 + 14 + x,
                          18.9 * cm,
                          5,
                          len(d[k]["different"]) * (6 * cm) / max["max_p"] +
                          16,
                          leftPadding=0,
                          rightPadding=0,
                          id='normal',
                          showBoundary=0))  # col 2
                items.append(
                    Frame(1 * cm + (k - 1) * 17 + 19 + x,
                          18.9 * cm,
                          5,
                          len(d[k]["items"]) * (6 * cm) / max["max"] + 16,
                          leftPadding=0,
                          rightPadding=0,
                          id='normal',
                          showBoundary=0))  # col 3

            # legend table with days
            items.append(
                Frame(1 * cm,
                      17.8 * cm,
                      19 * cm,
                      1.5 * cm,
                      leftPadding=4,
                      rightPadding=0,
                      id='normal',
                      showBoundary=0))
            # table with values
            items.append(
                Frame(1 * cm,
                      1 * cm,
                      19 * cm,
                      16 * cm,
                      leftPadding=4,
                      rightPadding=0,
                      id='normal',
                      showBoundary=0))

        if type == "data":
            items.append(
                Paragraph(t(self.language, "edit_stats_spreading"),
                          self.chartheader))
            items.append(FrameBreak())

            for k in d:
                if k == 0:
                    continue
                items.append(
                    PdfImage(config.basedir + "/web/img/stat_baruser_vert.png",
                             width=5,
                             height=((len(d[k]["visitors"]) *
                                      (6 * cm) / max["max_u"] + 1) or 1)))
                items.append(FrameBreak())
                items.append(
                    PdfImage(config.basedir + "/web/img/stat_barpage_vert.png",
                             width=5,
                             height=((len(d[k]["different"]) *
                                      (6 * cm) / max["max_p"] + 1) or 1)))
                items.append(FrameBreak())
                items.append(
                    PdfImage(config.basedir + "/web/img/stat_bar_vert.gif",
                             width=5,
                             height=((len(d[k]["items"]) *
                                      (6 * cm) / max["max"] + 1) or 1)))
                items.append(FrameBreak())

            t_data = []
            weekend = []
            for k in d:
                if k > 0:  # first item holds max values
                    if self.stats.getWeekDay(k) > 4:
                        weekend.append(('BACKGROUND', (k - 1, 0), (k - 1, -1),
                                        colors.HexColor('#E6E6E6')))
                    t_data.append('%02d \n%s' %
                                  (k,
                                   t(
                                       self.language, "monthname_" +
                                       str(int(self.period[-2:])) + "_short")))

            tb = Table([t_data], 31 * [17], 30)
            tb.setStyle(
                TableStyle([
                    ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                    ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                    ('INNERGRID', (0, 0), (-1, -1), 1, colors.black),
                    ('BOX', (0, 0), (-1, -1), 1, colors.black),
                    ('FONTNAME', (0, 0), (-1, -1), 'Helvetica'),
                    ('FONTSIZE', (0, 0), (-1, -1), 7),
                ] + weekend))
            items.append(tb)
            items.append(FrameBreak())

            t_data = [[
                t(self.language, "edit_stats_day"),
                t(self.language,
                  "edit_stats_diffusers").replace("<br/>", "\n"),
                t(self.language, "edit_stats_pages"),
                t(self.language, "edit_stats_access")
            ]]  # +31*[4*[2]]
            weekend = []
            for k in d:
                if k > 0:  # first item holds max values
                    if self.stats.getWeekDay(k) > 4:
                        weekend.append(('BACKGROUND', (0, k), (-1, k),
                                        colors.HexColor('#E6E6E6')))
                    t_data.append([
                        '%02d.%s %s' % (k,
                                        t(
                                            self.language, "monthname_" +
                                            str(int(self.period[-2:])) +
                                            "_short"), self.period[:4]),
                        len(d[k]["visitors"]),
                        len(d[k]["different"]),
                        len(d[k]["items"])
                    ])

            tb = Table(t_data, 4 * [100], [25] + (len(d) - 1) * [12])
            tb.setStyle(
                TableStyle([
                    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                    ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                    ('INNERGRID', (0, 0), (-1, -1), 1, colors.black),
                    ('BOX', (0, 0), (-1, -1), 1, colors.black),
                    ('FONTNAME', (0, 0), (-1, -1), 'Helvetica'),
                    ('FONTSIZE', (0, 0), (-1, -1), 7),
                    ('BACKGROUND', (1, 0), (1, 0), colors.HexColor('#fff11d')),
                    ('BACKGROUND', (2, 0), (2, 0), colors.HexColor('#2ea495')),
                    ('BACKGROUND', (3, 0), (3, 0), colors.HexColor('#84a5ef')),
                ] + weekend))
            items.append(tb)
        return items
Exemplo n.º 6
0
def minutesToPdfTest(request, id_minutes):
    saveViewsLog(request, "pdfmodule.views.minutesToPdfTest")
    if request.user.is_staff:
        pdf_address = "/pdf/reporte%s.pdf" % (int(random.random() * 100000))
    # try:
        # _actions= rel_user_action.objects.all().order_by("-date_done")

        from reportlab.pdfgen import canvas
        canvas_obj = canvas.Canvas("%s%s" % (MEDIA_ROOT, pdf_address))
        # c.drawString(50,700,"700 Primera prueba de reportlab con django")
        # c.showPage()
        # c.save()
        estiloHoja = getSampleStyleSheet()
        estilo1 = estiloHoja['BodyText']
        estilo2 = estiloHoja['Normal']

        # Inicializamos story.

        story = []
        story2 = []

        # Añadimos algunos flowables.

        parrafo1 = Paragraph('Id de Acta: %s' % (id_minutes), estilo1)
        parrafo2 = Paragraph('España, Murcia, Lorca', estilo2)

        # Agregamos una tabla
        list_data = [["Esto", "Es", "Una", "Tabla"],
                    ["Esto", "Es", "Una", "Tabla"],
                    ["Esto", "Es", "Una", "Tabla"],
                    ["Esto", "Es", "Una", "Tabla"], ]
        t = Table(list_data)

        # agregamos una imagen
        img = Image("static/img/dragon.jpg", width=100, height=100)
        # img = Image("static/img/org.png",width=4,height=3)

        # Añadimos los flowables a la lista story.

        story.append(parrafo1)
        story.append(parrafo2)
        story.append(t)
        story.append(Spacer(0, 20))
        story2.append(img)

        # Creamos documento.

        # documento = SimpleDocTemplate("%s%s"%(MEDIA_ROOT,pdf_address),
        # pagesize = A4)

        # Y construimos el documento.

        # documento.build(story)

        # creo los frames
        f1 = Frame(350, 350, 200, 200, showBoundary=1)
        f2 = Frame(50, 50, 200, 200, showBoundary=1)

        # agregando los frames al objeto canvas
        f1.addFromList(story, canvas_obj)
        canvas_obj.showPage()

        f2.addFromList(story2, canvas_obj)

        canvas_obj.save()
    # except:
        # print "Ocurrio un error al generar el PDF"
        # ctx = {"actions":
        # rel_user_action.objects.all().order_by("-date_done")}
        return HttpResponseRedirect('/media%s' % (pdf_address))
    else:
        return HttpResponseRedirect('/')
Exemplo n.º 7
0
capacity = ''
title = f'Design Manual for {capacity}kg .pdf'
cover_image = static('images/coverimage.jpg')


def foot1(canvas, doc):
    canvas.saveState()
    canvas.setFont('Times-Roman', 19)
    canvas.drawString(dx(6), py(6), "Oti Onyedikachi")
    canvas.restoreState()


v = ParagraphStyle(name='Heading1', alignment=4)

template1 = PageTemplate('cover',
                         [Frame(px(5), py(5), px(95), py(95), id='F1')],
                         onPage=foot1)
b = BaseDocTemplate('pop.pdf')
b.addPageTemplates(template1)
n = getSampleStyleSheet()

s = [
    Paragraph(title, n['Normal']),
    Image(cover_image, px(75), py(75)),
    Paragraph('dgdfgdfgdfgdfgrd', style=v)
]

b.build(s)
# leftMargin=dx(22), rightMargin=dx(22), topMargin=py(30), bottomMargin=py(30),
# main_canvas = canvas.Canvas(title, pagesize=A4, pageCompression=1)
#
Exemplo n.º 8
0
def facturaGenerator(request, factura):
    D = decimal.Decimal
    cantida_cuentas = len(tableList)
    #BUILD RESPONSE
    #fecha_emision = timezone.now().date()
    #response = HttpResponse( content_type='application/pdf' )
    #filename = 'datosbancarios%s%s' %( request.user.condominio.nombre, fecha_emision )
    #response[ 'Content-Disposition' ] = 'attachment; filename="%s.pdf"' %( filename )
    #BUFFER
    buff = BytesIO()
    doc = BaseDocTemplate(buff,
                          pagesize=letter,
                          topMargin=0.5 * inch,
                          bottomMargin=0.5 * inch,
                          rightMargin=0.5 * inch,
                          leftMargin=0.5 * inch)
    relacion_data_frame = Frame(doc.leftMargin,
                                doc.bottomMargin,
                                doc.width,
                                doc.height - (1 * inch),
                                id='relacion_data',
                                showBoundary=1)
    doc.addPageTemplates([
        PageTemplate(frames=[
            relacion_data_frame,
        ],
                     onPage=partial(static_elements,
                                    request=request,
                                    cantida_cuentas=cantida_cuentas)),
    ])
    #doc =  BaseDocTemplate(buff,pagesize=letter,pageTemplates=[],showBoundary=0,leftMargin=0.5*inch,rightMargin=0.5*inch,topMargin=0.5*inch,bottomMargin=0.5*inch,allowSplitting=0,title=None,author=None,_pageBreakQuick=1,encrypt=None)

    #STYLER
    #styles = getSampleStyleSheet()
    story = []

    #TABLE HEADER
    styles = getSampleStyleSheet()
    headerStyle = styles['h6']
    headerStyle.alignment = TA_CENTER
    #NEED DYNAMIC HEADERS
    #print tableList
    # relacion_list_header = []
    bank_list = []
    # all_keys = list(set().union(*(d.keys() for d in tableList)))
    # for column in all_keys:
    # 	relacion_list_header.append(Paragraph(str(column), headerStyle))
    # relacion_list.append(relacion_list_header)
    banco = Paragraph('''Banco''', headerStyle)
    nro_cuenta = Paragraph('''Numero de Cuenta''', headerStyle)
    info_adicional = Paragraph('''Informacion Adicional''', headerStyle)
    # pagos = Paragraph('''Abonos''', headerStyle)
    # porcentaje = Paragraph('''Alicuota''', headerStyle)
    # cuota = Paragraph('''Cuota''', headerStyle)
    # total = Paragraph('''Total''', headerStyle)
    header_list = [banco, nro_cuenta, info_adicional]
    # for key,value in tableList[0].iteritems():
    # 	if not key in ['inmueble', 'abonos', 'alicuota', 'porcentaje', 'total', 'deuda_previa', 'residente']:
    # 		print key
    # 		relacion_list.insert(4,value)

    #APPEND FIRST ROW
    bank_list.append(header_list)
    #print header_list

    #APPEND data
    styles = getSampleStyleSheet()
    dataStyle = styles['Normal']
    dataStyle.alignment = TA_CENTER
    dataStyle.fontSize = 6
    for row in tableList:
        banco = Paragraph(str(row['banco']), dataStyle)
        nro_cuenta = Paragraph(str(row['numero_de_cuenta']), dataStyle)
        info_adicional = Paragraph(str(row['informacion_adicional']),
                                   dataStyle)
        row_data = [banco, nro_cuenta, info_adicional]
        bank_list.append(row_data)

    table = Table(bank_list,
                  colWidths=None,
                  rowHeights=None,
                  style=None,
                  splitByRow=1,
                  repeatRows=1,
                  repeatCols=0,
                  rowSplitRange=None,
                  spaceBefore=None,
                  spaceAfter=None)

    LIST_STYLE = TableStyle([
        ('LINEBELOW', (0, 1), (-1, -1), 0.3, colors.black),
        #('BACKGROUND', ( 0, 1 ), ( -1,  1 ),colors.Color(red=(244.0/255),green=(243.0/255),blue=(242.0/255))),
        #('BACKGROUND', ( 0, -1 ), ( -1,  -1 ),colors.Color(red=(244.0/255),green=(243.0/255),blue=(242.0/255))),
        # ('LINEBELOW', ( 0,  0), ( -1, -20 ), 1, colors.black),
        #('LINEBELOW', ( 0,  0), ( -1, -20 ), 0.3, colors.black),
        ('BACKGROUND', (0, 0), (-1, 0), colors.gold),
        # ('ALIGN', (0,0), (-2,-1), 'LEFT'),
        # ('ALIGN', (1,0), (-1,-1), 'RIGHT')
    ])
    table.setStyle(LIST_STYLE)
    story.append(table)
    #story.append(FrameBreak())

    #a= Table([[1, 2, 3],[4, 'foo', 6],[7, 8, 'bar'],])
    # logo_path = '/tucondominioaldia/usuario/pdfs/pdflogo.png'
    # logo = Image(logo_path, width= 3.5 *inch, height= 0.6 *inch)
    # story.append(logo)
    # #table = Table(total_a_pagar, colWidths=[1.875*inch,1.875*inch], rowHeights=None, style=None, splitByRow=1,repeatRows=0, repeatCols=0, rowSplitRange=None, spaceBefore=None,spaceAfter=None)
    #story.append(a)
    doc.build(story)
    #response.write(buff.getvalue())
    #buff.close()
    return buff
Exemplo n.º 9
0
    def create(self):
        styles = getSampleStyleSheet()

        aW, aH = letter

        nrm = styles['Normal']
        hd1 = styles['Heading1']
        hd2 = styles['Heading2']

        styles.add(
            ParagraphStyle(name='Right',
                           fontSize=12,
                           spaceAfter=15,
                           alignment=TA_RIGHT))
        styles.add(
            ParagraphStyle(name='Left',
                           fontSize=12,
                           spaceAfter=15,
                           borderColor='black',
                           borderRadius=3,
                           borderPadding=5,
                           borderWidth=1,
                           alignment=TA_LEFT))

        basepg = Canvas(self.pdf_file)

        # Form title
        ttl = []
        ttl.append(Paragraph('Nonconformance Report', hd1))
        ttl.append(LineDrw(500))
        frm = Frame(15 * mm,
                    260 * mm,
                    width=150 * mm,
                    height=25 * mm,
                    showBoundary=0)
        frm.addFromList(ttl, basepg)

        # First text area box
        dscrp = []
        dscrp.append(Paragraph('Project Description', hd2))
        dscrp.append(Paragraph(self.ta['ta_1'], nrm))
        frm1 = Frame(15 * mm,
                     240 * mm,
                     width=180 * mm,
                     height=25 * mm,
                     showBoundary=1)
        frm1.addFromList(dscrp, basepg)

        # Section of labels for input text
        info = []
        info.append(
            Paragraph('<b><i>Job Number:</i></b>', style=styles['Right']))
        info.append(
            Paragraph('<b><i>Requestor:</i></b>', style=styles['Right']))
        info.append(
            Paragraph('<b><i>Contact Information:</i></b>',
                      style=styles['Right']))
        info.append(
            Paragraph('<b><i>Fabricator:</i></b>', style=styles['Right']))
        info.append(
            Paragraph('<b><i>Date Of Issue:</i></b>', style=styles['Right']))
        info.append(
            Paragraph('<b><i>Pipe Specification Code:</i></b>',
                      style=styles['Right']))
        info.append(
            Paragraph('<b><i>P&ID Line Number:</i></b>',
                      style=styles['Right']))
        frmLft = Frame(15 * mm,
                       150 * mm,
                       width=65 * mm,
                       height=85 * mm,
                       showBoundary=0)
        frmLft.addFromList(info, basepg)

        # list of first section of input text boxes
        inpt = []
        for n in range(1, 8):
            indx = 't_' + str(n)
            inpt.append(Paragraph(self.t[indx], style=styles['Left']))
        frmRgt = Frame(80 * mm,
                       150 * mm,
                       width=65 * mm,
                       height=85 * mm,
                       showBoundary=0)
        frmRgt.addFromList(inpt, basepg)

        # second textarea box
        dscrp = []
        dscrp.append(Paragraph('Related Drawings or Documentation:', hd2))
        dscrp.append(Paragraph(self.ta['ta_2'], nrm))
        frm1 = Frame(15 * mm,
                     120 * mm,
                     width=180 * mm,
                     height=45 * mm,
                     showBoundary=1)
        frm1.addFromList(dscrp, basepg)

        # third textarea box
        dscrp = []
        dscrp.append(Paragraph('Nonconformance Description:', hd2))
        dscrp.append(Paragraph(self.ta['ta_3'], nrm))
        frm1 = Frame(15 * mm,
                     70 * mm,
                     width=180 * mm,
                     height=45 * mm,
                     showBoundary=1)
        frm1.addFromList(dscrp, basepg)

        # fourth textarea box
        dscrp = []
        dscrp.append(Paragraph('Proposed Repair', hd2))
        dscrp.append(Paragraph(self.ta['ta_4'], nrm))
        frm1 = Frame(15 * mm,
                     30 * mm,
                     width=180 * mm,
                     height=35 * mm,
                     showBoundary=1)
        frm1.addFromList(dscrp, basepg)

        basepg.showPage()

        # check box labels
        info = []
        info.append(
            Paragraph('<b><i>Has QC Manager been notified?</i></b>',
                      style=styles['Right']))
        info.append(
            Paragraph('<b><i>Has Operations been notified?</i></b>',
                      style=styles['Right']))
        frmLft1 = Frame(15 * mm,
                        200 * mm,
                        width=65 * mm,
                        height=65 * mm,
                        showBoundary=0)
        frmLft1.addFromList(info, basepg)

        # check box checked values
        inpt = []
        txt = 'No'
        if 'chk_1' in self.chk:
            txt = 'Yes'
        inpt.append(Paragraph(txt, style=styles['Left']))
        inpt.append(Spacer(1, 13))
        txt = 'No'
        if 'chk_2' in self.chk:
            txt = 'Yes'
        inpt.append(Paragraph(txt, style=styles['Left']))
        frmLft2 = Frame(80 * mm,
                        197 * mm,
                        width=15 * mm,
                        height=65 * mm,
                        showBoundary=0)
        frmLft2.addFromList(inpt, basepg)

        # fifth textarea box
        dscrp = []
        dscrp.append(Paragraph('Final Repair or Disposition:', hd2))
        dscrp.append(Paragraph('(indicate schedule for repair)', nrm))
        dscrp.append(Paragraph(self.ta['ta_5'], nrm))
        frm1 = Frame(15 * mm,
                     190 * mm,
                     width=180 * mm,
                     height=45 * mm,
                     showBoundary=1)
        frm1.addFromList(dscrp, basepg)

        # text box labels
        info = []
        info.append(
            Paragraph('<b><i>QC Manager Approval</i></b>',
                      style=styles['Right']))
        info.append(Spacer(1, 13))
        info.append(
            Paragraph('<b><i>Operations Approval</i></b>',
                      style=styles['Right']))
        info.append(Spacer(1, 13))
        info.append(
            Paragraph('<b><i>Requestor Approval</i></b>',
                      style=styles['Right']))
        frmLft1 = Frame(10 * mm,
                        100 * mm,
                        width=65 * mm,
                        height=65 * mm,
                        showBoundary=0)
        frmLft1.addFromList(info, basepg)

        # input text data
        inpt = []
        for n in range(8, 11):
            indx = 't_' + str(n)
            inpt.append(Paragraph(self.t[indx], style=styles['Left']))
            inpt.append(Spacer(1, 13))
        frmLft2 = Frame(80 * mm,
                        100 * mm,
                        width=65 * mm,
                        height=65 * mm,
                        showBoundary=0)
        frmLft2.addFromList(inpt, basepg)

        # text box labels
        info = []
        for n in range(3):
            info.append(Paragraph('<b><i>Date</i></b>', style=styles['Right']))
            info.append(Spacer(1, 13))
        frmRgt1 = Frame(95 * mm,
                        100 * mm,
                        width=65 * mm,
                        height=65 * mm,
                        showBoundary=0)
        frmRgt1.addFromList(info, basepg)

        # text box input data
        inpt = []
        for n in range(11, 14):
            indx = 't_' + str(n)
            inpt.append(Paragraph(self.t[indx], style=styles['Left']))
            inpt.append(Spacer(1, 13))
        frmRgt2 = Frame(160 * mm,
                        100 * mm,
                        width=35 * mm,
                        height=65 * mm,
                        showBoundary=0)
        frmRgt2.addFromList(inpt, basepg)

        basepg.save()
Exemplo n.º 10
0
def ORIGINAL_print_pdf(request, tag_id):
    from reportlab.pdfgen.canvas import Canvas
    from reportlab.lib.styles import getSampleStyleSheet
    from reportlab.lib.units import inch
    from reportlab.platypus import Paragraph, Frame, Image
       
    styles = getSampleStyleSheet()
    styleN = styles['Normal']
    styleH = styles['Heading1']
    
    tag = get_object_or_404(Tag, pk=tag_id)
  
    fname = "mylabels.pdf"
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=%s' %(fname)
    
    c  = Canvas(response)
    width =  8.5*inch/2; height = 11*inch/4.0
    for j in range(0,2):
        for i in range(0,4):
            x1 = j*8.5*inch/2.0; y1 = i*(11)*inch/4.0
            
            slogan = []
            slogan.append(Paragraph(tag.slogan1,styleN))
            slogan.append(Paragraph(tag.slogan2,styleN))
            
            contact =[]
            contact.append(Paragraph(tag.contact1,styleN))
            contact.append(Paragraph(tag.contact2,styleN))
            contact.append(Paragraph(tag.contact3,styleN))
            
            url=[Paragraph(tag.url,styleN)]
                                   
            qrcode=[]
            if tag.qrcode:
                qrcode.append(Image(tag.qrcode.path, 0.3*height, 0.3*height))           
            
            logo=[]
            if tag.logo:
                logo.append(Image(tag.logo.path, 0.4*height, 0.4*height))
            
            # Define frames and sizes here.
            logo_frame = Frame(x1,  y1+.5*height, .5*width, .5*height, showBoundary=0 )
            slogan_frame = Frame(x1,y1+.1*height, .5*width, .4*height, showBoundary=0)
            
            contact_frame = Frame(x1+.5*width, y1+.6*height, .5*width, .4*height, showBoundary=0)
            qrcode_frame = Frame(x1+.5*width,y1+.1*height, .5*width, .5*height, showBoundary=0)
            url_frame =  Frame(x1,y1, .5*width, .2*height, showBoundary=0) 
                                    
            contact_frame.addFromList(contact,c)
            slogan_frame.addFromList(slogan,c)
            qrcode_frame.addFromList(qrcode, c)
            url_frame.addFromList(url,c)
            logo_frame.addFromList(logo, c)
            
    c.save()    
           
    return response

    tv = {'tag_id':tag_id}
    return render_to_response("labels/print.html",tv)
    def make_page_templates(self, fdict=None, flist=None, use_default=True):
        """Makes template with frames if fdict not given goes with default 6 frames"""

        frames = []
        default_fdict = dict(
            fstat=dict(x1=self.doc.leftMargin,
                       y1=self.doc.bottomMargin + self.default_fheight +
                       self.dpads,
                       width=self.default_fwidth,
                       height=self.default_fheight,
                       id="fstat",
                       showBoundary=self.show_bound,
                       leftPadding=11 * mm,
                       topPadding=7 * mm),
            ctbar=dict(
                x1=self.doc.leftMargin + self.default_fwidth + self.dpads,
                y1=self.doc.bottomMargin + self.default_fheight + self.dpads,
                width=self.default_fwidth,
                height=self.default_fheight,
                id="ctbar",
                showBoundary=self.show_bound,
                leftPadding=0 * mm,
                topPadding=3 * mm,
                rightPadding=0 * mm,
                bottomPadding=0 * mm),
            jfbar=dict(
                x1=(self.doc.leftMargin + self.default_fwidth + self.dpads) *
                2,
                y1=self.doc.bottomMargin + self.default_fheight + self.dpads,
                width=self.default_fwidth,
                height=self.default_fheight,
                id="jfbar",
                showBoundary=self.show_bound,
                leftPadding=0 * mm,
                topPadding=3 * mm,
                rightPadding=0 * mm,
                bottomPadding=0 * mm),
            usr17=dict(x1=self.doc.leftMargin,
                       y1=self.doc.bottomMargin,
                       width=self.default_fwidth,
                       height=self.default_fheight,
                       id="usr17",
                       showBoundary=self.show_bound,
                       leftPadding=0 * mm,
                       topPadding=0 * mm,
                       rightPadding=0 * mm,
                       bottomPadding=0 * mm),
            usr18=dict(x1=self.doc.leftMargin + self.default_fwidth +
                       self.dpads,
                       y1=self.doc.bottomMargin,
                       width=self.default_fwidth,
                       height=self.default_fheight,
                       id="usr18",
                       showBoundary=self.show_bound,
                       leftPadding=0 * mm,
                       topPadding=0 * mm,
                       rightPadding=0 * mm,
                       bottomPadding=0 * mm),
            usr19=dict(
                x1=(self.doc.leftMargin + self.default_fwidth + self.dpads) *
                2,
                y1=self.doc.bottomMargin,
                width=self.default_fwidth,
                height=self.default_fheight,
                id="usr19",
                showBoundary=self.show_bound,
                leftPadding=0 * mm,
                topPadding=0 * mm,
                rightPadding=0 * mm,
                bottomPadding=0 * mm))
        if fdict == None:
            fdict = {}

        if flist == None:
            flist = ['fstat', 'ctbar', 'jfbar', 'usr17', 'usr18', 'usr19']

        for frm in flist:
            kwargs = fdict.get(
                frm, default_fdict[frm]) if use_default else fdict[frm]
            frames.append(Frame(**kwargs))

        self.doc.addPageTemplates(
            [PageTemplate(id='facility_metrics', frames=frames)])
Exemplo n.º 12
0
def fake_for_pages(body, title, httpresponse, user):
    styles = getSampleStyleSheet()
    styleNormal = styles['Normal']
    styleHeading = styles['Heading1']
    styleHeading.alignment = 1

    def head_footer(canvas, doc):
        canvas.saveState()
        P = Paragraph("BROKEN - Contact [email protected]", styleNormal)
        w, h = P.wrap(doc.width, doc.bottomMargin)
        P.drawOn(canvas, doc.leftMargin, h)
        P = Paragraph("Page BUGGED of BROKEN", styleNormal)
        w, h = P.wrap(doc.width, doc.bottomMargin)
        P.drawOn(canvas, doc.width + doc.leftMargin, h)

        P = Paragraph("BUGGED - Contact [email protected]",
                      styleHeading)
        w, h = P.wrap(doc.width + doc.leftMargin + doc.rightMargin,
                      doc.topMargin)
        P.drawOn(canvas, 0, doc.height + doc.topMargin)
        #canvas.drawCentredString((doc.width+doc.leftMargin+doc.rightMargin)/2.0, doc.height+doc.topMargin, title)
        #pdb.set_trace()
        canvas.restoreState()

    new_body = []
    for b in body:
        temp = []
        for part in b:
            try:
                if len(part) > 40:
                    t = part.split(' ')
                    a = " ".join(t[0:round(len(t) / 2)])
                    b = " ".join(t[len(t) - round(len(t) / 2):])
                    temp += ["\n".join([a, b])]
                else:
                    temp += [part]
            except:
                temp += [part]
        new_body += [temp]
    TABLE = Table(data=new_body, repeatRows=1)
    TABLE.setStyle(
        TableStyle([('FONTSIZE', (0, 0), (-1, -1), 8),
                    ('LINEBELOW', (0, 0), (-1, -1), 0.25, colors.red),
                    ('ALIGN', (0, 0), (-1, -1), "LEFT")]))
    table = []
    table.append(TABLE)
    doc = BaseDocTemplate(httpresponse,
                          topMargin=12,
                          bottomMargin=20,
                          pagesize=landscape(A4))

    frame = Frame(doc.leftMargin,
                  doc.bottomMargin,
                  doc.width,
                  doc.height,
                  id='normal')
    template = PageTemplate(id='table', frames=frame, onPage=head_footer)
    doc.addPageTemplates([template])

    doc.build(table)
    return doc.page
Exemplo n.º 13
0
def report_gen(body, title, httpresponse, user):
    styles = getSampleStyleSheet()
    styleNormal = styles['Normal']
    styleHeading = styles['Heading1']
    styleHeading.alignment = 1
    total_pages = fake_for_pages(body, title, httpresponse, user)

    def head_footer(canvas, doc):
        canvas.saveState()
        P = Paragraph(
            "Report Generated: {}    By: {} - Stock Database V{}".format(
                datetime.datetime.today().strftime("%d/%m/%Y"), user,
                __version__), styleNormal)
        w, h = P.wrap(doc.width, doc.bottomMargin)
        P.drawOn(canvas, doc.leftMargin, h)
        P = Paragraph(
            "Page {} of {}".format(canvas.getPageNumber(), total_pages),
            styleNormal)
        w, h = P.wrap(doc.width, doc.bottomMargin)
        P.drawOn(canvas, doc.width + doc.leftMargin, h)

        P = Paragraph("{}".format(title), styleHeading)
        w, h = P.wrap(doc.width + doc.leftMargin + doc.rightMargin,
                      doc.topMargin)
        P.drawOn(canvas, 0, doc.height + doc.topMargin)
        #canvas.drawCentredString((doc.width+doc.leftMargin+doc.rightMargin)/2.0, doc.height+doc.topMargin, title)
        #pdb.set_trace()
        canvas.restoreState()

    new_body = []
    for b in body:
        temp = []
        for part in b:
            try:
                if len(part) > 40:
                    t = part.split(' ')
                    a = " ".join(t[0:round(len(t) / 2)])
                    b = " ".join(t[len(t) - round(len(t) / 2):])
                    temp += ["\n".join([a, b])]
                else:
                    temp += [part]
            except:
                temp += [part]
        new_body += [temp]
    TABLE = Table(data=new_body, repeatRows=1)
    TABLE.setStyle(
        TableStyle([('FONTSIZE', (0, 0), (-1, -1), 8),
                    ('LINEBELOW', (0, 0), (-1, -1), 0.25, colors.red),
                    ('ALIGN', (0, 0), (-1, -1), "LEFT")]))
    table = []
    table.append(TABLE)
    doc = BaseDocTemplate(httpresponse,
                          topMargin=12,
                          bottomMargin=20,
                          pagesize=landscape(A4))

    frame = Frame(doc.leftMargin,
                  doc.bottomMargin,
                  doc.width,
                  doc.height,
                  id='normal')
    template = PageTemplate(id='table', frames=frame, onPage=head_footer)
    doc.addPageTemplates([template])

    doc.build(table)
    return doc
Exemplo n.º 14
0
story.append(PageBreak())  # Inicio en otra hoja
story.append(Paragraph("Esto es el texto del Frame que pertenece al" +\
                       " pagetemplate de dos columnas" * 500, estilo['Normal']))

story.append(NextPageTemplate('UnaColumna'))
story.append(PageBreak())
story.append(Paragraph("Regresamos al texto del Frame normal del" +\
                        " pagetemplate de dos columnas"*100, estilo['Normal']))

#NIVEL 3: CREAMOS LOS FRAMES, para luego asignarlos a un pagetemplate.
#===========================
#Frame (x1, y1, ancho, alto, leftPadding=6, bottomPadding=6, rightPadding=6,
# topPadding=6, id=None, showBoundary=0)

#1. Frame que contendrá a toda el contenido de una hoja
frameN = Frame(inch, inch, 451, 697, id='normal')

#2. Frame de columnas
frame1 = Frame(inch, inch, 220, 697, id='col1')
frame2 = Frame(inch + 230, inch, 220, 697, id='col2')

#NIVEL 4: CREAMOS LOS PAGETEMPLATE, le asignamos los frames y los canvas
#=================================
#PageTemplate(id=None,frames=[],onPage=_doNothing,onPageEnd=_doNothing)
PTUnaColumna = PageTemplate(id='UnaColumna', frames=frameN, onPage=pie)
PTDosColumnas = PageTemplate(id='DosColumnas',
                             frames=[frame1, frame2],
                             onPage=encabezado,
                             onPageEnd=pie)

#NIVEL 5: CREAMOS EL DOCTEMPLATE, a partir del BaseDocTemplate
Exemplo n.º 15
0
def _create_confirmation(confirmation_buffer, invoice, booking):

    global DPAW_HEADER_LOGO
    #    if  cols_var["TEMPLATE_GROUP"] == 'rottnest':
    #        DPAW_HEADER_LOGO = os.path.join(settings.BASE_DIR, 'mooring', 'static', 'mooring', 'img','logo-rottnest-island-sm.png')
    #    else:
    #        DPAW_HEADER_LOGO = os.path.join(settings.BASE_DIR, 'ledger', 'payments','static', 'payments', 'img','dbca_logo.jpg')
    DPAW_HEADER_LOGO = os.path.join(settings.BASE_DIR, 'ledger', 'payments',
                                    'static', 'payments', 'img',
                                    'dbca_logo.jpg')

    every_page_frame = Frame(PAGE_MARGIN,
                             PAGE_MARGIN + 250,
                             PAGE_WIDTH - 2 * PAGE_MARGIN,
                             PAGE_HEIGHT - 450,
                             id='EveryPagesFrame',
                             showBoundary=0)
    remit_frame = Frame(PAGE_MARGIN,
                        PAGE_MARGIN,
                        PAGE_WIDTH - 2 * PAGE_MARGIN,
                        PAGE_HEIGHT - 600,
                        id='RemitFrame',
                        showBoundary=0)
    every_page_template = PageTemplate(id='EveryPages',
                                       frames=[every_page_frame, remit_frame],
                                       onPage=_create_header)

    doc = BaseDocTemplate(confirmation_buffer,
                          pageTemplates=[every_page_template],
                          pagesize=A4)

    # this is the only way to get data into the onPage callback function
    doc.invoice = invoice
    doc.booking = booking
    owner = invoice.owner

    elements = []
    #elements.append(Spacer(1, SECTION_BUFFER_HEIGHT * 5))

    # Draw Products Table
    invoice_table_style = TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP'),
                                      ('GRID', (0, 0), (-1, -1), 1,
                                       colors.black),
                                      ('ALIGN', (0, 0), (-1, -1), 'LEFT')])
    items = invoice.order.lines.all()
    discounts = invoice.order.basket_discounts
    #if invoice.text:
    #    elements.append(Paragraph(invoice.text, styles['Left']))
    #    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT * 2))
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT * 2))

    data = [
        #['Item','Product', 'Quantity','Unit Price', 'Total']
        ['Item', 'Product', 'Quantity', 'Fees']
    ]
    val = 1
    s = styles["BodyText"]
    s.wordWrap = 'CJK'

    for item in items:
        data.append([
            val,
            Paragraph(item.description, s), item.quantity,
            invoice.payment_status.capitalize()
        ])
        val += 1
    # Discounts
    data.append(['', '', ''])
    t = Table(data,
              style=invoice_table_style,
              hAlign='LEFT',
              colWidths=(
                  0.7 * inch,
                  None,
                  0.7 * inch,
                  1.0 * inch,
              ))
    elements.append(t)
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT * 2))
    # /Products Table
    if invoice.payment_status != 'paid' and invoice.payment_status != 'over_paid':
        elements.append(
            Paragraph(settings.INVOICE_UNPAID_WARNING, styles['Left']))

    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT * 6))

    # Remitttance Frame
    #    elements.append(FrameBreak())
    #    boundary = BrokenLine(PAGE_WIDTH - 2 * (PAGE_MARGIN *1.1))
    #    elements.append(boundary)
    #    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    #
    #    remittance = Remittance(HEADER_MARGIN,HEADER_MARGIN - 10,invoice)
    #    elements.append(remittance)
    doc.build(elements)

    return confirmation_buffer
Exemplo n.º 16
0
def _create_approval(approval_buffer, approval, proposal, copied_to_permit, user):
    site_url = settings.SITE_URL
    every_page_frame = Frame(PAGE_MARGIN, PAGE_MARGIN, PAGE_WIDTH - 2 * PAGE_MARGIN,
                             PAGE_HEIGHT - 160, id='EveryPagesFrame')
    every_page_template = PageTemplate(id='EveryPages', frames=[every_page_frame], onPage=_create_approval_header)

    doc = BaseDocTemplate(approval_buffer, pageTemplates=[every_page_template], pagesize=A4)

    # this is the only way to get data into the onPage callback function
    doc.approval = approval
    doc.site_url = site_url
    region = approval.region if hasattr(approval, 'region') else ''
    district = approval.district if hasattr(approval, 'district') else ''
    region_district = '{} - {}'.format(region, district) if district else region

    approval_table_style = TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP')])

    elements = []


    title = approval.title.encode('UTF-8')

    #Organization details

    address = proposal.applicant.organisation.postal_address
    email = proposal.applicant.organisation.organisation_set.all().first().contacts.all().first().email
    elements.append(Paragraph(email,styles['BoldLeft']))
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    elements.append(Paragraph(_format_name(approval.applicant),styles['BoldLeft']))
    elements.append(Paragraph(address.line1, styles['BoldLeft']))
    elements.append(Paragraph(address.line2, styles['BoldLeft']))
    elements.append(Paragraph(address.line3, styles['BoldLeft']))
    elements.append(Paragraph('%s %s %s' % (address.locality, address.state, address.postcode), styles['BoldLeft']))
    elements.append(Paragraph(address.country.name, styles['BoldLeft']))
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    elements.append(Paragraph(approval.issue_date.strftime(DATE_FORMAT), styles['BoldLeft']))
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    #elements.append(Paragraph(title, styles['InfoTitleVeryLargeCenter']))
    #elements.append(Paragraph(approval.activity, styles['InfoTitleLargeLeft']))
    elements.append(Paragraph('APPROVAL OF PROPOSAL {} {} TO UNDERTAKE DISTURBANCE ACTIVITY IN {}'.format(title, proposal.lodgement_number, region_district), styles['InfoTitleLargeLeft']))
    #import ipdb; ipdb.set_trace()
    #elements.append(Paragraph(approval.tenure if hasattr(approval, 'tenure') else '', styles['InfoTitleLargeRight']))

    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    elements.append(Paragraph('The submitted proposal {} {} has been assessed and approved. The approval is granted on the understanding that: '.format(title, proposal.lodgement_number), styles['BoldLeft']))
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    list_of_bullets= []
    list_of_bullets.append('The potential impacts of the proposal on values the department manages have been removed or minimised to a level \'As Low As Reasonably Practicable\' (ALARP) and the proposal is consistent with departmental objectives, associated management plans and the land use category/s in the activity area.')
    list_of_bullets.append('Approval is granted for the period {} to {}.  This approval is not valid if {} makes changes to what has been proposed or the proposal has expired.  To change the proposal or seek an extension, the proponent must re-submit the proposal for assessment.'.format(approval.start_date.strftime(DATE_FORMAT), approval.expiry_date.strftime(DATE_FORMAT),_format_name(approval.applicant)))
    list_of_bullets.append('The proponent accepts responsibility for advising {} of new information or unforeseen threats that may affect the risk of the proposed activity.'.format(settings.DEP_NAME_SHORT))
    list_of_bullets.append('Information provided by {0} for the purposes of this proposal will not be provided to third parties without permission from {0}.'.format(settings.DEP_NAME_SHORT))
    list_of_bullets.append('The proponent accepts responsibility for supervising and monitoring implementation of activity/ies to ensure compliance with this proposal. {} reserves the right to request documents and records demonstrating compliance for departmental monitoring and auditing.'.format(settings.DEP_NAME_SHORT))
    list_of_bullets.append('Non-compliance with the conditions of the proposal may trigger a suspension or withdrawal of the approval for this activity.')
    list_of_bullets.append('Management actions listed in Appendix 1 are implemented.')

    understandingList = ListFlowable(
            [ListItem(Paragraph(a, styles['Left']), bulletColour='black', value='circle') for a in list_of_bullets],
            bulletFontName=BOLD_FONTNAME, bulletFontSize=SMALL_FONTSIZE, bulletType='bullet')
            #bulletFontName=BOLD_FONTNAME
    elements.append(understandingList)

    # proposal requirements
    requirements = proposal.requirements.all().exclude(is_deleted=True)
    if requirements.exists():
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        elements.append(Paragraph('The following requirements must be satisfied for the approval of the proposal not to be withdrawn:', styles['BoldLeft']))
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

        conditionList = ListFlowable(
            [Paragraph(a.requirement, styles['Left']) for a in requirements.order_by('order')],
            bulletFontName=BOLD_FONTNAME, bulletFontSize=MEDIUM_FONTSIZE)
        elements.append(conditionList)

    # if copied_to_permit:
    #     elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    #     elements.append(Paragraph('Assessor Comments', styles['BoldLeft']))
    #     elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    #     for k,v in copied_to_permit:
    #         elements.append(Paragraph(v.encode('UTF-8'), styles['Left']))
    #         elements.append(Paragraph(k.encode('UTF-8'), styles['Left']))
    #         elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    elements += _layout_extracted_fields(approval.extracted_fields)

    # additional information
    '''if approval.additional_information:
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        elements.append(Paragraph('Additional Information', styles['BoldLeft']))
        elements += _layout_paragraphs(approval.additional_information)'''

    # delegation holds the dates, approvale and issuer details.
    delegation = []

    # dates and licensing officer
    # dates_licensing_officer_table_style = TableStyle([('VALIGN', (0, 0), (-2, -1), 'TOP'),
    #                                                   ('VALIGN', (0, 0), (-1, -1), 'BOTTOM')])

    # delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    # date_headings = [Paragraph('Date of Issue', styles['BoldLeft']), Paragraph('Valid From', styles['BoldLeft']),
    #                  Paragraph('Date of Expiry', styles['BoldLeft'])]
    # date_values = [Paragraph(approval.issue_date.strftime(DATE_FORMAT), styles['Left']),
    #                Paragraph(approval.start_date.strftime(DATE_FORMAT), styles['Left']),
    #                Paragraph(approval.expiry_date.strftime(DATE_FORMAT), styles['Left'])]

    # if approval.original_issue_date is not None:
    #     date_headings.insert(0, Paragraph('Original Date of Issue', styles['BoldLeft']))
    #     date_values.insert(0, Paragraph(approval.original_issue_date.strftime(DATE_FORMAT), styles['Left']))

    # delegation.append(Table([[date_headings, date_values]],
    #                         colWidths=(120, PAGE_WIDTH - (2 * PAGE_MARGIN) - 120),
    #                         style=dates_licensing_officer_table_style))

    # proponent details
    # delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    # address = proposal.applicant.organisation.postal_address
    # address_paragraphs = [Paragraph(address.line1, styles['Left']), Paragraph(address.line2, styles['Left']),
    #                       Paragraph(address.line3, styles['Left']),
    #                       Paragraph('%s %s %s' % (address.locality, address.state, address.postcode), styles['Left']),
    #                       Paragraph(address.country.name, styles['Left'])]
    # delegation.append(Table([[[Paragraph('Licensee:', styles['BoldLeft']), Paragraph('Address', styles['BoldLeft'])],
    #                           [Paragraph(_format_name(approval.applicant),
    #                                      styles['Left'])] + address_paragraphs]],
    #                         colWidths=(120, PAGE_WIDTH - (2 * PAGE_MARGIN) - 120),
    #                         style=approval_table_style))
    if user.phone_number:
        contact_number = user.phone_number
    elif user.mobile_number:
        contact_number = user.mobile_number
    else:
        contact_number= settings.DEP_PHONE

    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(Paragraph('Should you have any queries about this approval, please contact {} {}, '
                                'on {} or by email at {}'.format(user.first_name, user.last_name, contact_number, user.email), styles['Left']))
    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(Paragraph('To provide feedback on the system used to submit the approval or update contact details, please '
        'contact {} Works Coordinator - {}'.format(settings.SYSTEM_NAME_SHORT, settings.SUPPORT_EMAIL), styles['Left']))
    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(Paragraph('Approved on behalf of the', styles['Left']))
    delegation.append(Paragraph('{}'.format(settings.DEP_NAME), styles['BoldLeft']))
    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    delegation.append(Paragraph('{} {}'.format(user.first_name, user.last_name), styles['Left']))
    delegation.append(Paragraph('{}'.format(region_district), styles['Left']))
    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(Paragraph(approval.issue_date.strftime(DATE_FORMAT), styles['Left']))

    elements.append(KeepTogether(delegation))

    # Appendix section
    elements.append(PageBreak())
    elements.append(Paragraph('Appendix 1 - Management Actions', styles['BoldLeft']))
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    if copied_to_permit:
        # for k,v in copied_to_permit:
        #     elements.append(Paragraph(v.encode('UTF-8'), styles['Left']))
        #     elements.append(Paragraph(k.encode('UTF-8'), styles['Left']))
        #     elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        for item in copied_to_permit:
            for key in item:
               elements.append(Paragraph(key.encode('UTF-8'), styles['Left']))
               elements.append(Paragraph(item[key].encode('UTF-8'), styles['Left']))
    else:
        elements.append(Paragraph('There are no management actions.', styles['Left']))


    doc.build(elements)

    return approval_buffer
Exemplo n.º 17
0
def minutesToPdf(request, id_minutes):
    saveViewsLog(request, "pdfmodule.views.minutesToPdf")
    if request.user.is_staff:

        _minutes = minutes.objects.get(pk=id_minutes)

        # Datos del acta
        m_group = _minutes.id_group.name
        m_code = _minutes.code
        m_date_created = _minutes.date_created
        m_date_start = _minutes.id_extra_minutes.date_start
        m_date_end = _minutes.id_extra_minutes.date_end
        m_location = _minutes.id_extra_minutes.location
        m_agenda = _minutes.id_extra_minutes.agenda
        m_agreement = _minutes.id_extra_minutes.agreement

        # --------------------------------------------------------------
        # Creacion del PDF
        pdf_address = "/pdf/reporte%s.pdf" % (int(random.random() * 100000))

        # Generar el objeto canvas (documento PDF)
        from reportlab.pdfgen import canvas
        canvas_obj = canvas.Canvas("%s%s" % (MEDIA_ROOT, pdf_address))

        # Definiendo estilos basicos
        estiloHoja = getSampleStyleSheet()
        estilo1 = estiloHoja['BodyText']
        estilo2 = estiloHoja['Normal']

        # Inicializamos story (Listas de objetos flowables)
        story = []

        # Añadimos algunos flowables.
        p1 = Paragraph(u"Grupo: %s" % (m_group), estilo1)
        p2 = Paragraph(u"Codigo de acta: %s Creada el: %s" %
                       (m_code, m_date_created), estilo1)
        p3 = Paragraph(u"La reunion inicio el: %s Y finalizo el: %s" %
                       (m_date_start, m_date_end), estilo1)
        p4 = Paragraph(u"Lugar de encuentro: %s" % (m_location), estilo1)
        p5 = Paragraph(u"Orden de dia", estilo1)
        p6 = Paragraph(u"%s" % (m_agenda), estilo1)
        p7 = Paragraph(u"Conclusiones", estilo1)
        p8 = Paragraph(u"%s" % (m_agreement), estilo1)

        # Añadimos los flowables a la lista story.

        story.append(p1)
        story.append(p2)
        story.append(p3)
        story.append(p4)
        story.append(p5)
        story.append(p6)
        story.append(p7)
        story.append(p8)

        # creo los frames
        f1 = Frame(50, 600, 500, 200, showBoundary=1)

        # agregando los frames al objeto canvas
        f1.addFromList(story, canvas_obj)

        canvas_obj.save()

        return HttpResponseRedirect('/media%s' % (pdf_address))
    else:
        return HttpResponseRedirect('/')
Exemplo n.º 18
0
def _create_renewal(renewal_buffer, approval, proposal):
    site_url = settings.SITE_URL
    every_page_frame = Frame(PAGE_MARGIN, PAGE_MARGIN, PAGE_WIDTH - 2 * PAGE_MARGIN,
                             PAGE_HEIGHT - 160, id='EveryPagesFrame')
    every_page_template = PageTemplate(id='EveryPages', frames=[every_page_frame], onPage=_create_approval_header)

    doc = BaseDocTemplate(renewal_buffer, pageTemplates=[every_page_template], pagesize=A4)

    # this is the only way to get data into the onPage callback function
    doc.approval = approval
    doc.site_url = site_url

    approval_table_style = TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP')])

    elements = []


    title = approval.title.encode('UTF-8')

    # additional information
    '''if approval.additional_information:
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        elements.append(Paragraph('Additional Information', styles['BoldLeft']))
        elements += _layout_paragraphs(approval.additional_information)'''

    # delegation holds the dates, approvale and issuer details.
    delegation = []
    # proponent details
    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    address = proposal.applicant.organisation.postal_address
    address_paragraphs = [Paragraph(address.line1, styles['Left']), Paragraph(address.line2, styles['Left']),
                          Paragraph(address.line3, styles['Left']),
                          Paragraph('%s %s %s' % (address.locality, address.state, address.postcode), styles['Left']),
                          Paragraph(address.country.name, styles['Left'])]
    delegation.append(Table([[[Paragraph('Licensee:', styles['BoldLeft']), Paragraph('Address', styles['BoldLeft'])],
                              [Paragraph(_format_name(approval.applicant),
                                         styles['Left'])] + address_paragraphs]],
                            colWidths=(120, PAGE_WIDTH - (2 * PAGE_MARGIN) - 120),
                            style=approval_table_style))

    expiry_date = approval.expiry_date.strftime(DATE_FORMAT)
    full_name = proposal.submitter.get_full_name()

    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(Paragraph('Dear {} '.format(full_name), styles['Left']))

    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(Paragraph('This is a reminder that your approval: ', styles['Left']))

    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    title_with_number = '{} - {}'.format(approval.lodgement_number, title)

    delegation.append(Paragraph(title_with_number, styles['InfoTitleLargeLeft']))

    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(Paragraph('is due to expire on {}'.format(expiry_date), styles['Left']))

    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(Paragraph('Please note that if you have outstanding compliances these are required to be submitted before the approval can be renewed'
                                , styles['Left']))

    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(Paragraph('If you have any queries, contact the {} '
                                'on {}.'.format(settings.DEP_NAME, settings.DEP_PHONE), styles['Left']))

    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(Paragraph('Yours sincerely ', styles['Left']))
    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
    delegation.append(Paragraph('DIRECTOR GENERAL', styles['Left']))
    delegation.append(Paragraph('{}'.format(settings.DEP_NAME), styles['Left']))

    elements.append(KeepTogether(delegation))

    doc.build(elements)

    return renewal_buffer
Exemplo n.º 19
0
    def page_layouts(self, pagesize, cardsize, margins, spacing):
        """
            Generate page templates for front/back sides of cards

            @param pagesize: the page size, tuple (w, h)
            @param cardsize: the card size, tuple (w, h)
            @param margins: the page margins, tuple (N, E, S, W)
            @param spacing: the spacing between cards, tuple (H, V)

            - all sizes in points (72 points per inch)
        """

        pagewidth, pageheight = pagesize
        cardwidth, cardheight = cardsize

        topmargin, leftmargin = margins[0], margins[3]

        hspacing, vspacing = spacing

        # Y-position (from page bottom) of first card row
        y0 = pageheight - topmargin - cardheight

        # X-position of first card in a row
        # - front from the left, back from the right
        # - actual page width differs between printers, so we may need
        #   to add a parameter to account for this horizontal shift (TODO)
        x0_front = leftmargin
        x0_back = pagewidth - leftmargin - cardwidth  # + hshift

        fframes, bframes = [], []
        for i in range(self.rows_per_page):

            # Y-position of current row
            y = y0 - i * (vspacing + cardheight)

            # Add frames for cards in this row
            for j in range(self.cards_per_row):

                # Front
                fframes.append(
                    Frame(
                        x0_front + j * (cardwidth + hspacing),
                        y,
                        cardwidth,
                        cardheight,
                        topPadding=0,
                        rightPadding=0,
                        bottomPadding=0,
                        leftPadding=0,
                    ))

                # Back
                bframes.append(
                    Frame(
                        x0_back - j * (cardwidth + hspacing),
                        y,
                        cardwidth,
                        cardheight,
                        topPadding=0,
                        rightPadding=0,
                        bottomPadding=0,
                        leftPadding=0,
                    ))

        # Generate and return the page templates
        return [
            PageTemplate(id="Front", frames=fframes),
            PageTemplate(id="Back", frames=bframes),
        ]
def generate_certificate(attestID, navn, firmanavn, kursnavn, kursdato,
                         kurssted, kursnavn2, kursdato2, pdf_filename,
                         navnASCII):
    attestID += 1
    with open(pdf_filename, "w+") as f:
        # Geometry
        c = canvas.Canvas(pdf_filename, pagesize=A4)
        width = A4[0]
        height = A4[1]
        x = 0
        halfWidth = width / 2
        quarterWidth = width / 4
        threeQuarterWidth = quarterWidth * 3

        # Draws basic properties, incl. filling the canvas with the desired color and adding a background logo
        frame = Frame(0, 0, width, height - 2 * cm, showBoundary=False)
        c.setFillColor(HexColor(hexBaseGroenn))
        b = c.beginPath()
        b.moveTo(x, x)
        b.lineTo(x, height)
        b.lineTo(width, height)
        b.lineTo(width, x)
        c.drawPath(b, True, True)
        c.drawImage('img/questback_mark.png',
                    5, (height / 4),
                    width=(1776 / 3),
                    height=(1182 / 3),
                    mask='auto')
        c.setStrokeColor(HexColor(hexHvit))
        c.setFillColor(HexColor(hexHvit))
        c.setFont('Helvetica-Bold', 52, leading=True)
        c.drawCentredString((halfWidth), 675, 'academy')

        # Draws language specific properties
        try:
            if kurssted == "Oslo" or kurssted == "Trondheim":
                c.setFont('Helvetica-Bold', 32, leading=True)
                c.drawCentredString(halfWidth, 550, TITLE)
                c.setFont('Helvetica-Bold', 34, leading=False)
                c.drawCentredString(halfWidth, 450, navn)
                c.setFont('Helvetica', 24, leading=False)
                c.drawCentredString(halfWidth, 500, norIssuedBecause)
                c.drawCentredString(halfWidth, 400,
                                    norFrom + blank + firmanavn)
                c.drawCentredString(halfWidth, 350, norIssuedTo)
                c.drawCentredString(halfWidth, 300,
                                    kursnavn + blank + THE + blank + kursdato)
                c.drawCentredString(halfWidth, 275,
                                    kursnavn2 + THE + blank + kursdato2)
                c.drawCentredString(halfWidth, 250, IN + blank + kurssted)
                c.setFont('Helvetica', 18, leading=False)
                c.drawCentredString(quarterWidth, 100, WIL)
                c.drawCentredString(quarterWidth, 75, HSA)
                c.drawCentredString(quarterWidth, 50, today)
                c.drawCentredString(threeQuarterWidth, 100, HAK)
                c.drawCentredString(threeQuarterWidth, 75, NAM)
                c.drawCentredString(threeQuarterWidth, 50, today)
            elif kurssted == "Stockholm":
                c.setFont('Helvetica-Bold', 32, leading=True)
                c.drawCentredString(halfWidth, 550, TITLE)
                c.setFont('Helvetica-Bold', 34, leading=False)
                c.drawCentredString(halfWidth, 450, navn)
                c.setFont('Helvetica', 24, leading=False)
                c.drawCentredString(halfWidth, 500, sweIssuedTo)
                c.drawCentredString(halfWidth, 400,
                                    sweFrom + blank + firmanavn)
                c.drawCentredString(halfWidth, 350, sweIssuedBecause + blank)
                c.drawCentredString(halfWidth, 300,
                                    kursnavn + blank + THE + blank + kursdato)
                c.drawCentredString(
                    halfWidth, 275,
                    kursnavn2 + blank + THE + blank + kursdato2)
                c.drawCentredString(halfWidth, 250, IN + blank + kurssted)
                c.setFont('Helvetica', 18, leading=False)
                c.drawCentredString(quarterWidth, 100, WIL)
                c.drawCentredString(quarterWidth, 75, HSA)
                c.drawCentredString(quarterWidth, 50, today)
                c.drawCentredString(threeQuarterWidth, 100, HAK)
                c.drawCentredString(threeQuarterWidth, 75, NAM)
                c.drawCentredString(threeQuarterWidth, 50, today)
        except Exception as err:
            print("Tegningen feilet %s\n%s" % (pdf_filename, err))

        # Draws a line below signatures
        c.setLineJoin(mode=2)
        c.setLineWidth(1)
        p = c.beginPath()
        p.moveTo(50, 122)
        p.lineTo(250, 122)
        p.close()
        p.moveTo(350, 122)
        p.lineTo(550, 122)
        p.close()
        c.drawPath(p, fill=1, stroke=1)

        # Adds signatures (use e.g. https://onlinepngtools.com/create-transparent-png to flaten new signatures (remove any noise)
        c.drawImage('img/wilhelm.png',
                    50,
                    110,
                    width=200,
                    height=100,
                    mask=[0, 0, 0, 0, 0, 0])
        c.drawImage('img/hakon.png',
                    350,
                    110,
                    width=200,
                    height=100,
                    mask=[0, 0, 0, 0, 0, 0])

        story = []
        story.append(get_image('img/questback_white.png', width=width / 1.25))
        frame.addFromList(story, c)
        c.showPage()
        c.save()
        f.close()

        print(f"Sertifisering for {navnASCII} er generert")
        return attestID
Exemplo n.º 21
0
    def getStyle(self, page):
        frames = []

        if page == 1:  # first page
            # main header
            frames.append(
                Frame(1 * cm,
                      25.5 * cm,
                      19 * cm,
                      3 * cm,
                      leftPadding=0,
                      rightPadding=0,
                      id='normal',
                      showBoundary=0))
            # top 10
            frames += self.getStatTop("frames")

        elif page == 2:  # page 2
            # main header pages >1
            frames.append(
                Frame(1 * cm,
                      27.5 * cm,
                      19 * cm,
                      1 * cm,
                      leftPadding=0,
                      rightPadding=0,
                      id='normal',
                      showBoundary=0))
            # countries
            frames += self.getStatCountry("frames")

        elif page == 3:  # page 3
            # main header pages >1
            frames.append(
                Frame(1 * cm,
                      27.5 * cm,
                      19 * cm,
                      1 * cm,
                      leftPadding=0,
                      rightPadding=0,
                      id='normal',
                      showBoundary=0))
            # date
            frames += self.getStatDate("frames")

        elif page == 4:  # page 4
            # main header pages >1
            frames.append(
                Frame(1 * cm,
                      27.5 * cm,
                      19 * cm,
                      1 * cm,
                      leftPadding=0,
                      rightPadding=0,
                      id='normal',
                      showBoundary=0))
            # weekday
            frames += self.getStatDay("frames")

            # time
            frames += self.getStatTime("frames")

        return frames
Exemplo n.º 22
0
    def gen_pdf(self):
        print('Combining Images into PDF.....')
        path1 = image_dir + 'week_heatmap.png'
        path2 = image_dir + 'memory.png'
        path3 = image_dir + 'word_cloud.png'
        path4 = image_dir + 'bar.png'
        path5 = image_dir + 'score.png'
        path6 = image_dir + 'red.png'
        pdf = PdfFileWriter()

        # Using ReportLab Canvas to insert image into PDF
        imgTemp = BytesIO()
        imgDoc = canvas.Canvas(imgTemp, pagesize=(2000, 2300))

        # heat map x, y - start position
        imgDoc.drawImage(path1, -150, 1400, width=2600, height=650)
        # memory
        imgDoc.drawImage(path2, 1070, 681, width=697, height=667)
        # word_cloud
        imgDoc.drawImage(path3, -28, 585, width=1100, height=778)
        # score
        imgDoc.drawImage(path5, 1128, -59, width=894, height=672)
        # bar
        imgDoc.drawImage(path4, 0, -11, width=1286, height=620)
        # logo
        imgDoc.drawImage(logo, 99, 2068, width=105, height=80)
        # red square
        imgDoc.drawImage(path6, inch * 24.3, inch * 16.25, width=91, height=45)
        imgDoc.drawImage(path6, inch * 24.3, inch * 14.69, width=91, height=45)
        imgDoc.drawImage(path6, inch * 24.3, inch * 13.14, width=91, height=45)
        imgDoc.drawImage(path6, inch * 24.3, inch * 11.60, width=91, height=45)

        # draw three lines, x,y,width,height
        imgDoc.rect(0.83 * inch, 28.5 * inch, 26.0 * inch, 0.04 * inch, fill=1)
        imgDoc.rect(0.83 * inch, 18.9 * inch, 26.0 * inch, 0.04 * inch, fill=1)
        imgDoc.rect(0.83 * inch, 8.5 * inch, 26.0 * inch, 0.04 * inch, fill=1)
        # title
        imgDoc.setFont('Helvetica-Bold', 82)
        imgDoc.drawString(
            212,
            2078,
            "Personal YouTube Usage Report",
        )

        # first watch
        bodyStyle = ParagraphStyle('Body', fontSize=31)
        items1 = []
        link1 = '<link href=' + urls[-1] + '>PLAY</link>'
        items1.append(Paragraph(link1, bodyStyle))
        f1 = Frame(inch * 24.3, inch * 14.88, inch * 12, inch * 2)
        f1.addFromList(items1, imgDoc)

        # most watch
        items2 = []
        link2 = '<link href=' + max(set(urls), key=urls.count) + '>PLAY</link>'
        items2.append(Paragraph(link2, bodyStyle))
        f2 = Frame(inch * 24.3, inch * 13.34, inch * 12, inch * 2)
        f2.addFromList(items2, imgDoc)

        # first like
        items3 = []
        link3 = '<link href=' + like + '>PLAY</link>'
        items3.append(Paragraph(link3, bodyStyle))
        f3 = Frame(inch * 24.3, inch * 11.79, inch * 12, inch * 2)
        f3.addFromList(items3, imgDoc)

        # first comment
        items4 = []
        link4 = '<link href=' + link + '>PLAY</link>'
        items4.append(Paragraph(link4, bodyStyle))
        f4 = Frame(inch * 24.3, inch * 10.25, inch * 12, inch * 2)
        f4.addFromList(items4, imgDoc)

        # first search
        items4 = []
        link4 = '<link href=' '>' + str(
            re.sub('[^\w\s]', '', str(searchRaw[-1]))) + '</link>'
        items4.append(Paragraph(link4, bodyStyle))
        f4 = Frame(inch * 23.7, inch * 8.73, inch * 12, inch * 2)
        f4.addFromList(items4, imgDoc)

        imgDoc.save()
        pdf.addPage(PdfFileReader(BytesIO(imgTemp.getvalue())).getPage(0))
        pdf.write(open("YouTube_Report.pdf", "wb"))
        print(
            'Congratulations! You have successfully created your personal YouTube report!'
        )
        if sys.platform == "win32":
            os.startfile("YouTube_Report.pdf")
        else:
            opener = "open" if sys.platform == "darwin" else "xdg-open"
            subprocess.call([opener, "YouTube_Report.pdf"])
Exemplo n.º 23
0
    def getStatCountry(self, type):
        items = []
        d = self.stats.getProgress('country')
        max = float(d[0]["max"])

        if type == "frames":
            # header country
            items.append(
                Frame(1 * cm,
                      26.0 * cm,
                      19 * cm,
                      1 * cm,
                      leftPadding=0,
                      rightPadding=0,
                      id='normal',
                      showBoundary=0))
            i = 0
            for v in sorted([(len(d[k]['items']), k)
                             for k in filter(lambda x: x != 0, d.keys())],
                            reverse=True):
                if v[0] != 0:
                    items.append(
                        Frame(1 * cm, (25.1 - (i * 0.5)) * cm,
                              3 * cm,
                              25,
                              leftPadding=0,
                              rightPadding=0,
                              id='normal',
                              showBoundary=0))  # label
                    items.append(
                        Frame(4 * cm, (25.2 - (i * 0.5)) * cm,
                              v[0] * 400 / max,
                              25,
                              leftPadding=0,
                              rightPadding=0,
                              id='normal',
                              showBoundary=0))  # bar
                    items.append(
                        Frame(4 * cm + (v[0] * 400 / max) + 5,
                              (25.1 - (i * 0.5)) * cm,
                              40,
                              25,
                              leftPadding=0,
                              rightPadding=0,
                              id='normal',
                              showBoundary=0))  # number
                    i += 1

        if type == "data":
            items.append(
                Paragraph(t(self.language, "edit_stats_country"),
                          self.chartheader))
            items.append((FrameBreak()))

            for v in sorted([(len(d[k]['items']), k)
                             for k in filter(lambda x: x != 0, d.keys())],
                            reverse=True)[:50]:
                if v[0] != 0:
                    items.append(Paragraph(str(v[1]), self.bv))
                    items.append((FrameBreak()))
                    items.append(
                        PdfImage(config.basedir + "/web/img/stat_bar.png",
                                 width=v[0] * 400 / max,
                                 height=10))
                    items.append((FrameBreak()))
                    items.append(Paragraph(str(v[0]), self.bv))
                    items.append((FrameBreak()))

            items = items[:-1]
        return items
Exemplo n.º 24
0
from reportlab.lib.pagesizes import letter
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus import BaseDocTemplate, Frame, PageTemplate, Paragraph

styles = getSampleStyleSheet()
styleN = styles['Normal']
styleH = styles['Heading1']


def footer(canvas, doc):
    canvas.saveState()
    P = Paragraph("This is a multi-line footer.  It goes on every page.  " * 5,
                  styleN)
    w, h = P.wrap(doc.width, doc.bottomMargin)
    P.drawOn(canvas, doc.leftMargin, h)
    canvas.restoreState()


doc = BaseDocTemplate('testpg.pdf', pagesize=letter)
frame = Frame(doc.leftMargin,
              doc.bottomMargin,
              doc.width,
              doc.height,
              id='normal')
template = PageTemplate(id='test', frames=frame, onPage=footer)
doc.addPageTemplates([template])

text = []
for i in range(111):
    text.append(Paragraph("This is line %d." % i, styleN))
doc.build(text)
Exemplo n.º 25
0
    def getStatDay(self, type):
        d = self.stats.getProgress('day')
        max = d[0]
        items = []

        h = 4 * cm  # max height
        l = 2 * cm  # left space
        b = 21.5 * cm  # bottom

        if type == "frames":
            # header weekday
            items.append(
                Frame(1 * cm,
                      26.0 * cm,
                      19 * cm,
                      1 * cm,
                      leftPadding=0,
                      rightPadding=0,
                      id='normal',
                      showBoundary=0))
            for k in d:
                if k == 0:
                    continue
                items.append(
                    Frame(l + (k - 1) * 17,
                          b,
                          16,
                          len(d[k]["visitors"]) * h / max["max_u"] + 16,
                          leftPadding=0,
                          rightPadding=0,
                          id='normal',
                          showBoundary=0))  # col 1
                items.append(
                    Frame(l + (k - 1) * 17 + 5,
                          b,
                          16,
                          len(d[k]["different"]) * h / max["max_p"] + 16,
                          leftPadding=0,
                          rightPadding=0,
                          id='normal',
                          showBoundary=0))  # col 2
                items.append(
                    Frame(l + (k - 1) * 17 + 10,
                          b,
                          16,
                          len(d[k]["items"]) * h / max["max"] + 16,
                          leftPadding=0,
                          rightPadding=0,
                          id='normal',
                          showBoundary=0))  # col 3

            items.append(
                Frame(l + 5,
                      b - 1.1 * cm,
                      119,
                      1.5 * cm,
                      id='normal',
                      showBoundary=0))
            items.append(
                Frame(8 * cm,
                      b - 1.4 * cm,
                      11 * cm,
                      6 * cm,
                      id='normal',
                      showBoundary=0))

        if type == "data":
            items.append(
                Paragraph(t(self.language, "edit_stats_spreading_day"),
                          self.chartheader))

            for k in d:
                if k == 0:
                    continue
                items.append(
                    PdfImage(config.basedir + "/web/img/stat_baruser_vert.png",
                             width=5,
                             height=len(d[k]["visitors"]) * h / max["max_u"] +
                             1))
                items.append(FrameBreak())
                items.append(
                    PdfImage(config.basedir + "/web/img/stat_barpage_vert.png",
                             width=5,
                             height=len(d[k]["different"]) * h / max["max_p"] +
                             1))
                items.append(FrameBreak())
                items.append(
                    PdfImage(config.basedir + "/web/img/stat_bar_vert.gif",
                             width=6,
                             height=len(d[k]["items"]) * h / max["max"] + 1))
                items.append(FrameBreak())

            tb = Table([[
                t(self.language, "dayname_" + str(x) + "_short")
                for x in range(0, 7)
            ]], 7 * [17], 17)
            tb.setStyle(
                TableStyle([
                    ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                    ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                    ('INNERGRID', (0, 0), (-1, -1), 1, colors.black),
                    ('BOX', (0, 0), (-1, -1), 1, colors.black),
                    ('FONTNAME', (0, 0), (-1, -1), 'Helvetica'),
                    ('FONTSIZE', (0, 0), (-1, -1), 7),
                    ('BACKGROUND', (5, 0), (-1, -1),
                     colors.HexColor('#E6E6E6')),
                ]))
            items.append(tb)
            items.append(FrameBreak())

            t_data = [[t(self.language, "dayname_" + str(x) + "_long")]
                      for x in range(0, 7)]

            for k in d:
                if k == 0:
                    continue
                t_data[k - 1] += [len(d[k][key]) for key in d[k].keys()]
            t_data = [[
                t(self.language, "edit_stats_weekday"),
                t(self.language, "edit_stats_diffusers").replace(
                    "<br/>", "\n"),
                t(self.language, "edit_stats_pages"),
                t(self.language, "edit_stats_access")
            ]] + t_data

            tb = Table(t_data, 4 * [70], [25] + 7 * [16])
            tb.setStyle(
                TableStyle([
                    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                    ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                    ('INNERGRID', (0, 0), (-1, -1), 1, colors.black),
                    ('BOX', (0, 0), (-1, -1), 1, colors.black),
                    ('FONTNAME', (0, 0), (-1, -1), 'Helvetica'),
                    ('FONTSIZE', (0, 0), (-1, -1), 7),
                    ('BACKGROUND', (1, 0), (1, 0), colors.HexColor('#fff11d')),
                    ('BACKGROUND', (2, 0), (2, 0), colors.HexColor('#2ea495')),
                    ('BACKGROUND', (3, 0), (3, 0), colors.HexColor('#84a5ef')),
                ]))
            items.append(tb)
        return items
Exemplo n.º 26
0
def generateLogs(argv, printcmd, location="./"):
    # FIRST, figure out what days we are going to be printing logs for
    import calendar
    import datetime

    calendar.setfirstweekday(calendar.SUNDAY)

    if len(argv) < 4:
        printcmd("should be:\n\t%s <year> <month> <day> [number of days]\n" %
                 argv[0])
        return

    year = int(argv[1])
    month = int(argv[2])
    day = int(argv[3])
    today = datetime.datetime(year, month, day)

    numdays = 7
    try:
        numdays = int(argv[4])
    except IndexError:
        pass
    except ValueError:
        pass

    if today.weekday() != calendar.SUNDAY:
        printcmd(
            "This is supposed to start on a Sunday.  I assume you know what you're doing.\n"
        )

    dates = [today + datetime.timedelta(i) for i in xrange(numdays)]
    progEvents = dict([(date, []) for date in dates])
    opEvents = dict([(date, []) for date in dates])

    # SECOND, download the schedule
    # TODO: get rid of this and just talk to the database or whatever directly if
    #       that's at all possible!  This is a little silly!  If we're going to
    #       output things this way, we should put out an XML file!

    import urllib
    import codecs
    import model
    import json

    if True:
        printcmd("Downloading schedule...")
        sched_raw = unicode(
            urllib.urlopen(
                'http://www.wmbr.org/~lowe/templogs.php?start_year=%d&start_month=%d&start_day=%d&num_days=%d'
                % (year, month, day, numdays)).read(), "iso-8859-1")
        printcmd("Done.\n")
    else:
        printcmd("Using cached schedule (probably not what you want)...")
        sched_raw = "".join(
            codecs.open("templogs_sample", "r", "iso-8859-1").readlines())
        printcmd("Done.\n")

    timestrtodelta = lambda timestr: datetime.timedelta(
        0, sum(map(lambda x, y: int(x) * y, timestr.split(":"), [60 * 60, 60]))
    )

    printcmd("Adding shows...")

    schedule = json.loads(sched_raw)
    for date_str in schedule:
        year = int(date_str.split("-")[0])
        month = int(date_str.split("-")[1])
        day = int(date_str.split("-")[2])
        date = datetime.datetime(year, month, day)
        for show in schedule[date_str]:
            if show["type"] == "show":
                progEvents[date].append(
                    model.show(show["show_name"],
                               date + timestrtodelta(show["start_time"]),
                               date + timestrtodelta(show["end_time"]),
                               show["engineer"], show["producers"],
                               show["announcers"]))
            elif show["type"] == "signoff":
                opEvents[date].append((date + timestrtodelta(show["time"]),
                                       'TURN OFF TRANSMITTER'))
                progEvents[date].append(
                    model.signoff(date + timestrtodelta(show["time"])))
            elif show["type"] == "signon":
                opEvents[date].append(
                    (date + timestrtodelta(show["time"]),
                     'TEST EAS LIGHTS AND TURN ON TRANSMITTER'))
                progEvents[date].append(
                    model.signon(date + timestrtodelta(show["time"])))

    printcmd("Done.\n")

    # THIRD, compute other events that will occur on a particular day

    printcmd("Inserting FCC events (EAS tests, tower lights)...")

    import random

    # which dates should have an EAS test?
    easDays = [
        random.sample(dlist, 1)[0] for dlist in
        [[d for d in dates[i:i + 7] if d.strftime("%A") != "Sunday"]
         for i in xrange(len(dates) / 7)] if len(dlist) > 0
    ]

    # check the tower lights at civil twilight
    import twilight

    twilights = map(twilight.twilight, dates)
    for date in dates:
        twilightTime = twilight.twilight(date)
        opEvents[date].append((twilightTime, "CHECK TOWER LIGHTS: READING ="))

        # random EAS check once per week (taken from last version)
        # EAS tests must be conducted between 8:30 AM and twilight.
        # It is by WMBR convention that they are conducted at half
        # past an hour.  To be conservative, I also bring back the
        # late limit to half-past the previous hour from twilight,
        # thus avoiding any issues involving having the EAS test
        # and twilight too close together.
        if date in easDays:
            easDateTime = date + datetime.timedelta(
                0,
                random.randrange(8, twilightTime.hour) * 60 * 60 + 30 * 60)
            opEvents[date].append(
                (easDateTime, "CONDUCT REQUIRED WEEKLY EAS TEST"))

    printcmd("Done\n")

    # FOURTH, produce the pdf

    import os
    from reportlab.platypus import BaseDocTemplate, Frame, NextPageTemplate, PageBreak, PageTemplate, Table, TableStyle, Paragraph, flowables
    from reportlab.lib import colors
    from reportlab.lib.units import inch
    from reportlab.lib.pagesizes import letter
    from reportlab.lib.styles import getSampleStyleSheet
    from reportlab.rl_config import defaultPageSize
    import tablegen
    import progtablegen

    #letter paper
    PAGE_WIDTH, PAGE_HEIGHT = letter
    styles = getSampleStyleSheet()
    Elements = []

    def foot(title):
        def _foot(canvas, doc):
            today = datetime.date(doc.docEval("currentYear"),
                                  doc.docEval("currentMonth"),
                                  doc.docEval("currentDay"))
            canvas.saveState()
            canvas.setFont('Times-Roman', 20)
            canvas.drawString(0.3 * inch, PAGE_HEIGHT - 0.7 * inch, title)
            canvas.drawRightString(PAGE_WIDTH - 0.5 * inch,
                                   PAGE_HEIGHT - 0.7 * inch,
                                   today.strftime("%A, %b %d, %Y"))
            # this draws the page number on the outside corner of the log
            if doc.page % 2 == 0:
                canvas.drawString(0.3 * inch, 0.3 * inch,
                                  "Page %d" % (doc.page))
            else:
                canvas.drawRightString(PAGE_WIDTH - 0.5 * inch, 0.3 * inch,
                                       "Page %d" % (doc.page))
            canvas.restoreState()

        return _foot

    def title(title):
        def _title(canvas, doc):
            canvas.saveState()
            canvas.setFont('Times-Roman', 20)
            canvas.drawString(0.3 * inch, PAGE_HEIGHT - 0.7 * inch, title)
            canvas.drawRightString(
                PAGE_WIDTH - 0.5 * inch, PAGE_HEIGHT - 0.7 * inch,
                "%02d/%02d/%d — %02d/%02d/%d" %
                (dates[0].month, dates[0].day, dates[0].year, dates[-1].month,
                 dates[-1].day, dates[-1].year))
            canvas.restoreState()

        return _title

    def rulesPage():
        import op_title

        eltList = []
        paraPrefix = "<para"
        for elt in op_title.contents.split(paraPrefix):
            if len(elt.strip()) > 0:
                eltList.append(Paragraph(paraPrefix + elt, styles['Normal']))
        data = [["Henry Holtzman", "Home: 617-327-1298", "Work: 617-253-0319"],
                ["Ted Young", "Home: 617-776-7473", "Cell: 617-447-8439"]]
        eltList.append(Table(data, style=[('SIZE', (0, 0), (-1, -1), 12)]))
        return eltList

    def SigPage():
        data = [[
            "CUSTODIAN (print name)", "INITIALS", "TIME ON", "SIGNATURE",
            "TIME OFF", "SIGNATURE"
        ]] + [[None] * 6] * 22
        tableWidths = [2 * inch, None, None, 1.7 * inch, None, 1.7 * inch]
        tableHeights = [None] + [30] * 22
        t = Table(data, tableWidths, tableHeights)
        t.setStyle(
            TableStyle([
                ('VALIGN', (0, 0), (-1, 0), 'TOP'),
                ('ALIGN', (0, 0), (-1, 0), 'CENTER'),
                ('ALIGN', (3, 0), (3, 0), 'RIGHT'),
                ('ALIGN', (5, 0), (5, 0), 'RIGHT'),
                ('GRID', (0, 0), (1, -1), .6, colors.black),
                ('LINEABOVE', (2, 0), (3, -1), .6, colors.black),
                ('LINEAFTER', (3, 0), (3, -1), .6, colors.black),
                ('LINEABOVE', (4, 0), (5, -1), .6, colors.black),
                ('LINEAFTER', (5, 0), (5, -1), .6, colors.black),
                ('BOX', (0, 0), (-1, -1), 2, colors.black),
                ('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey),
                ('VALIGN', (0, 1), (0, -1), 'MIDDLE'),
            ]))
        return t

    ## The operating log

    printcmd("Writing operating log...")

    doc = BaseDocTemplate(location + "oplog.pdf",
                          showBoundary=0,
                          allowSplitting=0,
                          leftMargin=0.5 * inch,
                          rightMargin=0.5 * inch,
                          topMargin=1.4 * inch,
                          bottomMargin=0.5 * inch)

    frameNormal = Frame(doc.leftMargin,
                        doc.bottomMargin,
                        doc.width,
                        doc.height,
                        id='normal')

    Elements.extend(rulesPage())

    for date in dates:
        Elements.append(flowables.DocAssign("currentYear", date.year))
        Elements.append(flowables.DocAssign("currentMonth", date.month))
        Elements.append(flowables.DocAssign("currentDay", date.day))
        tables = tablegen.make_day_tables(opEvents[date])
        Elements.append(NextPageTemplate('OTALogPage'))
        Elements.append(PageBreak())
        Elements.append(SigPage())
        for table in tables:
            Elements.append(NextPageTemplate('OpLogPage'))
            Elements.append(PageBreak())
            Elements.append(table)

    doc.addPageTemplates([
        PageTemplate(id='Title',
                     frames=frameNormal,
                     onPage=title("WMBR Operating Log"),
                     pagesize=letter),
        PageTemplate(id='OTALogPage',
                     frames=frameNormal,
                     onPage=foot("WMBR Operating Log"),
                     pagesize=letter),
        PageTemplate(id='OpLogPage',
                     frames=frameNormal,
                     onPage=foot("WMBR Operating Log"),
                     pagesize=letter)
    ])

    #start the construction of the pdf
    doc.build(Elements)

    printcmd("Done\n")

    ## The programming log

    printcmd("Writing programming log...")
    doc = BaseDocTemplate(location + "proglog.pdf",
                          showBoundary=0,
                          allowSplitting=0,
                          leftMargin=0.5 * inch,
                          rightMargin=0.5 * inch,
                          topMargin=1.4 * inch,
                          bottomMargin=0.5 * inch)

    frameNormal = Frame(doc.leftMargin,
                        doc.bottomMargin,
                        doc.width,
                        doc.height,
                        id='normal')

    Elements.extend(rulesPage())

    for date in dates:
        Elements.append(flowables.DocAssign("currentYear", date.year))
        Elements.append(flowables.DocAssign("currentMonth", date.month))
        Elements.append(flowables.DocAssign("currentDay", date.day))
        tables = progtablegen.make_day_tables(progEvents[date])
        Elements.append(NextPageTemplate('OTALogPage'))
        Elements.append(PageBreak())
        Elements.append(SigPage())
        Elements.append(NextPageTemplate('ProgLogPage'))
        Elements.append(PageBreak())
        Elements.extend(tables)

    doc.addPageTemplates([
        PageTemplate(id='Title',
                     frames=frameNormal,
                     onPage=title("WMBR Programming Log"),
                     pagesize=letter),
        PageTemplate(id='OTALogPage',
                     frames=frameNormal,
                     onPage=foot("WMBR Programming Log"),
                     pagesize=letter),
        PageTemplate(id='ProgLogPage',
                     frames=frameNormal,
                     onPage=foot("WMBR Programming Log"),
                     pagesize=letter)
    ])

    #start the construction of the pdf
    doc.build(Elements)
    printcmd("Done\n")
    printcmd("Finished.\n")
Exemplo n.º 27
0
from reportlab.pdfgen.canvas import Canvas
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import inch
from reportlab.platypus import Paragraph, Frame
styles = getSampleStyleSheet()
styleN = styles['Normal']
styleH = styles['Heading1']
styleF = styles['Heading2']
story = []
#add some flowables
story.append(Paragraph("Certification Report"
                       "Meeting Date: January 28,2016"
                       "County PIG Program",styleH))
story.append(Paragraph("This is a paragraph in <i>Normal</i> style.",
styleN))
c = Canvas('mydoc.pdf')
f = Frame(inch, inch, 6*inch, 9*inch, showBoundary=1)
f.addFromList(story,c)
c.save()
Exemplo n.º 28
0
def pdf(patient, exam, plan, folder=report_folder, fields=None, overwrite=True, priority=4):
    tic = time.time()
    filename = os.path.join(folder, '{}_{}.pdf'.format(patient.Name.replace('^', '_'), plan.Name))
    if overwrite and os.path.isfile(filename):
        logging.debug('Deleting existing file per overwrite flag')
        os.remove(filename)

    # Initialize Platypus document
    logging.debug('Initializing PDF to save to {}'.format(filename))
    doc = BaseDocTemplate(filename,
                          pagesize=letter,
                          pageTemplates=[PageTemplate(id='all',
                                                      frames=[Frame(0.75 * inch, 0.75 * inch, 7 * inch, 9.5 * inch,
                                                                    showBoundary=0)])],
                          showBoundary=0,
                          rightMargin=0.75 * inch,
                          leftMargin=0.75 * inch,
                          bottomMargin=0.75 * inch,
                          topMargin=0.75 * inch,
                          allowSplitting=1,
                          title='Treatment Planning Order',
                          encrypt=None)

    # Define text style
    s = ParagraphStyle({'fontName': 'Helvetica',
                        'fontSize': 10,
                        'leading': 10,
                        'leftIndent': 0,
                        'rightIndent': 0,
                        'firstLineIndent': 0,
                        'encoding': 'Unicode',
                        'alignment': TA_LEFT,
                        'spaceBefore': 0,
                        'spaceAfter': 0,
                        'bulletFontName': 'Helvetica',
                        'bulletFontSize': 10,
                        'bulletIndent': 0,
                        'textColor': colors.black,
                        'backColor': None,
                        'wordWrap': None,
                        'borderWidth': 0,
                        'borderPadding': 0,
                        'borderColor': None,
                        'borderRadius': None,
                        'allowWidows': 1,
                        'allowOrphans': 0,
                        'textTransform': None,
                        'endDots': None,
                        'splitLongWords': 1,
                        'bulletAnchor': 'start',
                        'justifyLastLine': 0,
                        'justifyBreaks': 0})

    # Start report
    story = [Table(data=[[Image(os.path.join(os.path.dirname(__file__), 'report_logo.jpg'),
                                width=2 * inch,
                                height=0.4306 * inch),
                          P('<b><font size=14>' + fields['protocol'] + ' Treatment Planning Order</font></b>', s)]],
                   colWidths=[2.5 * inch, 5 * inch],
                   spaceAfter=0.25 * inch,
                   hAlign='LEFT',
                   style=TableStyle([('VALIGN', (0, 0), (-1, -1), 'MIDDLE')]))]

    # Retrieve CT info
    info = exam.GetAcquisitionDataFromDicom()
    story.append(Table(data=[[P('<b>Name:</b>', s), P(patient.Name.replace('^', ' '), s)],
                             [P('<b>Patient ID:</b>', s), P(patient.PatientID, s)],
                             [P('<b>Date of Birth:</b>', s), P('{}/{}/{}'.format(patient.DateOfBirth.Month,
                                                                                 patient.DateOfBirth.Day,
                                                                                 patient.DateOfBirth.Year), s)],
                             [P('<b>Clinic:</b>', s), P(fields['institution'], s)],
                             [P('<b>Diagnosis:</b>', s), P(' '.join(fields['diagnosis']), s)],
                             [P('<b>Order:</b>', s), P(fields['order'], s)],
                             [P('<b>Planning Image:</b>', s), P('{}, {} {}'.
                                                                format(exam.Name,
                                                                       info['EquipmentModule']['InstitutionName'],
                                                                       info['EquipmentModule']['StationName']), s)],
                             [P('<b>Plan Name:</b>', s), P(plan.Name, s)]
                             ],
                       colWidths=[1.5 * inch, 5 * inch],
                       spaceAfter=0.25 * inch,
                       hAlign='LEFT',
                       style=TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP')])))

    # If a fields dict was not provided, query the provided plan
    if fields is None:
        fields = {'plans': [], 'fractions': [], 'technique': []}
        for b in plan.BeamSets:
            fields['plans'].append(b.DicomPlanLabel)
            fields['fractions'].append(b.FractionationPattern.NumberOfFractions)
            fields['technique'].append(b.DeliveryTechnique)

    # Generate plan details table
    details_header = [P('<b>Plan Details</b>', s)]
    for p in fields['plans']:
        details_header.append(P('<b>{}</b>'.format(p.replace('_R0A0', '_RXAX')), s))

    details = list([details_header])
    details.append([P('Number of Fractions', s)])
    for n in range(len(fields['plans'])):
        if len(fields['fractions']) > n and fields['fractions'][n] is not None:
            details[-1].append(P('{}'.format(fields['fractions'][n]), s))

        else:
            details[-1].append(details[-1][-1])

    if 'technique' in fields and len(fields['technique']) > 0 and fields['technique'][0] is not None:
        details.append([P('Technique', s)])
        for n in range(len(fields['plans'])):
            details[-1].append(P(fields['technique'][min(n, len(fields['technique'])-1)], s))

    if 'frequency' in fields and len(fields['frequency']) > 0 and fields['frequency'][0] is not None:
        details.append([P('Treatment frequency', s)])
        for n in range(len(fields['plans'])):
            details[-1].append(P(fields['frequency'][min(n, len(fields['frequency']) - 1)], s))

    if 'imaging' in fields and len(fields['imaging']) > 0 and fields['imaging'][0] is not None:
        details.append([P('Image guidance', s)])
        for n in range(len(fields['plans'])):
            details[-1].append(P(fields['imaging'][min(n, len(fields['imaging']) - 1)], s))

    if 'motion' in fields and len(fields['motion']) > 0 and fields['motion'][0] is not None:
        details.append([P('Motion management', s)])
        for n in range(len(fields['plans'])):
            details[-1].append(P(fields['motion'][min(n, len(fields['motion']) - 1)], s))

    width = min(1.5, 4.5 / len(details[0])) * inch
    story.append(Table(data=details,
                       colWidths=[1.5 * inch] + [width] * len(fields['plans']),
                       spaceAfter=0.25 * inch,
                       repeatRows=1,
                       hAlign='LEFT',
                       style=TableStyle([('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                                         ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                                         ('BACKGROUND', (0, 0), (-1, 0), colors.lightblue),
                                         ('VALIGN', (0, 0), (-1, -1), 'TOP')])))

    # Generate target table
    if 'targets' in fields:
        target_header = [P('<b>Target Dose</b>', s)]
        for p in fields['plans']:
            target_header.append(P('<b>{}</b>'.format(p.replace('_R0A0', '_RXAX')), s))

        if len(fields['plans']) > 1:
            target_header.append(P('<b>Composite</b>', s))

        targets = [target_header]
        for t in fields['targets'].keys():
            if fields['targets'][t]['use']:
                targets.append([P(t, s)])
                c = 0
                for n in range(len(fields['plans'])):
                    if len(fields['targets'][t]['dose']) > n and fields['targets'][t]['dose'][n] > 0:
                        targets[-1].append(P('{} Gy @ {} Gy/fx'.format(fields['targets'][t]['dose'][n],
                                                                       fields['targets'][t]['dose'][n] /
                                                                       fields['fractions'][n]), s))
                        c += fields['targets'][t]['dose'][n]

                    else:
                        targets[-1].append(P(' ', s))

                if len(fields['plans']) > 1:
                    targets[-1].append(P('{} Gy'.format(c), s))

        story.append(Table(data=targets,
                           colWidths=[1.5 * inch] + [width] * (len(targets[0]) - 1),
                           spaceAfter=0.25 * inch,
                           repeatRows=1,
                           hAlign='LEFT',
                           style=TableStyle([('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                                             ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                                             ('BACKGROUND', (0, 0), (-1, 0), colors.lightblue),
                                             ('VALIGN', (0, 0), (-1, -1), 'TOP')])))

    # Generate goals table
    goals_header = [P('<b>Clinical Goals</b>', s)]
    if len(fields['plans']) == 1:
        goals_header.append(P('<b>{}</b>'.format(fields['plans'][0].replace('_R0A0', '_RXAX')), s))

    else:
        goals_header.append(P('<b>Composite</b>', s))

    goals_header.append(P('<b>Priority</b>', s))
    goals_dict = {}
    c = 0
    for f in plan.TreatmentCourse.EvaluationSetup.EvaluationFunctions:
        try:
            c += 1
            if f.PlanningGoal.Priority < priority:
                goal = Goals.print_goal(f, 'eval')
                if goal != '':
                    if '{}{}'.format(f.PlanningGoal.Priority, f.ForRegionOfInterest.Name) in goals_dict:
                        goals_dict['{}{}'.format(f.PlanningGoal.Priority,
                                                 f.ForRegionOfInterest.Name)][1] += '<br/>' + goal

                    else:
                        goals_dict['{}{}'.format(f.PlanningGoal.Priority, f.ForRegionOfInterest.Name)] = \
                            [f.ForRegionOfInterest.Name, goal, f.PlanningGoal.Priority]

                else:
                    logging.warning('Unrecognized type for clinical goal {}'.format(c))

        except Exception:
            logging.warning('An error occurred adding clinical goal {}'.format(c))

    goals = [goals_header]
    oars = []
    for k in sorted(goals_dict.keys()):
        goals.append([P(goals_dict[k][0], s), P(goals_dict[k][1], s), P('{}'.format(goals_dict[k][2]), s)])
        if len(oars) < 5 and ('targets' not in fields or goals_dict[k][0] not in fields['targets']):
            oars.append(goals_dict[k][0])

    story.append(Table(data=goals,
                       colWidths=[1.5 * inch + width * (len(targets[0]) - 2)] + [width] + [0.75 * inch],
                       spaceAfter=0.25 * inch,
                       repeatRows=1,
                       hAlign='LEFT',
                       style=TableStyle([('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                                         ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                                         ('BACKGROUND', (0, 0), (-1, 0), colors.lightblue),
                                         ('VALIGN', (0, 0), (-1, -1), 'TOP')])))

    # Add billing justification
    modality = '3D'
    for b in plan.BeamSets:
        if b.Modality == 'Photons' and b.PlanGenerationTechnique == 'Imrt':
            modality = 'IMRT'
            break

    justification = 'To avoid complication-inducing doses to the '
    if len(oars) > 1:
        justification += '{} and {}'.format(', '.join(oars[0:-1]), oars[-1])
    elif len(oars) > 0:
        justification += oars[0]
    else:
        justification = 'To avoid excessive dose heterogeneity within the target'

    story.append(Table(data=[[P('<b>Date of Service: </b>', s), P(time.strftime('%m/%d/%Y %I:%M %p',
                                                                                time.localtime()), s)],
                             [P('<b>Reason for {}: </b>'.format(modality), s), P(justification, s)]],
                       colWidths=[1.5 * inch, 5 * inch],
                       spaceAfter=0.25 * inch,
                       hAlign='LEFT',
                       style=TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP')])))

    # Add plan options
    if 'options' in fields:
        options = []
        for o in sorted(fields['options'].iterkeys()):
            if fields['options'][o]:
                options.append([P('[X]', s), P(o, s)])

            else:
                options.append([P('[&nbsp;&nbsp;]', s), P(o, s)])

        if len(options) > 0:
            options[0].insert(0, P('<b>Plan Options:</b>', s))
            for i in range(1, len(options)):
                options[i].insert(0, P('', s))

        story.append(Table(data=options,
                           colWidths=[1.5 * inch, 0.35 * inch, 4.65 * inch],
                           spaceAfter=0.25 * inch,
                           hAlign='LEFT',
                           style=TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP')])))

    # Add comments
    if 'comments' in fields and fields['comments'].strip() != '':
        story.append(Table(data=[[P('<b>Comments:</b>', s), P(fields['comments'].replace('\n', '<br/>'), s)]],
                           colWidths=[1.5 * inch, 5 * inch],
                           spaceAfter=0.25 * inch,
                           hAlign='LEFT',
                           style=TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP')])))

    # Finish up
    doc.build(story)
    logging.debug('WriteTpo.pdf() completed successfully in {:.3f} seconds'.format(time.time() - tic))
    return filename
Exemplo n.º 29
0
def creditsects(form, elev, classe):
    """renvoie les crédits ects pdf de l'élève elev, ou si elev vaut None renvoie les crédits ects pdf de toute la classe en un seul fichier"""
    datedujour = form.cleaned_data['date'].strftime('%d/%m/%Y')
    filiere, annee = form.cleaned_data['classe'].split("_")
    signataire = form.cleaned_data['signature']
    etoile = form.cleaned_data['etoile']
    tree = etree.parse(join(RESOURCES_ROOT, 'classes.xml')).getroot()
    classexml = tree.findall("classe[@nom='{}'][@annee='{}']".format(
        filiere, annee)).pop()
    domaine = classexml.get("domaine")
    branche = classexml.get("type").lower()
    precision = classexml.get("precision")
    signature = False
    if 'tampon' in form.cleaned_data:
        signature = form.cleaned_data['tampon']
    LIST_NOTES = "ABCDEF"
    response = HttpResponse(content_type='application/pdf')
    if elev is None:
        eleves = Eleve.objects.filter(classe=classe).order_by(
            'user__last_name', 'user__first_name').select_related('user')
        nomfichier = "ECTS_{}.pdf".format(unidecode(classe.nom)).replace(
            " ", "-").replace('*', 'etoile')
        credits = NoteECTS.objects.credits(classe)[0]
    else:
        eleves = [elev]
        credits = [False]
        nomfichier = unidecode("ECTS_{}_{}_{}.pdf".format(
            classe.nom.upper(), elev.user.first_name,
            elev.user.last_name.upper())).replace(" ", "-")
    response['Content-Disposition'] = "attachment; filename={}".format(
        nomfichier)
    pdf = easyPdf()
    cm = pdf.format[0] / 21
    pdf.marge_x = cm  # 1cm de marge gauche/droite
    pdf.marge_y = 1.5 * cm  # 1,5cm de marge haut/bas
    I = Image(join(RESOURCES_ROOT, 'marianne.jpg'))
    I.drawHeight = 1.8 * cm
    I.drawWidth = 3 * cm
    if signature and signataire == 'Proviseur':
        try:
            I2 = Image(join(RESOURCES_ROOT, 'proviseur.png'))
        except Exception:
            try:
                I2 = Image(join(RESOURCES_ROOT, 'proviseur.png'))
            except Exception:
                I2 = False
    elif signature and signataire == 'Proviseur adjoint':
        try:
            I2 = Image(join(RESOURCES_ROOT, 'proviseuradjoint.png'))
        except Exception:
            try:
                I2 = Image(join(RESOURCES_ROOT, 'proviseuradjoint.png'))
            except Exception:
                I2 = False
    else:
        I2 = False
    if I2:
        I2.drawHeight = 3 * cm
        I2.drawWidth = 3 * cm
    newpage = False
    style = ParagraphStyle(name='normal', fontSize=9, leading=11, spaceAfter=5)
    styleResume = ParagraphStyle(name='resume',
                                 fontSize=9,
                                 leading=11,
                                 spaceAfter=0)
    styleTitre = ParagraphStyle(name='titre',
                                fontSize=12,
                                leading=13,
                                fontName="Helvetica-Bold",
                                borderColor='black',
                                borderPadding=(0, 0, 2, 0),
                                borderWidth=1,
                                backColor='#DDDDDD',
                                spaceAfter=2)
    data1 = [["A", "Très Bien", "C", "Assez Bien", "E", "Passable"],
             ["B", "Bien", "D", "Convenable", "F", "Insuffisant"]]
    LIST_STYLE1 = TableStyle([('GRID', (0, 0), (-1, -1), .2, (0, 0, 0)),
                              ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                              ('ALIGN', (0, 0), (-1, -1), 'CENTRE'),
                              ('FACE', (0, 0), (-1, -1), 'Helvetica'),
                              ('SIZE', (0, 0), (-1, -1), 8),
                              ('BACKGROUND', (0, 0), (-1, -1), (.9, .9, .9))])
    t1 = Table(data1,
               colWidths=[.8 * cm, 2 * cm, .8 * cm, 2 * cm, .8 * cm, 2 * cm],
               rowHeights=[12] * 2)
    t1.setStyle(LIST_STYLE1)
    data2 = [["8","D","","Université","",""],["7","D","","Université","",""],["6","D","","Université","",""],\
      ["5","M","","Université ou grande école","",""],["4","M","","Université ou grande école","",""],["3","L","ATS","Université ou grande école","",""],\
      ["2","L","STS-IUT","","Université","CPGE"],["1","L","STS-IUT","","Université","CPGE"],["0","Bac","Enseignement secondaire","","",""]]
    LIST_STYLE2 = TableStyle([
        ('GRID', (0, 0), (1, 4), .8, (0, 0, 0)),
        ('GRID', (3, 0), (5, 4), .8, (0, 0, 0)),
        ('GRID', (0, 5), (5, 8), .8, (0, 0, 0)),
        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ('ALIGN', (0, 0), (-1, -1), 'CENTRE'),
        ('FACE', (0, 0), (-1, -1), 'Helvetica-Bold'),
        ('SIZE', (0, 0), (-1, -1), 8),
        ('BACKGROUND', (0, 0), (-1, -1), (1, 1, 1)), ('SPAN', (3, 0), (5, 0)),
        ('SPAN', (3, 1), (5, 1)), ('SPAN', (3, 2), (5, 2)),
        ('SPAN', (3, 3), (5, 3)), ('SPAN', (3, 4), (5, 4)),
        ('SPAN', (3, 5), (5, 5)), ('SPAN', (2, 6), (3, 6)),
        ('SPAN', (2, 7), (3, 7)), ('SPAN', (2, 8), (5, 8)),
        ('BACKGROUND', (3, 0), (5, 2), '#FABF8F'),
        ('BACKGROUND', (3, 3), (5, 4), '#FBD4B4'),
        ('BACKGROUND', (2, 5), (2, 5), '#76923C'),
        ('BACKGROUND', (3, 5), (5, 5), '#FDE9D9'),
        ('BACKGROUND', (4, 6), (4, 7), '#FDE9D9'),
        ('BACKGROUND', (2, 6), (3, 7), '#D6E3BC'),
        ('BACKGROUND', (5, 6), (5, 7), '#FF9900')
    ])
    t2 = Table(
        data2,
        colWidths=[.84 * cm, .91 * cm, .75 * cm, 1.4 * cm, 2.5 * cm, 2.5 * cm],
        rowHeights=[.8 * cm] * 9)
    t2.setStyle(LIST_STYLE2)
    texte = "1. Information sur l'étudiant"
    p1 = Paragraph(texte, styleTitre)
    texte = "2. Information sur la formation"
    p3 = Paragraph(texte, styleTitre)
    texte = "3. Information sur le niveau de la formation"
    p5 = Paragraph(texte, styleTitre)
    texte = """<b><i>3.1. Niveau de la formation:</i></b><br/>
	Située au sein des études menant au grade de licence.<br/>
	Niveau bac + 2 / 120 crédits ECTS<br/>
	<b><i>3.2. Durée officielle du programme de formation:</i></b><br/>
	La durée du programme est de 2 ans.<br/>
	<b><i>3.3. Conditions d’accès:</i></b><br/>
	Entrée sélective après le baccalauréat s’effectuant dans le cadre d’une procédure nationale d’admission.<br/>
	Cf: <a href="http://www.admission-postbac.fr" color="blue">http://www.admission-postbac.fr</a>"""
    p6 = Paragraph(texte, style)
    texte = """4. Information sur les contenus et les résultats obtenus"""
    p7 = Paragraph(texte, styleTitre)
    texte = """<b><i>4.1. Organisation des études:</i></b><br/>
	Plein temps, contrôle continu écrit et oral<br/>
	<b><i>4.2. Exigences du programme:</i></b><br/>
	La formation dispensée a pour objet de donner aux étudiants une compréhension approfondie des disciplines enseignées et une appréhension de leurs caractéristiques générales. Elle prend en compte leurs évolutions, leurs applications et la préparation à des démarches de recherche.
	Elle est définie par des programmes nationaux.<br/>
	<b><i>4.3. Précisions sur le programme:</i></b><br/>
	Voir relevé au verso et catalogue de cours<br/>
	<b><i>4.4. Échelle d’évaluation:</i></b><br/>
	L’évaluation prend en compte l’ensemble des travaux des étudiants. La qualité du travail, des résultats obtenus et des compétences acquises est exprimée par une mention conformément au tableau ci-dessous."""
    p8 = Paragraph(texte, styleResume)
    texte = """<b><i>4.5. Classification de la formation:</i></b><br/>
	Une mention globale, portant sur l’ensemble du parcours et s’exprimant dans la même échelle qu’en 4.4 figure à la fin du relevé."""
    p9 = Paragraph(texte, style)
    texte = "5. Information sur la fonction de la qualification"
    p10 = Paragraph(texte, styleTitre)
    texte = """<b><i>5.1. Accès à un niveau d’études supérieur:</i></b><br/>
	Accès par concours aux grandes écoles.<br/>
	Accès, par validation de parcours, à tout type d’établissement d’enseignement supérieur.<br/>
	<b><i>5.2. Statut  professionnel (si applicable):</i></b><br/>
	Sans objet"""
    p11 = Paragraph(texte, style)
    texte = "6. Informations complémentaires"
    p12 = Paragraph(texte, styleTitre)
    texte = """<b><i>6.1. Informations complémentaires:</i></b><br/>
	Catalogue des cours et arrêtés ministériels définissant les programmes consultables sur :<br/>
	<a href="http://www.enseignementsup-recherche.gouv.fr/" color="blue">http://www.enseignementsup-recherche.gouv.fr/</a><br/>
	<b><i>6.2. Autres sources d’information:</i></b><br/>
	Pour toute information sur le dispositif CPGE consulter :<br/>
	<a href="http://www.enseignementsup-recherche.gouv.fr/" color="blue">http://www.enseignementsup-recherche.gouv.fr/</a>"""
    p13 = Paragraph(texte, style)
    texte = "7. Certification de l’attestation"
    p14 = Paragraph(texte, styleTitre)
    texte = "8. Informations sur le système national d’enseignement supérieur"
    p16 = Paragraph(texte, styleTitre)
    p17 = Paragraph("<br/> <br/>", style)
    for eleve, credit in zip(eleves, credits):
        if elev or credit and credit['ddn'] and credit['ine'] and credit[
                'sem1'] == 30 and credit[
                    'sem2'] == 30:  # si l'élève a bien toutes les infos/crédits
            if newpage:  # si ce n'est pas la première page, on change de page
                pdf.showPage()
            pdf.y = pdf.format[1] - pdf.marge_y - 1.8 * cm
            I.drawOn(pdf, 9 * cm, pdf.y)
            pdf.y -= 10
            pdf.setFont("Times-Roman", 7)
            pdf.drawCentredString(10.5 * cm, pdf.y,
                                  "MINISTÈRE DE L'ÉDUCATION NATIONALE")
            pdf.y -= 8
            pdf.drawCentredString(
                10.5 * cm, pdf.y,
                "DE l'ENSEIGNEMENT SUPÉRIEUR ET DE LA RECHERCHE")
            pdf.y -= 12
            pdf.setFont("Helvetica-Bold", 11)
            pdf.drawCentredString(10.5 * cm, pdf.y,
                                  "CLASSES PRÉPARATOIRES AUX GRANDES ÉCOLES")
            pdf.y -= 12
            pdf.setFont("Helvetica", 11)
            pdf.drawCentredString(10.5 * cm, pdf.y,
                                  "ANNEXE DESCRIPTIVE DE LA FORMATION")
            story = [p1]
            texte = "<b><i>1.1. Nom:</i></b> {}<br/><b><i>1.2. Prénom:</i></b> {}<br/><b><i>1.3. Date de Naissance:</i></b> {}<br/><b><i>1.4. Lieu de Naissance:</i></b> {}<br/><b><i>1.5. N° INE:</i></b> {}".format(
                eleve.user.last_name.upper(), eleve.user.first_name.title(),
                "" if not eleve.ddn else eleve.ddn.strftime('%d/%m/%Y'),
                "" if not eleve.ldn else eleve.ldn.title(), eleve.ine)
            p2 = Paragraph(texte, style)
            story.extend([p2, p3])
            texte = """<b><i>2.1. Nom de la formation:</i></b><br/>
			Classe préparatoire {} {} {}<br/>
			<b><i>2.2. Principaux domaines d’étude:</i></b><br/>
			{}<br/>
			<b><i>2.3. Nom et statut de l’institution gérant la formation:</i></b><br/>
			Ministère de l’enseignement supérieur et de la recherche
			Classes préparatoires aux grandes écoles<br/>
			<b><i>2.4. Nom et statut de l’établissement dispensant la formation:</i></b><br/>
			{}<br/>
			<b><i>2.5. Langue de formation:</i></b> français""".format(
                branche, filiere, "(" + precision + ")" if precision else "",
                domaine,
                Config.objects.get_config().nom_adresse_etablissement.replace(
                    "\n",
                    "<br/>").replace("\r",
                                     "<br/>").replace("<br/><br/>", "<br/>"))
            p4 = Paragraph(texte, style)
            story.extend([p4, p5, p6, p7, p8, t1, p9])
            fl = Frame(cm,
                       1.5 * cm,
                       9 * cm,
                       23 * cm,
                       showBoundary=0,
                       leftPadding=0,
                       rightPadding=0,
                       topPadding=0,
                       bottomPadding=0)
            fl.addFromList(story, pdf)
            story = [p10, p11, p12, p13, p14]
            texte = """<b><i>7.1. Date:</i></b> {}<br/>
			<b><i>7.2. Signature:</i></b><br/><br/><br/><br/>
			<b><i>7.3. Fonction:</i></b> {}<br/>
			<b><i>7.4. Tampon ou cachet officiel:</i></b><br/><br/><br/><br/><br/><br/>""".format(
                datedujour, signataire)
            p15 = Paragraph(texte, style)
            story.extend([p15, p16, p17, t2])
            fr = Frame(11 * cm,
                       1.5 * cm,
                       9 * cm,
                       23 * cm,
                       showBoundary=0,
                       leftPadding=0,
                       rightPadding=0,
                       topPadding=0,
                       bottomPadding=0)
            fr.addFromList(story, pdf)
            if I2:
                I2.drawOn(pdf, 16.2 * cm, 13.2 * cm)
            pdf.showPage()
            pdf.y = pdf.format[1] - pdf.marge_y - 12
            pdf.setFont('Helvetica-Bold', 12)
            pdf.drawCentredString(
                10.5 * cm, pdf.y, "RELEVÉ DE RÉSULTATS (classe {})".format(
                    filiere + ('*' if etoile and classe.annee == 2 else '')))
            sem1, sem2 = NoteECTS.objects.notePDF(eleve)
            data = [["ENSEIGNEMENTS", "Crédits ECTS", "Mention"],
                    ["Premier semestre", "", ""]]
            sp = 0  # variable qui va contenir la somme pondérée des notes en vue du calcul de la mention globale
            coeff = 0  # somme des coeffs pour vérifier si on en a 60 au total
            for note in sem1:
                data.append([
                    note[0] + ("" if not note[1] else " ({})".format(note[1])),
                    note[2], LIST_NOTES[note[4]]
                ])
                sp += note[2] * note[4]
                if note[4] != 5:
                    coeff += note[2]
            data.append(["Deuxième semestre", "", ""])
            for note in sem2:
                data.append([
                    note[0] + ("" if not note[1] else " ({})".format(note[1])),
                    note[3], LIST_NOTES[note[4]]
                ])
                sp += note[3] * note[4]
                if note[4] != 5:
                    coeff += note[3]
            LIST_STYLE = TableStyle([
                ('GRID', (0, 0), (-1, -1), .8, (0, 0, 0)),
                ('SPAN', (0, 1), (2, 1)),
                ('SPAN', (0, 2 + len(sem1)), (2, 2 + len(sem1))),
                ('FACE', (0, 0), (-1, -1), 'Helvetica-Bold'),
                ('SIZE', (0, 0), (-1, -1), 8), ('SIZE', (0, 1), (2, 1), 9),
                ('SIZE', (0, 2 + len(sem1)), (2, 2 + len(sem1)), 9),
                ('SIZE', (0, 0), (2, 0), 10),
                ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                ('ALIGN', (0, 2), (0, -1), 'LEFT'),
                ('ALIGN', (1, 0), (2, -1), 'CENTRE'),
                ('ALIGN', (0, 0), (2, 1), 'CENTRE'),
                ('ALIGN', (0, 2 + len(sem1)), (2, 2 + len(sem1)), 'CENTRE'),
                ('BACKGROUND', (0, 1), (2, 1), '#DDDDDD'),
                ('BACKGROUND', (0, 2 + len(sem1)), (2, 2 + len(sem1)),
                 '#DDDDDD')
            ])
            t = Table(data,
                      colWidths=[13 * cm, 2.8 * cm, 2.5 * cm],
                      rowHeights=[.8 * cm] * (3 + len(sem1) + len(sem2)))
            t.setStyle(LIST_STYLE)
            w, h = t.wrapOn(pdf, 0, 0)
            pdf.y -= h + 5
            pdf.x = (pdf.format[0] - w) / 2
            t.drawOn(pdf, pdf.x, pdf.y)
            pdf.y -= 20
            pdf.setFont('Helvetica-Bold', 10)
            if coeff == 60:
                pdf.drawString(
                    pdf.x, pdf.y, "Mention globale: {}".format(
                        LIST_NOTES[int(sp / 60 + .5)]))
            else:
                pdf.setFillColor((1, 0, 0))
                pdf.drawString(
                    pdf.x, pdf.y,
                    "Pas de mention, il manque {} crédits".format(60 - coeff))
                pdf.setFillColor((0, 0, 0))
            pdf.drawRightString(pdf.format[0] - pdf.x - 15, pdf.y,
                                "Cachet et signature")
            pdf.y -= 3.2 * cm
            if I2:
                I2.drawOn(pdf, pdf.format[0] - 2 * pdf.marge_x - 3 * cm, pdf.y)
            newpage = True
    pdf.save()
    fichier = pdf.buffer.getvalue()
    pdf.buffer.close()
    response.write(fichier)
    return response
Exemplo n.º 30
0
def createPDF(datasetID):
    """
    Get the ID of the dataset protocol and creates a PDF of this protocol using the reportlab tools
    :param datasetID:
    :return: a HTTPResponse PDF object
    """

    # Get all the information of this protocol
    basicInfo = BasicDataset.objects.get(id=datasetID)
    partnerInfo = Partner.objects.filter(dataset_id=datasetID)
    reqInfo = DataReq.objects.filter(dataset_id=datasetID).order_by('taskNr')
    stepInfo = ExpStep.objects.filter(dataset_id=datasetID).order_by('taskNr')
    reportingInfo = Reporting.objects.filter(dataset_id=datasetID).order_by('taskNr')

    # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=' + basicInfo.shortname + '.pdf'

    styles = {
        'default': ParagraphStyle(
            'default',
            fontName='Times-Roman',
            fontSize=10,
            leading=11,
            leftIndent=0,
            rightIndent=0,
            firstLineIndent=0,
            spaceBefore=0,
            spaceAfter=0,
            textColor= black,
            backColor=None,
            wordWrap=None,
            borderWidth= 0,
            borderPadding= 0,
            borderColor= None,
            borderRadius= None,
            allowWidows= 1,
            allowOrphans= 0,
            endDots=None,
            splitLongWords=1,
        ),

    }

    styles['title1'] = ParagraphStyle(
        'title1',
        parent=styles['default'],
        fontName='Helvetica-Bold',
        fontSize=24,
        leading=30,
        alignment=TA_CENTER,
        textColor=black,
    )

    styles['title2'] = ParagraphStyle(
        'title2',
        parent=styles['default'],
        fontName='Helvetica',
        fontSize=14,
        leading=18,
        leftIndent=5,
        alignment=TA_LEFT,
        textColor=black,
        spaceBefore = 0,
        borderRadius = None,
        firstLineIndent = 0,
        underlineProportion = 0.0,
        rightIndent = 0,
        wordWrap = None,
        allowWidows = 1,
        backColor = Color(.9,.9,.9),
        justifyLastLine = 0,
        textTransform = None,
        justifyBreaks = 0,
        spaceShrinkage = 0.05,
        splitLongWords = 1,
        bulletFontSize = 10,
        borderWidth = 1,
        borderPadding = 2,
        endDots = None,
        spaceAfter = 6,

    )

    styles['label'] = ParagraphStyle(
        'label',
        parent=styles['default'],
        fontName='Times-Bold',
    )

    buffer = BytesIO()
    doc = BaseDocTemplate(buffer)

    doc.addPageTemplates(
        [
            PageTemplate(
                frames=[
                    Frame(
                        doc.leftMargin,
                        doc.bottomMargin,
                        doc.width,
                        doc.height,
                        id=None
                    ),
                ]
            ),
        ]
    )


    # container for the 'Flowable' objects
    story = []

    scriptDir = os.path.dirname(__file__)
    im = Image(os.path.join(scriptDir, "static/img/sologo_new_cropped.png"), width=2.6*cm, height=2*cm)
    im.hAlign = 'RIGHT'

    data = [[im, Paragraph('{}'.format(basicInfo.shortname), styles['title1'])]]

    t=Table(data, hAlign='LEFT', colWidths=[2 * cm, 14 * cm])
    t.setStyle(TableStyle([('VALIGN',(0,0),(-1,-1),'TOP')]))
    story.append(t)
    story.append(Spacer(1, 16))


    story.append(Paragraph('Experiment Information', styles['title2']))
    data= [[Paragraph('Full experiment name:', styles['label']), Paragraph(basicInfo.title, styles['default'])],
           [Paragraph('Experiment Idea:', styles['label']), Paragraph(basicInfo.experimentIdea.replace('\n','<br />\n'), styles['default'])],
           [Paragraph('Hypothesis:', styles['label']), Paragraph(basicInfo.hypothesis.replace('\n','<br />\n'), styles['default'])],
           [Paragraph('Research objective:', styles['label']), Paragraph(basicInfo.researchObjective.replace('\n','<br />\n'), styles['default'])]]

    t=Table(data, hAlign='LEFT', colWidths=[4 * cm, 12 * cm])
    t.setStyle(TableStyle([('VALIGN',(0,0),(-1,-1),'TOP')]))
    story.append(t)
    story.append(Spacer(1, 24))


    # Partners
    story.append(Paragraph('Partners', styles['title2']))

    for partner in partnerInfo:

        partnerName = Paragraph('{}'.format(partner.name), styles['default'])
        if partner.lead == True:
            partnerName = Paragraph('{} (lead)'.format(partner.name), styles['default'])

        data = [[Paragraph('Name:', styles['label']), partnerName],
            [Paragraph('E-mail:', styles['label']), Paragraph(partner.email, styles['default'])],
           [Paragraph('Organisation:', styles['label']), Paragraph(partner.organisation, styles['default'])]]

        t=Table(data, hAlign='LEFT', colWidths=[4 * cm, 12 * cm])
        t.setStyle(TableStyle([('VALIGN',(0,0),(-1,-1),'TOP')]))
        story.append(t)
        story.append(Spacer(1, 16))

    story.append(Spacer(1, 24))

    story.append(Paragraph('A) Data & Method Preparation', styles['title2']))
    writeTasks(story, styles, reqInfo)
    story.append(Spacer(1, 24))

    story.append(Paragraph('B) Experiment Analysis Steps', styles['title2']))
    writeTasks(story, styles, stepInfo)
    story.append(Spacer(1, 24))

    story.append(Paragraph('C) Result Reporting', styles['title2']))
    writeTasks(story, styles, reportingInfo)

    # write the document to disk
    doc.build(story)

    pdf = buffer.getvalue()
    buffer.close()
    response.write(pdf)
    return response