Exemplo n.º 1
0
    def pdf_built(self, q1, q2, q3, q4, q5, q6, q7, q8, q9, q10, q11, q12, q13,
                  q14, user, rank):
        report = SimpleDocTemplate(
            "/home/kalinchenkomax/cs_alpha/customer_s/media/aer/aer.pdf",
            pageSize="A4")
        style = getSampleStyleSheet()
        today = date.today()

        AER = [
            Paragraph(f"AER {today}", style["Title"]),
            Paragraph(f"created by {rank} {user}"),
            Paragraph("What suppose to happen:", style["h2"]),
            Paragraph(q1, style["Normal"]),
            Paragraph("What did happen:", style["h2"]),
            Paragraph(q2, style["Normal"]),
            Paragraph("Sustainements:", style["h2"]),
            ListFlowable(
                [Paragraph(s) for s in [q3, q4, q5, q6, q7]],
                leftIndent=48,
            ),
            Paragraph("Improvements:", style["h2"]),
            ListFlowable(
                [Paragraph(s) for s in [q8, q9, q10, q11, q12]],
                leftIndent=48,
            ),
            Paragraph("Alibis:", style["h2"]),
            ListFlowable(
                [Paragraph(s) for s in [q13, q14]],
                leftIndent=48,
            ),
        ]

        report.build(AER)
Exemplo n.º 2
0
def list_flowable_squares():
    doc = SimpleDocTemplate("list_flowable_squares.pdf", pagesize=letter)
    styles = getSampleStyleSheet()
    normal = styles['Normal']
    story = []

    flowables = [
        Paragraph('Paragraph numero uno', normal),
        ListItem(Paragraph('Paragraph #2', normal), bulletColor="blue"),
        Paragraph('Paragraph #3', normal),
    ]

    flowables.append(
        ListFlowable([
            Paragraph("I'm a sublist item", normal),
            ListItem(Paragraph("I'm another sublist item", normal),
                     bulletColor='blue'),
            ListItem(Paragraph("I'm the last sublist item", normal),
                     bulletColor='red')
        ],
                     bulletType='bullet',
                     start='square'))

    lflow = ListFlowable(flowables, bulletType='I')
    story.append(lflow)

    doc.build(story)
Exemplo n.º 3
0
    def test1(self):
        styleSheet = getSampleStyleSheet()
        doc = SimpleDocTemplate(outputfile('test_platypus_lists1.pdf'))
        story = []
        sty = [
            ('GRID', (0, 0), (-1, -1), 1, colors.green),
            ('BOX', (0, 0), (-1, -1), 2, colors.red),
        ]
        normal = styleSheet['BodyText']
        lpSty = normal.clone('lpSty', spaceAfter=18)
        data = [[
            str(i + 1),
            Paragraph("xx " * (i % 10), styleSheet["BodyText"]),
            Paragraph(("blah " * (i % 40)), normal)
        ] for i in xrange(5)]
        data1 = [[
            str(i + 1),
            Paragraph(["zz ", "yy "][i] * (i + 3), styleSheet["BodyText"]),
            Paragraph(("duh  " * (i + 3)), normal)
        ] for i in xrange(2)]
        OL = ListFlowable([
            Paragraph("A table with 5 rows", lpSty),
            Table(data, style=sty, colWidths=[50, 100, 200]),
            ListItem(
                Paragraph("A sublist", normal),
                value=7,
            ),
            ListFlowable(
                [
                    Paragraph("Another table with 3 rows", normal),
                    Table(data[:3], style=sty, colWidths=[60, 90, 180]),
                    Paragraph(TEXTS[0], normal),
                ],
                bulletType='i',
            ),
            Paragraph("An unordered sublist", normal),
            ListFlowable(
                [
                    Paragraph("A table with 2 rows", normal),
                    ListItem(Table(data1, style=sty, colWidths=[60, 90, 180]),
                             bulletColor='green'),
                    ListItem(Paragraph(TEXTS[2], normal),
                             bulletColor='red',
                             value='square')
                ],
                bulletType='bullet',
                start='circle',
            ),
            Paragraph(TEXTS[1], normal),
        ])

        story.append(OL)
        doc.build(story)
Exemplo n.º 4
0
def makeList(context, items, numbered=False, start=1, itemSpace=6):
    kwargs = {
        "bulletDedent": 15,
        "leftIndent": 30,
        "spaceBefore": 0,
        "spaceAfter": 0,
        "bulletFontName": context.styleSheet["listBulletFontName"],
        "bulletFontSize": context.styleSheet["listBulletFontSize"],
        "start": start
    }

    if numbered:
        kwargs.update({"bulletFormat": context.styleSheet["listNumberFormat"]})

    else:
        kwargs.update({
            "value": "bullet",
            "bulletType": "bullet",
            "start": context.styleSheet["listBullet"],
            "bulletFontSize": 8,
            "bulletOffsetY": -1
        })

    context.lastListCounter = start + len(items)

    content = []
    content.append(
        ListFlowable([[item, Spacer(1, itemSpace)]
                      for item in items[:-1]] + [items[-1]], **kwargs))

    return content
Exemplo n.º 5
0
 def format_answer_list(self, answers, keep_together=True):
     answers = ListFlowable(answers,
                            bulletType='bullet',
                            style=self.answers_list_style)
     if keep_together:
         answers = KeepTogether(answers)
     return [answers, Spacer(1, 16)]
Exemplo n.º 6
0
    def get_metadata_page(self, recipient):
        MetadataPage = []
        MetadataPage.append(
            Paragraph(self.report_title, self.report_title_style))

        MetadataPage.append(Paragraph("Overview", self.section_title_style))

        overview_body = "Submitted by: {0}<br/>".format(
            self.get_user_identifier(self.user))
        if recipient:
            overview_body = overview_body + "Submitted on:  {0}<br/>".format(
                localtime(
                    self.report.submitted_to_school).strftime(date_format))
        overview_body = overview_body + \
            """Record Created: {0}
            Last Edited: {1}""".format(localtime(self.report.added).strftime(date_format),
                                       localtime(self.report.last_edited).strftime(date_format)
                                       if self.report.last_edited else "<i>Not edited</i>")
        overview_body = overview_body.replace('\n', '<br />\n')

        MetadataPage.append(Paragraph(overview_body, self.body_style))

        if recipient:
            MetadataPage.append(
                Paragraph("Contact Preferences", self.section_title_style))

            contact_body = """Name: {0}
            Phone: {1}
            Voicemail preferences: {2}
            Email: {3}
            Notes on preferred contact time of day, gender of admin, etc.:""".format(
                self.report.contact_name or "<i>None provided</i>",
                self.report.contact_phone, self.report.contact_voicemail
                or "None provided",
                self.report.contact_email).replace('\n', '<br />\n')

            MetadataPage.append(Paragraph(contact_body, self.body_style))
            MetadataPage.append(
                Paragraph(self.report.contact_notes or "None provided",
                          self.notes_style))

        MetadataPage.append(Paragraph("Key", self.section_title_style))

        key = ListFlowable([
            ListItem(Paragraph("Unselected option", self.answers_style),
                     value=self.unselected,
                     leftIndent=45),
            ListItem(Paragraph("<b>Selected option</b>", self.answers_style),
                     value=self.selected,
                     leftIndent=45),
            ListItem(Paragraph("Free text response", self.answers_style),
                     value=self.free_text,
                     leftIndent=45)
        ],
                           bulletType='bullet',
                           style=self.answers_list_style)
        MetadataPage.append(key)

        MetadataPage.append(PageBreak())
        return MetadataPage
Exemplo n.º 7
0
def add_definition(story):
    story.append(
        Paragraph(
            '<para><br/><br/>We introduce some terms for avoiding confusions.</para>',
            normalStyle))
    # title2 = title('Definition:', 2)
    # story.append(Paragraph(title2, normalStyle))
    delist = ListFlowable(
        [
            Paragraph(
                '<b>Explicit version declaration in Maven: </b>a library version is declared as a hard-coded value in version tag, e.g., &lt;version&gt;2.5&lt;/version&gt;.',
                normalStyle),
            Paragraph(
                '<b>Implicit version declaration in Maven: </b>a library version is declared as a referenced value in version tag through a declared property, e.g., &lt;version&gt;${guava.version}&lt;/version&gt;.',
                normalStyle),
            Paragraph(
                '<b>Inconsistent library: </b>a library whose multiple versions are used in multiple modules of a project; e.g., module A declares guava 2.5 but module B declares guava 2.6.',
                normalStyle),
            Paragraph(
                '<b>False consistent library: </b> a library that is used in multiple modules of a project with the same version declared separately; e.g., module A declares guava 2.5 explicitly and module B declares guava 2.5 explicitly. Therefore, such a consistency is likely to turn into inconsistency when there is an incomplete library update.',
                normalStyle),
            # Paragraph('<b>Property: </b>property tag in <font face="Times-Italic">pom</font>, <font face="Times-Italic">maven\'s</font> term for <font face="Times-Italic">variable</font>.',normalStyle),
        ],
        bulletType='bullet',
    )
    story.append(delist)
    story.append(Paragraph('<para><br/><br/></para>', normalStyle))
Exemplo n.º 8
0
 def add_list(self, items, list_style=UL):
     styles = getSampleStyleSheet()
     style = styles["Normal"]
     list_to_print = []
     for item in items:
         list_to_print.append(Paragraph(item, style))
     t = ListFlowable(list_to_print, bulletType='i')
     self.add(t)
def soil_section(rain_tot2, runoff_tot2, evap_tot2, rech_soil_tot2,
                 deficit_tot, soil_tdelta, soil_plot_path):

    soil_section = []

    #Set the style
    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY,
                              leading=24))

    #Add title
    title = 'Soil water budget'
    ptext = '<font size=24>%s</font>' % title
    soil_section.append(Paragraph(ptext, styles["Justify"]))

    #Add vertical space
    soil_section.append(Spacer(1, 30))

    #Add text
    ptext = '<font size=12>The soil water budget includes the following components:</font>'
    soil_section.append(Paragraph(ptext, styles["Justify"]))

    #Bullet list
    budget_components = ListFlowable([
        ListItem(Paragraph("rainfall (inflow term)", styles['Normal']),
                 value='circle'),
        ListItem(Paragraph("runoff (outflow term)", styles['Normal']),
                 value='circle'),
        ListItem(Paragraph("evapotranspiration (outflow term)",
                           styles['Normal']),
                 value='circle'),
        ListItem(Paragraph("percolation to the water table (outflow term)",
                           styles['Normal']),
                 value='circle')
    ],
                                     bulletType='bullet',
                                     start='circle')
    soil_section.append(budget_components)

    #Add vertical space
    soil_section.append(Spacer(1, 30))

    #Add text
    ptext = '<font size=12>According to model results, over the simulation period (%s days long), the total rainfall was %s mm.\
                            We can also estimate: %s mm of runoff, %s mm of evapotranspiration and %s mm of percolation to the water table.\
                            This results in a water deficit of %s mm.</font>' % (
        soil_tdelta, rain_tot2, runoff_tot2, evap_tot2, rech_soil_tot2,
        deficit_tot)
    soil_section.append(Paragraph(ptext, styles["Justify"]))

    #Add plot
    img = Image(soil_plot_path, 7 * inch, 5 * inch)
    soil_section.append(img)

    #Add vertical space
    soil_section.append(Spacer(1, 30))

    return soil_section
Exemplo n.º 10
0
 def separator(self):
     """question_set separator.
     """
     style = Style()
     return ListFlowable(
         [Paragraph(self._text_separator, style.title)],
         bulletType="bullet",
         start="",
     )
Exemplo n.º 11
0
def listify(input):
    listItems = []
    for item in input:
        listItem = ListItem(Paragraph((item), styleN),
                            leftIndent=35,
                            value='-')
        listItems.append(listItem)
    output = ListFlowable(listItems, bulletType='bullet')
    return output
Exemplo n.º 12
0
def create_list(canvas, starting_height, starting_x, max_width, list, style):
    bullet_list = []
    for item in list['data']:
        bullet_list.append(Paragraph(item, style=style))
    list = ListFlowable(bullet_list,
                        bulletType='bullet',
                        start='bulletchar',
                        bulletFontName='Times-Roman',
                        bulletFontSize=16,
                        style=list_style)

    w1, h1 = list.wrapOn(canvas, max_width, MAX_HEIGHT)
    if starting_height - h1 < 0:
        canvas.showPage()
        starting_height = TOP_PADDING

    list.drawOn(canvas, starting_x - w1, starting_height - h1)

    return starting_height - h1
Exemplo n.º 13
0
 def _build_in_progress_item(self):
     """Extend _doc with a list of two ListFlowable: an item container with
     zero or more sub item container and a separator."""
     question_set = ListFlowable(
         self._in_progress_item,
         bulletType=self.settings.top_item_bullet_type,
         start=self.settings.top_item_start,
     )
     self.settings.top_item_start += 1
     self._doc.extend([KeepTogether([question_set, self.separator])])
Exemplo n.º 14
0
def build_flowables(stylesheet):
    return [
        ListFlowable(
            [
                Paragraph('Apple', stylesheet['default']),
                Paragraph('Banana', stylesheet['default']),
                Paragraph('Orange', stylesheet['default']),
            ],
            bulletType='I'  # '1' (default) | 'i' | 'I' | 'a' | 'A'
        ),
    ]
Exemplo n.º 15
0
def build_flowables(stylesheet):
    return [
        Paragraph('Some text.', stylesheet['default']),
        ListFlowable(
            [
                Paragraph('Apple', stylesheet['default']),
                Paragraph('Banana', stylesheet['default']),
                Paragraph('Orange', stylesheet['default']),
            ],
            style=stylesheet['list_default'],
        ),
        Paragraph('More text.', stylesheet['default']),
        ListFlowable([
            Paragraph('Apple', stylesheet['default']),
            Paragraph('Banana', stylesheet['default']),
            Paragraph('Orange', stylesheet['default']),
        ],
                     style=stylesheet['list_special'],
                     start=5),
        Paragraph('Even more text.', stylesheet['default']),
    ]
 def add_terms(self, list):
     style = ParagraphStyle(
         name='Normal',
         fontName='Arabic',
         fontSize=8,
     )
     table = ListFlowable([
         ListItem(Paragraph(x, style), leftIndent=35, bulletColor='black')
         for x in list
     ],
                          bulletType='bullet')
     return table
Exemplo n.º 17
0
def handle_block(block):
    paragraphs = []

    for tag in block:
        if isinstance(tag, NavigableString):
            text = tag.strip()
            if text:
                paragraphs.append(Paragraph(text, styles['Normal']))
        elif tag.name in {'ul', 'ol'}:
            style = styles['Normal']
            if tag.name == 'ul':
                bullet = 'bullet'
            elif tag.name == 'ol':
                bullet = '1'

            paragraphs.append(
                ListFlowable(
                    [
                        ListItem(Paragraph(bullet_item.get_text(), style))
                        for bullet_item in tag.find_all('li')
                    ],
                    bulletType=bullet,
                ))
        elif tag.name in {'table'}:
            paragraphs.append(
                Table(
                    [[
                        Paragraph(cell.get_text(), styles['Normal'])
                        for cell in row.find_all({'td', 'th'})
                    ] for row in tag.find_all('tr')],
                    colWidths='*',
                    style=TableStyle([
                        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                        ('LINEABOVE', (0, 0), (-1, -1), 1, DARK_GREY),
                    ]),
                ))
        else:
            if tag.name in {'p'}:
                style = styles['Normal']
            elif tag.name == 'h2':
                style = styles['Heading2']
            elif tag.name == 'h3':
                style = styles['Heading3']
            elif tag.name == 'h4':
                style = styles['Heading4']
            elif tag.name == 'h5':
                style = styles['Heading5']

            text = tag.get_text()
            if text:
                paragraphs.append(Paragraph(text, style))
    return paragraphs
Exemplo n.º 18
0
def makeBulletList(list):
    bullets = ListFlowable(
        [
            ListItem(
                p_bullet(x),
                leftIndent=10, bulletColor='black', value='circle',
                bulletOffsetY=-2.88
            ) for x in list
        ],
        bulletType='bullet', bulletFontSize=3, leftIndent=5
    )

    return bullets
Exemplo n.º 19
0
    def bullet_list(self, body, level):
        items = []

        for text_line in body.split('<br/>'):
            try:
                bullet_text = ListItem(Paragraph(text_line,
                                                 self.style['bullet_list']),
                                       leftIndent=level * 35,
                                       value='bulletchar')
                items.append(bullet_text)
            except Exception as e:
                print('Error Creating PDF: ' + str(e))

        return ListFlowable(items, bulletType='bullet', start='bulletchar')
Exemplo n.º 20
0
    def body_story(self, team):
        def table_items():
            yield Paragraph(
                "Pertinence du sujet sélectionné",
                style=cell_body
            )
            yield Paragraph(
                "Qualité du travail de documentation",
                style=cell_body
            )
            yield Paragraph(
                "Qualité de la présentation",
                style=cell_body
            )
            yield Paragraph(
                "Expression orale",
                style=cell_body
            )
            yield Paragraph(
                "Réponse aux questions",
                style=cell_body
            )

        for _ in (
            Table(
                [
                    ['Numéro du jury', '']
                ],
                colWidths=[2 * self.H_UNIT] * 2,
                style=default_table_style + [
                    ('BACKGROUND', (0, 0), (0, 0), cell_bkgnd_color),
                    ('ALIGN', (0, 0), (0, 0), 'RIGHT')
                ]
            ),
            tables_spacer,
            Paragraph("Noter chaque point ci-dessous en utilisant le barême suivant :", style=cell_body),
            ListFlowable((
              Paragraph(e[1], style=cell_body) for e in EVALUATION_CHOICES
            ), bulletType='bullet', leftIndent=36, bulletDedent=15, spaceBefore=0.1 * inch, start='bulletchar'),
            tables_spacer,
            Table(
                [(_, '') for _ in table_items()],
                colWidths=[3 * self.H_UNIT, self.H_UNIT],
                style=default_table_style + [
                    ('FONTNAME', (0, 0), (-1, -1), 'Helvetica'),
                ]
            ),
        ):
            yield _
Exemplo n.º 21
0
 def _build_item(self, item) -> ListFlowable:
     """Build an item container.
     """
     style = Style(spaceAfter=self._space_text_image)
     space = Spacer(1, self._space_after_item)
     if item.image != Path("."):
         image = get_std_aspect_image(item.image, width=80)
         question = [
             Paragraph(item.text + NON_BREAK_SP, style.normal), image, space
         ]
     else:
         question = [Paragraph(item.text, style.normal), space]
     return ListFlowable(question,
                         leftIndent=0,
                         bulletType="bullet",
                         start="")
def list_flowable_demo():
    doc = SimpleDocTemplate("list_flowable_demo.pdf", pagesize=letter)
    styles = getSampleStyleSheet()
    normal = styles['Normal']
    story = []

    flowables = [
        Paragraph('Paragraph numero uno', normal),
        ListItem(Paragraph('Paragraph #2', normal),
                 bulletColor="blue",
                 value=5),
        Paragraph('Paragraph #3', normal),
    ]

    lflow = ListFlowable(flowables)
    story.append(lflow)

    doc.build(story)
Exemplo n.º 23
0
def build_content(stylesheet):

    data = get_data("pdf")
    # Add header image
    return [
        Image("TRLogo.jpg",
              width=5 * inch,
              height=3 * inch,
              kind='proportional'),
        Paragraph("Managed Data Service<br/>Data Point Definitions",
                  stylesheet['title']),
        Paragraph(
            "Release Version: %s%s%s%s" %
            ("2017.8", "<br/>", "Content Timestamp: ", str(ts)),
            stylesheet['alert']),
        PageBreak(),
        Paragraph(" ", stylesheet['spacer']),
        Paragraph("MDS Data Points", stylesheet['subheading']),
        Paragraph(REP_NOTES, stylesheet['default']),
        ListFlowable([
            Paragraph('Identifier: The unique identifier for the field.',
                      stylesheet['default']),
            Paragraph(
                'Module: Grouping of fields, "CLIENT DATA" represents data that can be sent to MDS.',
                stylesheet['default']),
            Paragraph(
                'V1 Only: If Yes, then the field is not available in Version 2.',
                stylesheet['default']),
            Paragraph(
                'XML Parent or Attribute Name: If all uppercase, then this is the '
                '//EntityAttributes/EntityAttribute/AttributeName text, '
                'otherwise it is the Parent Element Name.',
                stylesheet['default']),
            Paragraph('TBC: To Be Confirmed.', stylesheet['default']),
        ],
                     bulletType='bullet',
                     bulletFontSize=4,
                     leftIndent=10,
                     bulletOffsetY=-2,
                     start='circle'),
        Paragraph(" ", stylesheet['spacer']),
        Table(data, style=stylesheet['table'], repeatRows=1),
        Paragraph("End of Document", stylesheet['footer']),
    ]
Exemplo n.º 24
0
 def _build_item(self, item, **style_options: Any) -> ListFlowable:
     """Build an item container.
     """
     item_style = ParagraphStyle("Normal",
                                 spaceAfter=self.settings.space_text_image,
                                 **style_options)
     # style = Style(spaceAfter=self._space_text_image, **style_options)
     space = Spacer(1, self.settings.space_after_item)
     if item.image != Path("."):
         image = get_std_aspect_image(item.image, width=80)
         question = [
             Paragraph(item.text + NON_BREAK_SP, item_style),
             image,
             space,
         ]
     else:
         question = [Paragraph(item.text, item_style), space]
     return ListFlowable(question,
                         leftIndent=0,
                         bulletType="bullet",
                         start="")
def createBullet(c, text, x, y, font, size, indent=0):
    """ Function to create a Bullet Point """
    styles = getSampleStyleSheet()
    style = styles["Normal"]
    if indent != 0:
        t = ListFlowable([Paragraph(text, style)],
                         bulletType='bullet',
                         start='circle',
                         leftIndent=indent,
                         fontName=font,
                         bulletFontName="Helvetica",
                         bulletFontSize=8,
                         bulletAnchor="Start")
    else:
        t = ListFlowable([Paragraph(text, style)],
                         bulletType='bullet',
                         start='circle',
                         fontName=font,
                         bulletFontName="Helvetica",
                         bulletFontSize=8,
                         bulletAnchor="Start")
    t.wrapOn(c, 480, 20)
    t.drawOn(c, x, y)
    return y - size
Exemplo n.º 26
0
def render_workout_day(day, nr_of_weeks=7, images=False, comments=False, only_table=False):
    """
    Render a table with reportlab with the contents of the training day

    :param day: a workout day object
    :param nr_of_weeks: the numbrer of weeks to render, default is 7
    :param images: boolean indicating whether to also draw exercise images
           in the PDF (actually only the main image)
    :param comments: boolean indicathing whether the exercise comments will
           be rendered as well
    :param only_table: boolean indicating whether to draw a table with space
           for weight logs or just a list of the exercises
    """

    # If rendering only the table, reset the nr of weeks, since these columns
    # will not be rendered anyway.
    if only_table:
        nr_of_weeks = 0

    data = []

    # Init some counters and markers, this will be used after the iteration to
    # set different borders and colours
    day_markers = []
    group_exercise_marker = {}

    set_count = 1
    day_markers.append(len(data))

    p = Paragraph('<para align="center">%(days)s: %(description)s</para>' %
                  {'days': day['days_of_week']['text'],
                   'description': day['obj'].description},
                  styleSheet["SubHeader"])

    data.append([p])

    # Note: the _('Date') will be on the 3rd cell, but since we make a span
    #       over 3 cells, the value has to be on the 1st one
    data.append([_('Date') + ' ', '', ''] + [''] * nr_of_weeks)
    data.append([_('Nr.'), _('Exercise'), _('Reps')] + [_('Weight')] * nr_of_weeks)

    # Sets
    exercise_start = len(data)
    for set in day['set_list']:
        group_exercise_marker[set['obj'].id] = {'start': len(data), 'end': len(data)}

        # Exercises
        for exercise in set['exercise_list']:
            group_exercise_marker[set['obj'].id]['end'] = len(data)

            # Process the settings
            if exercise['has_weight']:
                setting_out = []
                for i in exercise['setting_text'].split('–'):
                    setting_out.append(Paragraph(i, styleSheet["Small"], bulletText=''))
            else:
                setting_out = Paragraph(exercise['setting_text'], styleSheet["Small"])

            # Collect a list of the exercise comments
            item_list = [Paragraph('', styleSheet["Small"])]
            if comments:
                item_list = [ListItem(Paragraph(i, style=styleSheet["ExerciseComments"]))
                             for i in exercise['comment_list']]

            # Add the exercise's main image
            image = Paragraph('', styleSheet["Small"])
            if images:
                if exercise['obj'].main_image:

                    # Make the images somewhat larger when printing only the workout and not
                    # also the columns for weight logs
                    if only_table:
                        image_size = 2
                    else:
                        image_size = 1.5

                    image = Image(exercise['obj'].main_image.image)
                    image.drawHeight = image_size * cm * image.drawHeight / image.drawWidth
                    image.drawWidth = image_size * cm

            # Put the name and images and comments together
            exercise_content = [Paragraph(exercise['obj'].name, styleSheet["Small"]),
                                image,
                                ListFlowable(item_list,
                                             bulletType='bullet',
                                             leftIndent=5,
                                             spaceBefore=7,
                                             bulletOffsetY=-3,
                                             bulletFontSize=3,
                                             start='square')]

            data.append([f"#{set_count}",
                         exercise_content,
                         setting_out]
                        + [''] * nr_of_weeks)
        set_count += 1

    table_style = [('FONT', (0, 0), (-1, -1), 'OpenSans'),
                   ('FONTSIZE', (0, 0), (-1, -1), 8),
                   ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                   ('LEFTPADDING', (0, 0), (-1, -1), 2),
                   ('RIGHTPADDING', (0, 0), (-1, -1), 0),
                   ('TOPPADDING', (0, 0), (-1, -1), 3),
                   ('BOTTOMPADDING', (0, 0), (-1, -1), 2),
                   ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),

                   # Header
                   ('BACKGROUND', (0, 0), (-1, 0), header_colour),
                   ('BOX', (0, 0), (-1, -1), 1.25, colors.black),
                   ('BOX', (0, 1), (-1, -1), 1.25, colors.black),
                   ('SPAN', (0, 0), (-1, 0)),

                   # Cell with 'date'
                   ('SPAN', (0, 1), (2, 1)),
                   ('ALIGN', (0, 1), (2, 1), 'RIGHT')]

    # Combine the cells for exercises on the same superset
    for marker in group_exercise_marker:
        start_marker = group_exercise_marker[marker]['start']
        end_marker = group_exercise_marker[marker]['end']

        table_style.append(('VALIGN', (0, start_marker), (0, end_marker), 'MIDDLE'))
        table_style.append(('SPAN', (0, start_marker), (0, end_marker)))

    # Set an alternating background colour for rows with exercises.
    # The rows with exercises range from exercise_start till the end of the data
    # list
    for i in range(exercise_start, len(data) + 1):
        if not i % 2:
            table_style.append(('BACKGROUND', (0, i - 1), (-1, i - 1), row_color))

    # Put everything together and manually set some of the widths
    t = Table(data, style=table_style)
    if len(t._argW) > 1:
        if only_table:
            t._argW[0] = 0.6 * cm  # Numbering
            t._argW[1] = 8 * cm  # Exercise
            t._argW[2] = 3.5 * cm  # Repetitions
        else:
            t._argW[0] = 0.6 * cm  # Numbering
            t._argW[1] = 4 * cm  # Exercise
            t._argW[2] = 3 * cm  # Repetitions

    return KeepTogether(t)
Exemplo n.º 27
0
def qcscreenToPdf():
    stylesheet = getSampleStyleSheet()
    pdf = BaseDocTemplate("SequencingReport.pdf", pagesize=landscape(A4))
    topHeight = 120  #The image is 86 pixels tall
    #fTL = Frame(pdf.leftMargin, pdf.height, width=pdf.width/2, height=topHeight, id="col1") #Fixed height
    #fTR = Frame(pdf.leftMargin+pdf.width/2, pdf.height, width=pdf.width/2, height=topHeight, id="col2")
    fB = Frame(pdf.leftMargin,
               pdf.bottomMargin,
               pdf.width,
               pdf.height - topHeight,
               id="bottom")
    fM = Frame(pdf.leftMargin,
               pdf.bottomMargin,
               pdf.width,
               pdf.height,
               id="main")

    elements = []
    #fastq_screen images
    elements.append(NextPageTemplate("FirstPage"))
    elements.append(Paragraph("Contaminant screen", stylesheet['title']))
    elements.append(
        Paragraph(
            "Below are images generated on the output of fastq_screen. In short, 1 million reads are randomly taken from each indicated sample. These reads are then aligned against a variety of organisms (mouse, human, etc.). The resulting alignments are then categorized as follows:",
            stylesheet['Normal']))
    elements.append(
        ListFlowable([
            Paragraph(
                "unique: aligns only a single time within a single species.",
                stylesheet['Normal']),
            Paragraph(
                "multimap: aligns multiple times, but only within a single species.",
                stylesheet['Normal']),
            Paragraph(
                "conserved: aligns a single time to each of two or more species.",
                stylesheet['Normal']),
            Paragraph(
                "repeat: aligns multiple times to each of two or more species.",
                stylesheet['Normal'])
        ],
                     bulletType='bullet',
                     start='circle'))
    elements.append(Spacer(0, 30))
    elements.append(
        Paragraph(
            "Ideally, the 'unique' and 'multimap' values will only be appreciably present in the species from which your sample should have arisen.",
            stylesheet['Normal']))
    elements.append(Spacer(0, 30))
    elements.append(
        Paragraph(
            "Note that as the mouse and human reference genomes are the best quality, many low complexity reads will align to them.",
            stylesheet['Normal']))
    elements.append(Spacer(0, 30))
    elements.append(NextPageTemplate("RemainingPages"))
    fqs = glob.glob("QCscreenOut/*.png")
    fqs.sort()
    for fq in fqs:
        print(fq)
        img = utils.ImageReader(fq)
        iw, ih = img.getSize()
        iw = 0.7 * iw
        ih = 0.7 * ih
        elements.append(Image(fq, width=iw, height=ih, hAlign="LEFT"))

    pdf.addPageTemplates([
        PageTemplate(id="FirstPage", frames=[fM]),
        PageTemplate(id="RemainingPages", frames=[fM])
    ]),
    pdf.build(elements)
Exemplo n.º 28
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))

    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,
                                             settings.DEP_PHONE, 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.º 29
0
    def _create_licence_purpose(elements, selected_activity, issued_purpose):
        '''
        Creates the licence purpose details per page available on the activity.
        '''

        # delegation holds the dates, licencee and issuer details.
        delegation = []
        sequence = purpose.purpose_sequence
        licence_display = '{0}-{1}-{2}'.format(licence.licence_number,
                                               sequence,
                                               issued_purpose.purpose.code)
        licence_purpose = issued_purpose.purpose.name
        elements.append(
            Paragraph(licence_purpose.upper(),
                      styles['InfoTitleVeryLargeCenter']))
        elements.append(
            Paragraph(
                'Regulation {}, Biodiversity Conservation Regulations 2018'.
                format(issued_purpose.purpose.regulation), styles['Center']))

        # applicant details
        delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        if application.applicant_type \
                == application.APPLICANT_TYPE_ORGANISATION:
            address = application.org_applicant.address
            pass
        elif application.applicant_type == application.APPLICANT_TYPE_PROXY:
            address = application.proxy_applicant.residential_address
            pass
        else:
            # applic.applicant_type == application.APPLICANT_TYPE_SUBMITTER
            address = application.submitter.residential_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('Licence Number', styles['BoldLeft']),
                Paragraph('Licence Holder', styles['BoldLeft']),
                Paragraph('Address', styles['BoldLeft'])
            ], [Paragraph(licence_display, styles['Left'])] + [
                Paragraph(licence.current_application.applicant,
                          styles['Left'])
            ] + address_paragraphs]],
                  colWidths=(120, PAGE_WIDTH - (2 * PAGE_MARGIN) - 120),
                  style=licence_table_style))

        # dates
        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('Date Valid From', styles['BoldLeft']),
            Paragraph('Date of Expiry', styles['BoldLeft'])
        ]
        date_values = [
            Paragraph(issued_purpose.issue_date.strftime('%d/%m/%Y'),
                      styles['Left']),
            Paragraph(issued_purpose.start_date.strftime('%d/%m/%Y'),
                      styles['Left']),
            Paragraph(issued_purpose.expiry_date.strftime('%d/%m/%Y'),
                      styles['Left'])
        ]

        if issued_purpose.is_reissued:
            date_headings.insert(
                0, Paragraph('Original Date of Issue', styles['BoldLeft']))
            date_values.insert(
                0, Paragraph(issued_purpose.original_issue_date,
                             styles['Left']))

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

        delegation.append(Spacer(1, SECTION_BUFFER_HEIGHT))

        elements.append(KeepTogether(delegation))

        # species
        species_ids = issued_purpose.purpose.get_species_list
        if species_ids:
            elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
            elements.append(Paragraph('SPECIES', styles['BoldLeft']))
            elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
            species = LicenceSpecies.objects.values_list('data').filter(
                specie_id__in=species_ids)
            speciesList = ListFlowable([
                Paragraph(s[0][0]['vernacular_names'], styles['Left'])
                for s in species
            ],
                                       bulletFontName=BOLD_FONTNAME,
                                       bulletFontSize=MEDIUM_FONTSIZE)
            elements.append(speciesList)
            elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

        try:
            # copy-to-licence sections with terms and additional information.
            activity_util = ActivitySchemaUtil(selected_activity.application)
            terms = selected_activity.additional_licence_info['terms']
            for term in terms:
                header = term['header']
                if not header:
                    continue
                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
                elements.append(Paragraph(header.upper(), styles['BoldLeft']))
                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
                text = activity_util.get_ctl_text(term)
                elements.append(Paragraph(text, styles['Left']))
                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

        except BaseException:
            pass

        # PurposeSpecies Section
#        for s in purpose.purpose_species_json:
#            if s.has_key('is_additional_info') and s['is_additional_info']:
#                continue
#
#            if s['details']:
#                parser = HtmlParser(s['details'])
#
#                # Get and Display Purpose Species Header
#                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
#                elements.append(
#                    Paragraph(
#                        s['header'],
#                        styles['BoldLeft']
#                    )
#                )
#                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
#
#                purposeSpeciesList = add_parsed_details(parser, list_flowable=False)
#                for info_item in purposeSpeciesList:
#                    elements.append(KeepTogether(info_item))

        for s in purpose.purpose_species_json:
            if 'is_additional_info' in s and s['is_additional_info']:
                continue

            if s['details']:
                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
                purposeSpeciesList, listcounter = html_to_rl(
                    s['details'], styles)

                for info_item in purposeSpeciesList:
                    elements.append(KeepTogether(info_item))

        # End PurposeSpecies Section

        # application conditions
        activity_conditions = selected_activity.application.conditions.filter(
            licence_activity_id=selected_activity.licence_activity_id,
            licence_purpose_id=issued_purpose.purpose.id)

        if activity_conditions.exists():
            elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
            elements.append(Paragraph('CONDITIONS', styles['BoldLeft']))
            #elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

            # Conditions Section
            #            conditionList = []
            #            for s in activity_conditions.order_by('order'):
            #                parser = HtmlParser(s.condition)
            #                conditionList += add_parsed_details(parser, list_flowable=False)
            #                #elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

            #            conditionList = ListFlowable(
            #                conditionList,
            #                bulletFontName=BOLD_FONTNAME, bulletFontSize=MEDIUM_FONTSIZE
            #            )
            #            elements.append(conditionList)

            listcounter = 0
            conditionList = []
            for s in activity_conditions.order_by('order'):
                #_conditionList, listcounter += html_to_rl(s.condition, styles)
                _conditionList, listcounter = html_to_rl(
                    s.condition_text, styles, listcounter)
                conditionList += _conditionList

            for info_item in conditionList:
                elements.append(KeepTogether(info_item))

            # End Conditions Section

        elements += _layout_extracted_fields(licence.extracted_fields)
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

        # signature block
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

        issue_officer = '{} {}'.format(selected_activity.updated_by.first_name,
                                       selected_activity.updated_by.last_name)
        elements.append(Paragraph('____________________', styles['Left']))
        elements.append(Paragraph(issue_officer, styles['Left']))
        elements.append(Paragraph('LICENSING OFFICER', styles['Left']))
        elements.append(Paragraph('WILDLIFE PROTECTION BRANCH',
                                  styles['Left']))
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        elements.append(Paragraph('Delegate of CEO', styles['ItalicLeft']))
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

        # additional information
        # 'is_additional_info' Section from Purposespecies
        #        for s in purpose.purpose_species_json:
        #            if s.has_key('is_additional_info') and s['is_additional_info'] and s['details']:
        #                parser = HtmlParser(s['details'])
        #
        #                # Get and Display Purpose Species Header
        #                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        #                elements.append(
        #                    Paragraph(
        #                        s['header'],
        #                        styles['BoldLeft']
        #                    )
        #                )
        #                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
        #
        #                purposeSpeciesInfoList = add_parsed_details(parser, list_flowable=False)
        #                #elements.append(purposeSpeciesInfoList)
        #                for info_item in purposeSpeciesInfoList:
        #                    elements.append(KeepTogether(info_item))

        # additional information
        for s in purpose.purpose_species_json:
            if 'is_additional_info' in s and s['is_additional_info'] and s[
                    'details']:
                # Get and Display Purpose Species Header
                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
                purposeSpeciesInfoList, listcounter = html_to_rl(
                    s['details'], styles)

                for info_item in purposeSpeciesInfoList:
                    elements.append(KeepTogether(info_item))
        # End PurposeSpecies Section

        if licence.has_additional_information_for(selected_activity):
            elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
            elements.append(
                Paragraph('ADDITIONAL INFORMATION', styles['BoldLeft']))
            #elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

            conditions = activity_conditions
            infos = []
            c_num = 0
            for c_id, condition in enumerate(conditions.order_by('order')):
                info = None
                if condition.standard_condition:
                    info = condition.standard_condition.additional_information
                    c_num = c_id + 1
                if info:
                    infos.append('{0} (related to condition no.{1})'.format(
                        info.encode('utf8'), c_num))

            # Conditions Section


#            for s in infos:
#                parser = HtmlParser(s)
#                infoList = add_parsed_details(parser)
#                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))
#                elements.append(infoList)

            for s in infos:
                infoList, listcounter = html_to_rl(s, styles)
                elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

                #elements.append(infoList)
                for info_item in infoList:
                    elements.append(KeepTogether(info_item))

            # End Conditions Section

        elements.append(PageBreak())
Exemplo n.º 30
0
def pdf_demo_11(file):
    doc = SimpleDocTemplate(file)
    style_sheet = getSampleStyleSheet()
    para_style = style_sheet['BodyText']
    # see dir(para_style) to see list of attributes which can be changed
    para_style.alignment = TA_JUSTIFY
    para_style.spaceBefore = 18
    head_style = style_sheet['Heading2']
    story = []
    story.append(Paragraph("Paragraphs of text", head_style))
    for i in range(10):
        s = f"This <strong>is</strong> a <em>paragraph</em> {i} with ten sentences using &lt;strong&gt; and &lt;em&gt; tags. " * 10
        p = Paragraph(s, para_style)
        story.append(p)
    # Spacers currently leave vertical space even though they have parameters for horizontal and vertical
    story.append(PageBreak())
    story.append(Paragraph("Examples of styles", head_style))
    for style_name, style in style_sheet.byName.items():
        style_description = f"{style_name} - {type(style).__name__}"
        # Using duck typing to try out the sample styles
        try:
            p = Paragraph(style_description, style)
        except AttributeError:
            # ListStyle doesn't have fontName attribute so can't be used with a Paragraph
            p = Paragraph(style_description, para_style)
        story.append(p)
    story.append(
        Paragraph("Builtin functions and classes listed in two columns",
                  head_style))
    list_style = getSampleStyleSheet()["OrderedList"]
    list_style.bulletFontName = "Courier"
    list_style.bulletFontSize = 10
    list_style.leftIndent = 24
    list_items_builtins = [
        ListItem(Paragraph(b,
                           getSampleStyleSheet()["Normal"]))
        for b in dir(builtins)
    ]
    story.append(
        BalancedColumns(
            F=[ListFlowable(list_items_builtins, style=list_style)], nCols=2))
    story.append(PageBreak())
    # If whitespace important use Preformatted rather than Paragraph
    story.append(Paragraph("Formatting text using whitespace", head_style))
    story.append(
        Preformatted(
            r"""
  ____             _                           _
 |  _ \           (_)                         ( )
 | |_) | ___  __ _ _ _ __  _ __   ___ _ __ ___|/
 |  _ < / _ \/ _` | | '_ \| '_ \ / _ \ '__/ __|
 | |_) |  __/ (_| | | | | | | | |  __/ |  \__ \
 |____/ \___|\__, |_|_| |_|_| |_|\___|_|  |___/
              __/ |
             |___/

  _____       _   _
 |  __ \     | | | |
 | |__) |   _| |_| |__   ___  _ __
 |  ___/ | | | __| '_ \ / _ \| '_ \
 | |   | |_| | |_| | | | (_) | | | |
 |_|    \__, |\__|_| |_|\___/|_| |_|
         __/ |
        |___/
    """,
            getSampleStyleSheet()["Code"]))
    doc.build(story, onFirstPage=number_page, onLaterPages=number_page)