Ejemplo n.º 1
0
 def add(self, style):
     if self.lang in self.font_overrides:
         style.fontName = self.font_overrides[self.lang]
     if self.lang in ['ja', 'zh', 'ko']:
         style.wordWrap = 'CJK'
     StyleSheet1.add(
         self,
         style)  # StyleSheet1 is an old-style class, can't use super()
Ejemplo n.º 2
0
    def para_style(self):
        from reportlab.lib.styles import ParagraphStyle, StyleSheet1

        stylesheet = StyleSheet1()
        stylesheet.add(ParagraphStyle(
            name='CommunityName',
            fontName='Helvetica',
            fontSize=16,
            textColor=colors.HexColor('#656565'),
            leading=18,
        ))
        stylesheet.add(ParagraphStyle(
            name='ReportName',
            fontName='Helvetica',
            fontSize=18,
            leading=30,
            alignment=TA_CENTER,
            textColor=colors.HexColor('#565656'),
        ))
        stylesheet.add(ParagraphStyle(
            name='normal',
            fontName='Helvetica',
            fontSize=8,
            textColor=colors.HexColor('#333333'),
        ))
        stylesheet.add(ParagraphStyle(
            name='value',
            alignment=TA_RIGHT,
            fontName='Helvetica',
            fontSize=8,
            textColor=colors.HexColor('#505050'),
        ))
        return stylesheet
Ejemplo n.º 3
0
def getStyleSheet():
    """Returns a stylesheet object"""
    stylesheet = StyleSheet1()

    stylesheet.add(ParagraphStyle(name='Normal',
                                  fontName="Helvetica",
                                  fontSize=10,
                                  leading=12))

    stylesheet.add(ParagraphStyle(name='BodyText',
                                  parent=stylesheet['Normal'],
                                  spaceBefore=14))

    stylesheet.add(ParagraphStyle(name='RightText',
                                  parent=stylesheet['Normal'],
                                  alignment=TA_RIGHT,
                                  spaceBefore=14))

    stylesheet.add(ParagraphStyle(name='JustifyText',
                                 parent=stylesheet['Normal'],
                                 alignment=TA_JUSTIFY,
                                 spaceBefore=14))

    stylesheet.add(ParagraphStyle(name='Bold',
                                  parent=stylesheet['BodyText'],
                                  fontName="Helvetica-Bold"))

    return stylesheet
Ejemplo n.º 4
0
def getShanghaiMovementCheck2015StyleSheet():
    """Returns a stylesheet object"""
    stylesheet = StyleSheet1()

    stylesheet.add(
        ParagraphStyle(name='Normal',
                       fontName='Microsoft-YaHei-Light',
                       fontSize=9,
                       leading=12))

    stylesheet.add(
        ParagraphStyle(name='Title',
                       parent=stylesheet['Normal'],
                       fontName='Microsoft-YaHei-Bold',
                       fontSize=44,
                       leading=66,
                       alignment=TA_CENTER,
                       spaceBefore=12,
                       spaceAfter=3))

    stylesheet.add(
        ParagraphStyle(name='Subtitle',
                       parent=stylesheet['Normal'],
                       fontName='Microsoft-YaHei-Light',
                       fontSize=16,
                       leading=24,
                       alignment=TA_CENTER,
                       spaceAfter=3))

    return stylesheet
Ejemplo n.º 5
0
def create_base_stylesheet():
    stylesheet = StyleSheet1()
    stylesheet.add(
        ParagraphStyle(name='Normal',
                       fontName='Times-Roman',
                       fontSize=16,
                       leading=18,
                       spaceAfter=5))
    stylesheet.add(
        ListStyle(
            name='UnorderedList',
            parent=None,
            leftIndent=18,
            rightIndent=0,
            bulletAlign='left',
            bulletType='1',
            bulletColor=colors.black,
            bulletFontName='Times-Roman',
            bulletFontSize=16,
            bulletOffsetY=0,
            bulletDedent='auto',
            bulletDir='ltr',
            bulletFormat=None,
            #start='circle square blackstar sparkle disc diamond'.split(),
            start=None,
        ),
        alias='ul')
    return stylesheet
Ejemplo n.º 6
0
 def get_style_sheet():
     stylesheet = StyleSheet1()
     stylesheet.add(
         ParagraphStyle(name='Normal',
                        fontName='Times-Roman',
                        fontSize=8,
                        leading=10,
                        spaceAfter=18))
     stylesheet.add(
         ParagraphStyle(name='SlideNumber',
                        parent=stylesheet['Normal'],
                        alignment=TA_RIGHT,
                        fontSize=6,
                        leading=8,
                        rightIndent=3,
                        spaceAfter=0))
     stylesheet.add(
         ParagraphStyle(name='Heading',
                        parent=stylesheet['Normal'],
                        fontSize=20,
                        leading=24,
                        alignment=TA_CENTER,
                        spaceAfter=0))
     stylesheet.add(
         ParagraphStyle(name='SubHeading',
                        parent=stylesheet['Normal'],
                        fontSize=16,
                        leading=20,
                        alignment=TA_CENTER))
     return stylesheet
Ejemplo n.º 7
0
 def _get_stylesheet(self):
     """
     Get a stylesheet. By default, this contains the "Normal" and "Heading1" styles.
     """
     stylesheet = StyleSheet1()
     stylesheet.add(
         ParagraphStyle(name='Normal',
                        fontName=self.font_regular,
                        fontSize=10,
                        leading=12))
     stylesheet.add(
         ParagraphStyle(name='InvoiceFrom', parent=stylesheet['Normal']))
     stylesheet.add(
         ParagraphStyle(name='Heading1',
                        fontName=self.font_bold,
                        fontSize=15,
                        leading=15 * 1.2))
     stylesheet.add(
         ParagraphStyle(name='FineprintHeading',
                        fontName=self.font_bold,
                        fontSize=8,
                        leading=12))
     stylesheet.add(
         ParagraphStyle(name='Fineprint',
                        fontName=self.font_regular,
                        fontSize=8,
                        leading=10))
     return stylesheet
Ejemplo n.º 8
0
 def _get_stylesheet(self):
     """
     Get a stylesheet. By default, this contains the "Normal" and "Heading1" styles.
     """
     stylesheet = StyleSheet1()
     stylesheet.add(
         ParagraphStyle(name='Normal',
                        fontName='OpenSans',
                        fontSize=10,
                        leading=12))
     stylesheet.add(
         ParagraphStyle(name='Heading1',
                        fontName='OpenSansBd',
                        fontSize=15,
                        leading=15 * 1.2))
     stylesheet.add(
         ParagraphStyle(name='FineprintHeading',
                        fontName='OpenSansBd',
                        fontSize=8,
                        leading=12))
     stylesheet.add(
         ParagraphStyle(name='Fineprint',
                        fontName='OpenSans',
                        fontSize=8,
                        leading=10))
     return stylesheet
    def _paragraph_styles(self):
        from reportlab.lib.styles import ParagraphStyle, StyleSheet1
        from reportlab.lib.enums import TA_CENTER, TA_RIGHT

        stylesheet = StyleSheet1()
        stylesheet.add(ParagraphStyle(
            name='CommunityName',
            fontName='Helvetica',
            fontSize=16,
            alignment=TA_CENTER,
            textColor=colors.HexColor('#505050'),
            leading=24,
        ))
        stylesheet.add(ParagraphStyle(
            name='ReportName',
            fontName='Helvetica',
            fontSize=18,
            leading=28,
            alignment=TA_CENTER,
            textColor=colors.HexColor('#565656'),
        ))
        stylesheet.add(ParagraphStyle(
            name='community_column',
            fontName='Helvetica',
            fontSize=14,
            leading=30,
            alignment=TA_RIGHT,
            textColor=colors.HexColor('#565656'),
        ))
        stylesheet.add(ParagraphStyle(
            name='report_period',
            fontName='Helvetica',
            fontSize=11,
            leading=22,
            alignment=TA_CENTER,
            textColor=colors.HexColor('#333333'),
        ))
        stylesheet.add(ParagraphStyle(
            name='report_vars',
            fontName='Helvetica',
            fontSize=14,
            leading=26,
            textColor=colors.HexColor('#565656'),
        ))
        stylesheet.add(ParagraphStyle(
            name='normal',
            fontName='Helvetica',
            fontSize=8,
            textColor=colors.HexColor('#333333'),
        ))
        stylesheet.add(ParagraphStyle(
            name='value',
            alignment=TA_RIGHT,
            fontName='Helvetica',
            fontSize=9,
            textColor=colors.HexColor('#444444'),
        ))
        return stylesheet
Ejemplo n.º 10
0
def _invoice_get_stylesheet():
    stylesheet = StyleSheet1()
    stylesheet.add(
        ParagraphStyle(name='Normal',
                       fontName='OpenSans',
                       fontSize=10,
                       leading=12))
    stylesheet.add(
        ParagraphStyle(name='Heading1',
                       fontName='OpenSansBd',
                       fontSize=15,
                       leading=15 * 1.2))
    return stylesheet
Ejemplo n.º 11
0
def build_styles(items):
    styles = StyleSheet1()
    for item in items:
        sz = item['size']
        style = ParagraphStyle(name=item['name'],
                               fontName=item['font'],
                               fontSize=sz,
                               textColor=asColor(item['color']),
                               alignment=asAlignment(item['align']),
                               allowOrphans=False,
                               allowOWidows=False,
                               leading=sz * 1.2)
        style.suffix = item['suffix']
        styles.add(style)
    return styles
Ejemplo n.º 12
0
 def getStyleSheet():
     stylesheet = StyleSheet1()
     stylesheet.add(ParagraphStyle(name='Normal',
                                   fontName='Times-Roman',
                                   fontSize=8,
                                   leading=10))
     stylesheet.add(ParagraphStyle(name='SlideNumber',
                                   parent=stylesheet['Normal'],
                                   alignment=TA_RIGHT,
                                   fontSize=6,
                                   leading=8))
     stylesheet.add(ParagraphStyle(name='Data',
                                   parent=stylesheet['Normal'],
                                   leftIndent=18,
                                   firstLineIndent=-18,
                                   ))
     return stylesheet
Ejemplo n.º 13
0
    def get_style_sheet(self):
        stylesheet = StyleSheet1()

        stylesheet.add(
            ParagraphStyle(name='Normal',
                           fontName=self._base_font_name,
                           fontSize=10,
                           leading=12))
        stylesheet.add(
            ParagraphStyle(name='BodyText',
                           parent=stylesheet['Normal'],
                           spaceBefore=6))
        stylesheet.add(ParagraphStyle(name='Title',
                                      parent=stylesheet['Normal'],
                                      fontName=self._base_font_name_bold,
                                      fontSize=18,
                                      leading=22,
                                      alignment=TA_CENTER,
                                      spaceAfter=6),
                       alias='title')
        stylesheet.add(
            ParagraphStyle(name='TableHeader',
                           parent=stylesheet['Normal'],
                           fontName=self._base_font_name_bold,
                           alignment=TA_CENTER))
        stylesheet.add(
            ParagraphStyle(name='TableBody',
                           parent=stylesheet['Normal'],
                           alignment=TA_CENTER))
        stylesheet.add(
            ParagraphStyle(name='Header',
                           parent=stylesheet['Normal'],
                           fontName=self._base_font_name_bold,
                           fontSize=18,
                           leading=22,
                           textColor=colors.green,
                           alias='header'))
        stylesheet.add(
            ParagraphStyle(name='Footer',
                           parent=stylesheet['Normal'],
                           textColor=colors.green,
                           alias='footer'))

        return stylesheet
Ejemplo n.º 14
0
def getStyleSheet(csStyle):
    """Returns a stylesheet object"""
    stylesheet = StyleSheet1()

    stylesheet.add(ParagraphStyle(name='Master', fontName=csStyle.font))

    stylesheet.add(
        ParagraphStyle(name='Title',
                       leading=csStyle.lineSpacing * csStyle.titleFontSize,
                       fontSize=csStyle.titleFontSize,
                       alignment=TA_CENTER,
                       parent=stylesheet['Master']))

    stylesheet.add(
        ParagraphStyle(name='Subtitle',
                       leading=csStyle.lineSpacing * csStyle.subtitleFontSize,
                       fontSize=csStyle.subtitleFontSize,
                       alignment=TA_CENTER,
                       parent=stylesheet['Master']))
    stylesheet.add(
        ParagraphStyle(name='Credits',
                       leading=csStyle.lineSpacing * csStyle.creditsFontSize,
                       fontSize=csStyle.creditsFontSize,
                       alignment=TA_CENTER,
                       parent=stylesheet['Master']))

    stylesheet.add(
        ParagraphStyle(name='Tempo',
                       leading=csStyle.lineSpacing * csStyle.tempoFontSize,
                       fontSize=csStyle.tempoFontSize,
                       alignment=TA_LEFT,
                       parent=stylesheet['Master']))

    stylesheet.add(
        ParagraphStyle(name='Heading',
                       leading=csStyle.lineSpacing * csStyle.headingFontSize,
                       fontSize=csStyle.headingFontSize,
                       alignment=TA_LEFT,
                       parent=stylesheet['Master'],
                       spaceAfter=2 * mm,
                       keepWithNext=1))

    return stylesheet
Ejemplo n.º 15
0
 def get_style(self):
     stylesheet = StyleSheet1()
     stylesheet.add(
         ParagraphStyle(name='Normal', fontName='Helvetica', fontSize=12, leading=14)
     )
     stylesheet.add(
         ParagraphStyle(
             name='Title', fontName='Helvetica-Bold', fontSize=14, leading=16
         )
     )
     stylesheet.add(
         ParagraphStyle(
             name='Speaker', fontName='Helvetica-Oblique', fontSize=12, leading=14
         )
     )
     stylesheet.add(
         ParagraphStyle(name='Meta', fontName='Helvetica', fontSize=10, leading=12)
     )
     return stylesheet
Ejemplo n.º 16
0
 def get_style(self):
     stylesheet = StyleSheet1()
     stylesheet.add(
         ParagraphStyle(name="Normal", fontName="Helvetica", fontSize=12, leading=14)
     )
     stylesheet.add(
         ParagraphStyle(
             name="Title", fontName="Helvetica-Bold", fontSize=14, leading=16
         )
     )
     stylesheet.add(
         ParagraphStyle(
             name="Speaker", fontName="Helvetica-Oblique", fontSize=12, leading=14
         )
     )
     stylesheet.add(
         ParagraphStyle(name="Meta", fontName="Helvetica", fontSize=10, leading=12)
     )
     return stylesheet
Ejemplo n.º 17
0
 def stylesheet(self):
     stylesheet = StyleSheet1()
     stylesheet.add(
         ParagraphStyle(name='Normal',
                        fontName='Gandhi-R',
                        fontSize=10,
                        leading=12))
     stylesheet.add(
         ParagraphStyle(name='Heading1',
                        fontName='Gandhi-B',
                        fontSize=16,
                        leading=20))
     stylesheet.add(
         ParagraphStyle(name='Meta',
                        fontName='Gandhi-I',
                        fontSize=10,
                        leading=12))
     stylesheet.add(
         ParagraphStyle(name='Message',
                        spaceBefore=2 * mm,
                        parent=stylesheet['Normal']))
     return stylesheet
def get_stylesheet():
    """
    Create and return a custom stylesheet
    """
    stylesheet = StyleSheet1()

    stylesheet.add(
        ParagraphStyle(name='Normal',
                       fontName=_baseFontName,
                       fontSize=12,
                       leading=14,
                       textColor=blue))

    stylesheet.add(
        ParagraphStyle(name='BodyText',
                       parent=stylesheet['Normal'],
                       spaceBefore=6))

    stylesheet.add(
        ParagraphStyle(name='Italic',
                       parent=stylesheet['BodyText'],
                       fontName=_baseFontNameI))

    stylesheet.add(
        ParagraphStyle(name='Bold',
                       parent=stylesheet['BodyText'],
                       fontName=_baseFontNameB))

    stylesheet.add(ParagraphStyle(name='Heading1',
                                  parent=stylesheet['Normal'],
                                  fontName=_baseFontNameB,
                                  fontSize=20,
                                  leading=24,
                                  spaceAfter=6),
                   alias='h1')

    return stylesheet
def stylesheet():
    """ Create the style sheet """
    global _stylesheet
    if _stylesheet is not None:
        return _stylesheet
    stylesheet = StyleSheet1()
    stylesheet.add(
        ParagraphStyle(name='Normal',
                       alignment=TA_LEFT,
                       fontName='Courier',
                       fontSize=10,
                       leading=12,
                       spaceAfter=2))
    stylesheet.add(ParagraphStyle(name='Heading1',
                                  parent=stylesheet['Normal'],
                                  pageBreakBefore=0,
                                  add_to_toc=True,
                                  keepWithNext=1,
                                  fontName='Courier-Bold',
                                  fontSize=16,
                                  leading=22,
                                  spaceBefore=0,
                                  spaceAfter=0),
                   alias='h1')
    stylesheet.add(ParagraphStyle(name='Heading2',
                                  parent=stylesheet['Normal'],
                                  frameBreakBefore=0,
                                  keepWithNext=1,
                                  fontName='Courier',
                                  fontSize=12,
                                  leading=18,
                                  spaceBefore=8,
                                  spaceAfter=0),
                   alias='h2')
    _stylesheet = stylesheet
    return stylesheet
Ejemplo n.º 20
0
 def add(self, style):
     if self.lang in self.font_overrides:
         style.fontName = self.font_overrides[self.lang]
     if self.lang in ['ja', 'zh', 'ko']:
         style.wordWrap = 'CJK'
     StyleSheet1.add(self, style)  # StyleSheet1 is an old-style class, can't use super()
Ejemplo n.º 21
0
# register new truetype fonts
pdfmetrics.registerFont(TTFont(
    'Ubuntu', path_join(settings.SITE_ROOT, 'static/fonts/Ubuntu-R.ttf')))
pdfmetrics.registerFont(TTFont(
    'Ubuntu-Bold', path_join(settings.SITE_ROOT, 'static/fonts/Ubuntu-B.ttf')))
pdfmetrics.registerFont(TTFont(
    'Ubuntu-Italic', path_join(settings.SITE_ROOT, 'static/fonts/Ubuntu-RI.ttf')))


# set style information
PAGE_HEIGHT = defaultPageSize[1]
PAGE_WIDTH = defaultPageSize[0]


# set custom stylesheets
stylesheet = StyleSheet1()
stylesheet.add(ParagraphStyle(
    name='Normal',
    fontName='Ubuntu',
    fontSize=10,
    leading=12,
))
stylesheet.add(ParagraphStyle(
    name='Paragraph',
    parent=stylesheet['Normal'],
    leading=14,
    spaceAfter=15
))
stylesheet.add(ParagraphStyle(
    name='Small',
    parent=stylesheet['Normal'],
Ejemplo n.º 22
0
def get_infringement_notice_table(sanction_outcome):
    col_width = [
        40 * mm,
        60 * mm,
        80 * mm,
    ]

    # SPAN (col, row)
    invoice_table_style = TableStyle([
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
        ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ('SPAN', (0, 0), (1, 0)),

        # Alleged offender
        ('SPAN', (0, 1), (0, 5)),
        ('SPAN', (1, 1), (2, 1)),
        ('SPAN', (1, 2), (2, 2)),
        ('SPAN', (1, 3), (2, 3)),
        ('SPAN', (1, 4), (2, 4)),
        ('SPAN', (1, 5), (2, 5)),

        # When
        ('SPAN', (1, 6), (2, 6)),

        # Where
        ('SPAN', (1, 7), (2, 7)),

        # Alleged offence
        ('SPAN', (0, 8), (0, 11)),
        ('SPAN', (1, 8), (2, 8)),
        ('SPAN', (1, 9), (2, 9)),
        ('SPAN', (1, 10), (2, 10)),
        ('SPAN', (1, 11), (2, 11)),

        # Officer issuing notice
        ('SPAN', (0, 12), (0, 14)),
        ('SPAN', (1, 12), (2, 12)),
        ('SPAN', (1, 13), (2, 13)),
        ('SPAN', (1, 14), (2, 14)),

        # Date
        ('SPAN', (1, 15), (2, 15)),
    ])

    date_str = gap(10) + '/' + gap(10) + '/ 20'

    styles = StyleSheet1()
    styles.add(
        ParagraphStyle(
            name='Normal',
            fontName='Times-Roman',
            fontSize=12,
            spaceBefore=7,  # space before paragraph
            spaceAfter=7,  # space after paragraph
            leading=16))  # space between lines
    styles.add(
        ParagraphStyle(name='BodyText', parent=styles['Normal'],
                       spaceBefore=6))
    styles.add(
        ParagraphStyle(name='Italic',
                       parent=styles['BodyText'],
                       fontName='Times-Italic'))
    styles.add(
        ParagraphStyle(name='Bold',
                       parent=styles['BodyText'],
                       fontName='Times-Bold'))
    # styles = getSampleStyleSheet()
    data = []
    data.append([
        Paragraph(
            '<i>Biodiversity Conservation Act 2016</i><br /><strong>Infringement Notice</strong>',
            styles['Normal']), '',
        Paragraph(
            u'Infringement<br />notice no. <font face="Helvetica"><strong>' +
            sanction_outcome.lodgement_number + u'</strong></font>',
            styles['Normal'])
    ])

    # Alleged offender
    offender = sanction_outcome.get_offender()[0]
    offender_dob = offender.dob.strftime('%d/%m/%Y') if offender.dob else ''
    offender_postcode = offender.residential_address.postcode if offender.residential_address else ''
    data.append([
        Paragraph('Alleged offender', styles['Bold']),
        Paragraph('Name: Family name: ' + get_font_str(offender.last_name),
                  styles['Normal']), ''
    ])
    data.append([
        '',
        Paragraph(
            gap(12) + 'Given names: ' + get_font_str(offender.first_name),
            styles['Normal']), ''
    ])
    data.append([
        '',
        Paragraph(
            gap(12) + 'Date of Birth: ' + get_font_str(offender_dob),
            styles['Normal']), ''
    ])
    data.append([
        '',
        [
            Paragraph('<strong>or</strong><br />Body corporate name: ',
                      styles['Normal']),
            Spacer(1, 22)
        ], ''
    ])
    data.append([
        '',
        [
            Paragraph('Address: ', styles['Normal']),
            Paragraph(get_font_str(str(offender.residential_address)),
                      styles['Normal']),
            Paragraph('Postcode: ' + get_font_str(offender_postcode),
                      styles['Normal']),
        ],
        '',
    ])

    # When
    offence_datetime = sanction_outcome.offence.offence_occurrence_datetime
    data.append([
        Paragraph('When', styles['Bold']),
        Paragraph(
            'Date: ' + get_font_str(offence_datetime.strftime('%d/%m/%Y')) +
            gap(5) + 'Time: ' +
            get_font_str(offence_datetime.strftime('%I:%M %p')),
            styles['Normal']), ''
    ])

    # Where
    offence_location = sanction_outcome.offence.location
    offence_location_str = str(offence_location) if offence_location else ''
    data.append([
        Paragraph('Where', styles['Bold']),
        [
            Paragraph('Location of offence', styles['Normal']),
            Paragraph(get_font_str(offence_location_str), styles['Normal']),
            Spacer(1, 25)
        ],
        '',
    ])

    # Alleged offence
    data.append([
        Paragraph('Alleged offence', styles['Bold']),
        [
            Paragraph('Description of offence', styles['Normal']),
            Paragraph(get_font_str(sanction_outcome.description),
                      styles['Normal']),
        ], ''
    ])  # row index: 8
    data.append([
        '',
        [
            Paragraph('Is this a 2nd subsequent offence?', styles['Normal']),
            YesNoCheckbox(11, 11),
        ],
        '',
    ])
    data.append([
        '',
        [
            Paragraph('Biodiversity Conservation Act 2016 s.',
                      styles['Normal']),
            Paragraph('or', styles['Normal']),
            Paragraph('Biodiversity Conservation Regulations 2018 r.',
                      styles['Normal'])
        ], ''
    ])
    data.append(['', Paragraph('Modified penalty: $', styles['Normal']), ''])

    # Officer issuing notice
    data.append([
        Paragraph('Officer issuing notice', styles['Bold']),
        Paragraph(
            'Name: {}'.format(
                get_font_str(
                    sanction_outcome.responsible_officer.get_full_name())),
            styles['Normal']), ''
    ])  # row index: 12
    data.append([
        '',
        Paragraph('Signature', styles['Normal']),
        '',
    ])
    data.append([
        '',
        Paragraph('Officer no.', styles['Normal']),
        '',
    ])

    # Date
    issue_date = get_font_str(
        sanction_outcome.date_of_issue.strftime('%d/%m/%Y'))
    issue_time = get_font_str(
        sanction_outcome.time_of_issue.strftime('%I:%M %p'))
    data.append([
        Paragraph('Date', styles['Bold']),
        Paragraph('Date of notice: ' + issue_date + ' ' + issue_time,
                  styles['Normal']), ''
    ])

    # Create 1st table
    t1 = Table(data, style=invoice_table_style, colWidths=col_width)

    return t1
Ejemplo n.º 23
0
def getStyleSheet():
    """Returns a stylesheet object"""
    stylesheet = StyleSheet1()

    stylesheet.add(
        ParagraphStyle(name='Normal',
                       fontName='Times-Roman',
                       fontSize=10,
                       leading=12,
                       spaceBefore=6))

    stylesheet.add(ParagraphStyle(name='Comment', fontName='Times-Italic'))

    stylesheet.add(ParagraphStyle(
        name='Indent0',
        leftIndent=18,
    ))

    stylesheet.add(
        ParagraphStyle(name='Indent1',
                       leftIndent=36,
                       firstLineIndent=0,
                       spaceBefore=1,
                       spaceAfter=7))

    stylesheet.add(
        ParagraphStyle(name='Indent2',
                       leftIndent=50,
                       firstLineIndent=0,
                       spaceAfter=100))

    stylesheet.add(
        ParagraphStyle(name='BodyText',
                       parent=stylesheet['Normal'],
                       spaceBefore=6))
    stylesheet.add(
        ParagraphStyle(name='Italic',
                       parent=stylesheet['BodyText'],
                       fontName='Times-Italic'))

    stylesheet.add(ParagraphStyle(name='Heading1',
                                  parent=stylesheet['Normal'],
                                  fontName='Times-Bold',
                                  alignment=TA_CENTER,
                                  fontSize=18,
                                  leading=22,
                                  spaceAfter=6),
                   alias='h1')

    stylesheet.add(ParagraphStyle(name='Heading2',
                                  parent=stylesheet['Normal'],
                                  fontName='Times-Bold',
                                  fontSize=14,
                                  leading=17,
                                  spaceBefore=12,
                                  spaceAfter=6),
                   alias='h2')

    stylesheet.add(ParagraphStyle(name='Heading3',
                                  parent=stylesheet['Normal'],
                                  fontName='Times-BoldItalic',
                                  fontSize=12,
                                  leading=14,
                                  spaceBefore=12,
                                  spaceAfter=6),
                   alias='h3')

    stylesheet.add(ParagraphStyle(name='Heading4',
                                  parent=stylesheet['Normal'],
                                  fontName='Times-BoldItalic',
                                  spaceBefore=10,
                                  spaceAfter=4),
                   alias='h4')

    stylesheet.add(ParagraphStyle(name='Title',
                                  parent=stylesheet['Normal'],
                                  fontName='Times-Bold',
                                  fontSize=32,
                                  leading=40,
                                  spaceAfter=36,
                                  alignment=TA_CENTER),
                   alias='t')

    stylesheet.add(ParagraphStyle(name='Bullet',
                                  parent=stylesheet['Normal'],
                                  firstLineIndent=0,
                                  leftIndent=54,
                                  bulletIndent=18,
                                  spaceBefore=0,
                                  bulletFontName='Symbol'),
                   alias='bu')

    stylesheet.add(ParagraphStyle(name='Definition',
                                  parent=stylesheet['Normal'],
                                  firstLineIndent=0,
                                  leftIndent=36,
                                  bulletIndent=0,
                                  spaceBefore=6,
                                  bulletFontName='Times-BoldItalic'),
                   alias='df')

    stylesheet.add(
        ParagraphStyle(name='Code',
                       parent=stylesheet['Normal'],
                       fontName='Courier-Bold',
                       fontSize=8,
                       leading=8.8,
                       leftIndent=36,
                       firstLineIndent=0,
                       hyphenationLang=''))

    stylesheet.add(
        ParagraphStyle(name='Link',
                       parent=stylesheet['Code'],
                       spaceAfter=7,
                       spaceBefore=0,
                       leftIndent=55))

    stylesheet.add(
        ParagraphStyle(name='FunctionHeader',
                       parent=stylesheet['Normal'],
                       fontName='Courier-Bold',
                       fontSize=8,
                       leading=8.8))

    stylesheet.add(
        ParagraphStyle(name='DocString',
                       parent=stylesheet['Normal'],
                       fontName='Courier',
                       fontSize=8,
                       leftIndent=18,
                       leading=8.8))

    stylesheet.add(
        ParagraphStyle(name='DocStringIndent',
                       parent=stylesheet['Normal'],
                       fontName='Courier',
                       fontSize=8,
                       leftIndent=36,
                       leading=8.8))

    stylesheet.add(ParagraphStyle(name='URL',
                                  parent=stylesheet['Normal'],
                                  fontName='Courier',
                                  textColor=colors.navy,
                                  alignment=TA_CENTER),
                   alias='u')

    stylesheet.add(
        ParagraphStyle(name='Centred',
                       parent=stylesheet['Normal'],
                       alignment=TA_CENTER))

    stylesheet.add(
        ParagraphStyle(name='Caption',
                       parent=stylesheet['Centred'],
                       fontName='Times-Italic'))

    return stylesheet
Ejemplo n.º 24
0
class _LabelPdfGenerator:
    page_width = 90 * mm
    page_height = 29 * mm

    margin_left = 3 * mm
    margin_top = 2 * mm
    margin_right = 4 * mm
    margin_bottom = 2 * mm

    inner_left = margin_left
    inner_top = page_height - margin_top
    inner_right = page_width - margin_right
    inner_bottom = margin_bottom
    inner_width = inner_right - margin_left
    inner_height = inner_top - margin_bottom

    stylesheet = StyleSheet1()
    stylesheet.add(ParagraphStyle(
        name='title',
        fontName='Helvetica',
        fontSize=12,
        alignment=TA_CENTER,
    ))
    stylesheet.add(ParagraphStyle(
        name='data',
        fontName='Helvetica',
        fontSize=10,
        alignment=TA_CENTER,
    ))

    def generate_label(self, title: str, data: str, logo_path: str, label_border: bool, output_path: str):
        canv = self._create_new_canvas(pdf_path=output_path)

        canv.setAuthor(config.App.TITLE)
        canv.setTitle(title)
        canv.setSubject(data)

        if label_border:
            self._draw_border(canv)
        self._draw_logo(canv, self.inner_left + 1 * mm, self.inner_top - 8.5 * mm, logo_path)
        self._draw_title(canv, self.inner_left + 32 * mm, self.inner_top - 10 * mm, 50 * mm, 10 * mm, title)
        self._draw_barcode(canv, self.inner_bottom + 5 * mm, data, bar_height=8 * mm)

        canv.showPage()
        canv.save()

    def _create_new_canvas(self, pdf_path: str) -> canvas:
        return canvas.Canvas(pdf_path, pagesize=(self.page_width, self.page_height))

    def _draw_border(self, canv: canvas):
        canv.roundRect(self.margin_left, self.margin_bottom, self.inner_width, self.inner_height, radius=5, stroke=1,
                       fill=0)

    def _draw_title(self, canv: canvas, x: int, y: int, width: int, height: int, title: str):
        self._draw_textbox(canv, x, y, width, height, title, style_name='title')

    def _draw_logo(self, canv: canvas, x: int, y: int, image_path: str):
        canv.drawImage(image_path, x, y, 28 * mm, 7 * mm)

    def _draw_barcode(self, canv: canvas, y: int, data: str, bar_height: int=20 * mm):
        # http://en.wikipedia.org/wiki/Code_39
        barcode = code39.Standard39(data, barWidth=0.6 * mm, barHeight=bar_height, stop=True, checksum=False)
        barcode.drawOn(canv, self.inner_left + (self.inner_width - barcode.width) / 2, y)

        box_height = 4 * mm
        self._draw_textbox(canv, self.inner_left, y - 0.5 * mm - box_height,
                           self.inner_width, box_height, data, style_name='data')

    def _draw_textbox(self, canv: canvas, x: int, y: int, width: int, height: int,
                      data: str, style_name: str, border: bool=False):
        table_cells = [
            [Paragraph(data, self.stylesheet[style_name])]
        ]
        table_style = [
            ('VALIGN', (-1, -1), (-1, -1), 'MIDDLE'),
        ]
        if border:
            table_style += [('BOX', (0, 0), (-1, -1), 0.25, colors.black)]

        table = Table(table_cells, colWidths=[width], rowHeights=[height])
        table.setStyle(TableStyle(table_style))
        table.wrapOn(canv, width, height)
        table.drawOn(canv, x, y)
Ejemplo n.º 25
0
def get_stylesheet():
    """Get a stylesheet for this here PDF"""

    from reportlab.lib.styles import ParagraphStyle, StyleSheet1

    stylesheet = StyleSheet1()
    stylesheet.add(
        ParagraphStyle(
            name="Body",
            fontName="Times-Roman",
            fontSize=7,
            leading=8,
        ))
    image_size = inch / 4
    stylesheet.add(
        ParagraphStyle(
            name="Event",
            fontName="Times-Roman",
            fontSize=7,
            leading=8,
            spaceAfter=10,
            leftIndent=image_size + inch / 28,
            firstLineIndent=-(image_size + inch / 28),
        ))
    image_size = inch / 5
    stylesheet.add(
        ParagraphStyle(
            name="Twitter",
            fontName="Times-Roman",
            fontSize=7,
            leading=8,
            spaceAfter=8,
            leftIndent=image_size + inch / 32,
            firstLineIndent=-(image_size + inch / 32),
        ))
    stylesheet.add(
        ParagraphStyle(
            name="TwitterReply",
            fontName="Times-Roman",
            fontSize=7,
            leading=8,
            spaceAfter=8,
            leftIndent=image_size + inch / 32,
            firstLineIndent=-(image_size + inch / 32),
            textColor='red',
        ))
    stylesheet.add(
        ParagraphStyle(
            name="List",
            fontName="Times-Roman",
            fontSize=8,
            leading=9,
            bulletIndent=1,
        ))
    stylesheet.add(
        ParagraphStyle(
            name="Cal",
            fontName="Helvetica",
            fontSize=6,
            leading=8,
            textColor='white',
        ))
    stylesheet.add(
        ParagraphStyle(
            name="CalComment",
            fontName="Helvetica",
            fontSize=6,
            leading=6,
            textColor='black',
        ))
    stylesheet.add(ParagraphStyle(
        name="Photo",
        fontSize=1,
        leading=0,
    ))
    stylesheet.add(
        ParagraphStyle(
            name="PhotoCaption",
            fontName="Helvetica",
            fontSize=10,
            leading=14,
            leftIndent=5,
            borderPadding=5,
            textColor='black',
            backColor='white',
        ))

    return stylesheet
Ejemplo n.º 26
0
def _create_pdf(invoice_buffer, sanction_outcome):
    PAGE_MARGIN = 5 * mm
    page_frame_1 = Frame(
        PAGE_MARGIN,
        PAGE_MARGIN,
        PAGE_WIDTH - 2 * PAGE_MARGIN,
        PAGE_HEIGHT - 2 * PAGE_MARGIN,
        id='PagesFrame1',
    )  #showBoundary=Color(0, 1, 0))
    PAGE_MARGIN2 = 17 * mm
    page_frame_2 = Frame(
        PAGE_MARGIN2,
        PAGE_MARGIN2,
        PAGE_WIDTH - 2 * PAGE_MARGIN2,
        PAGE_HEIGHT - 2 * PAGE_MARGIN2,
        id='PagesFrame2',
    )  #showBoundary=Color(0, 0, 1))
    page_template_1 = PageTemplate(
        id='Page1',
        frames=[
            page_frame_1,
        ],
    )
    page_template_2 = PageTemplate(
        id='Page2',
        frames=[
            page_frame_2,
        ],
    )
    doc = BaseDocTemplate(
        invoice_buffer,
        pageTemplates=[page_template_1, page_template_2],
        pagesize=A4,
    )  # showBoundary=Color(1, 0, 0))

    # Common
    FONT_SIZE_L = 11
    FONT_SIZE_M = 10
    FONT_SIZE_S = 8

    styles = StyleSheet1()
    styles.add(
        ParagraphStyle(
            name='Normal',
            fontName='Helvetica',
            fontSize=FONT_SIZE_M,
            spaceBefore=7,  # space before paragraph
            spaceAfter=7,  # space after paragraph
            leading=12))  # space between lines
    styles.add(
        ParagraphStyle(name='BodyText', parent=styles['Normal'],
                       spaceBefore=6))
    styles.add(
        ParagraphStyle(name='Italic',
                       parent=styles['BodyText'],
                       fontName='Helvetica-Italic'))
    styles.add(
        ParagraphStyle(name='Bold',
                       parent=styles['BodyText'],
                       fontName='Helvetica-Bold',
                       alignment=TA_CENTER))
    styles.add(
        ParagraphStyle(name='Right',
                       parent=styles['BodyText'],
                       alignment=TA_RIGHT))
    styles.add(
        ParagraphStyle(name='Centre',
                       parent=styles['BodyText'],
                       alignment=TA_CENTER))

    # Logo
    dpaw_header_logo = ImageReader(DPAW_HEADER_LOGO)
    dpaw_header_logo_size = dpaw_header_logo.getSize()
    width = dpaw_header_logo_size[0] / 2
    height = dpaw_header_logo_size[1] / 2
    dbca_logo = Image(DPAW_HEADER_LOGO, width=width, height=height)

    # 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'),
        ('SPAN', (0, 0), (1, 0)),

        # Alleged offender
        ('SPAN', (0, 1), (0, 5)),
        ('SPAN', (1, 1), (2, 1)),
        ('SPAN', (1, 2), (2, 2)),
        ('SPAN', (1, 3), (2, 3)),
        ('SPAN', (1, 4), (2, 4)),
        ('SPAN', (1, 5), (2, 5)),

        # When
        ('SPAN', (1, 6), (2, 6)),

        # Where
        ('SPAN', (1, 7), (2, 7)),

        # Alleged offence
        ('SPAN', (0, 8), (0, 9)),
        ('SPAN', (1, 8), (2, 8)),
        # ('SPAN', (1, 9), (2, 9)),
        ('SPAN', (1, 9), (2, 9)),
        # ('SPAN', (1, 10), (2, 10)),

        # Officer issuing notice
        ('SPAN', (0, 10), (0, 12)),
        ('SPAN', (1, 10), (2, 10)),
        ('SPAN', (1, 11), (2, 11)),
        ('SPAN', (1, 12), (2, 12)),

        # Date
        ('SPAN', (1, 13), (2, 13)),

        # Notice to alleged offender
        ('SPAN', (1, 14), (2, 14)),
    ])
    date_str = gap(10) + '/' + gap(10) + '/ 20'
    col_width = [
        40 * mm,
        60 * mm,
        80 * mm,
    ]

    data = []
    data.append([
        Paragraph(
            '<i>Biodiversity Conservation Act 2016</i><br /><strong><font size="'
            + str(FONT_SIZE_L) + '">Caution Notice</font></strong>',
            styles['Normal']), '',
        Paragraph(
            u'Caution<br />notice no. ' +
            get_font_str(sanction_outcome.lodgement_number), styles['Normal'])
    ])

    # Alleged offender
    offender = sanction_outcome.get_offender()
    offender_dob = offender[0].dob.strftime(
        '%d/%m/%Y') if offender[0].dob else ''
    data.append([
        Paragraph('Alleged offender', styles['Bold']),
        Paragraph('Name: Family name: ' + get_font_str(offender[0].last_name),
                  styles['Normal']), ''
    ])
    data.append([
        '',
        Paragraph(
            gap(12) + 'Given names: ' + get_font_str(offender[0].first_name),
            styles['Normal']), ''
    ])
    data.append([
        '',
        Paragraph(
            gap(12) + 'Date of Birth: ' + get_font_str(offender_dob),
            styles['Normal']), ''
    ])
    data.append([
        '',
        [
            Paragraph('<strong>or</strong><br />Body corporate name',
                      styles['Normal']),
            Spacer(1, 25)
        ], ''
    ])
    # data.append(['', [Paragraph('Address', styles['Normal']), Spacer(1, 25), Paragraph('Postcode', styles['Normal'])], ''])
    postcode = offender[0].residential_address.postcode if offender[
        0].residential_address else ''
    data.append([
        '',
        [
            Paragraph('Address: ', styles['Normal']),
            Paragraph(get_font_str(str(offender[0].residential_address)),
                      styles['Normal']),
            Paragraph('Postcode: ' + get_font_str(postcode), styles['Normal']),
        ],
        '',
    ])

    # When
    # data.append([Paragraph('When', styles['Bold']), Paragraph('Date' + date_str + gap(5) + 'Time' + gap(10) + 'am/pm', styles['Normal']), ''])
    offence_datetime = sanction_outcome.offence.offence_occurrence_datetime
    data.append([
        Paragraph('When', styles['Bold']),
        Paragraph(
            'Date: ' + get_font_str(offence_datetime.strftime('%d/%m/%Y')) +
            gap(5) + 'Time: ' +
            get_font_str(offence_datetime.strftime('%I:%M %p')),
            styles['Normal']), ''
    ])

    # Where
    # data.append([Paragraph('Where', styles['Bold']), [Paragraph('Location of offence', styles['Normal']), Spacer(1, 25)], ''])
    offence_location = sanction_outcome.offence.location
    offence_location_str = str(offence_location) if offence_location else ''
    data.append([
        Paragraph('Where', styles['Bold']),
        [
            Paragraph('Location of offence', styles['Normal']),
            Paragraph(get_font_str(offence_location_str), styles['Normal']),
            Spacer(1, 25)
        ],
        '',
    ])

    # Alleged offence
    data.append([
        Paragraph('Alleged offence', styles['Bold']),
        [
            Paragraph('Description of offence', styles['Normal']),
        ], ''
    ])  # row index: 8
    # data.append(['', rect, ''])
    # data.append(['', '?', ''])
    data.append([
        '',
        Paragraph(
            '<i>Biodiversity Conservation Act 2016 s.</i>' + gap(10) +
            'or<br /><i>Biodiversity Conservation Regulations 2018 r.</i>',
            styles['Normal']), ''
    ])

    # Officer issuing notice
    # data.append([Paragraph('Officer issuing notice', styles['Bold']), Paragraph('Name', styles['Normal']), ''])  # row index: 12
    data.append([
        Paragraph('Officer issuing notice', styles['Bold']),
        Paragraph(
            'Name: {}'.format(
                get_font_str(
                    sanction_outcome.responsible_officer.get_full_name())),
            styles['Normal']), ''
    ])  # row index: 12
    data.append(['', Paragraph('Signature', styles['Normal']), ''])
    data.append(['', Paragraph('Officer no.', styles['Normal']), ''])

    # Date
    issue_date = get_font_str(
        sanction_outcome.date_of_issue.strftime('%d/%m/%Y'))
    issue_time = get_font_str(
        sanction_outcome.time_of_issue.strftime('%I:%M %p'))
    data.append([
        Paragraph('Date', styles['Bold']),
        Paragraph('Date of notice: ' + issue_date + ' ' + issue_time,
                  styles['Normal']), ''
    ])

    # Notice to alleged offender
    body = []
    body.append(
        Paragraph(
            'It is alleged that you have committed the above offence.</p>',
            styles['Normal']))
    body.append(
        Paragraph(
            'If you object to the issue of this notice you can apply in writing to the Approved Officer at the below address for a review within 28 days after the date of this notice.',
            styles['Normal']))
    body.append(
        Paragraph(
            'Approved Officer — <i>Biodiversity Conservation Act 2016</i><br />Department of Biodiversity, Conservation and Attractions<br />Locked Bag 104<br />Bentley Delivery Centre WA 6983',
            styles['Normal']))
    data.append(
        [Paragraph('Notice to alleged offender', styles['Bold']), body, ''])

    # Create 1st table
    t1 = Table(data, style=invoice_table_style, colWidths=col_width)

    # Append tables to the elements to build
    gap_between_tables = 1.5 * mm
    elements = []
    elements.append(dbca_logo)
    elements.append(Spacer(0, 5 * mm))
    elements.append(t1)
    elements.append(NextPageTemplate([
        'Page2',
    ]))
    elements.append(PageBreak())
    elements.append(dbca_logo)
    elements.append(Spacer(0, 5 * mm))
    # ORIGINAL NOTES OF INCIDENT:
    title_original_notes = Paragraph(
        '<font size="' + str(FONT_SIZE_L) +
        '"><strong>ORIGINAL NOTES OF INCIDENT:</strong></font>',
        styles['Normal'])
    elements.append(title_original_notes)
    elements.append(Spacer(0, 10 * mm))
    for i in range(0, 25):
        elements.append(BrokenLine(170 * mm, 8 * mm))
    elements.append(
        Paragraph(
            '<font size="' + str(FONT_SIZE_L) + '"><strong>Signature: ' +
            gap(80) + 'Date:</strong></font>', styles['Normal']))

    doc.build(elements)
    return invoice_buffer
Ejemplo n.º 27
0
def _create_pdf(invoice_buffer, legal_case, offenders):
    every_page_frame = Frame(
        PAGE_MARGIN,
        PAGE_MARGIN,
        PAGE_WIDTH - 2 * PAGE_MARGIN,
        PAGE_HEIGHT - 2 * PAGE_MARGIN,
        id='EveryPagesFrame',
    )  #showBoundary=Color(0, 1, 0))
    every_page_template = PageTemplate(
        id='EveryPages',
        frames=[
            every_page_frame,
        ],
    )
    doc = BaseDocTemplate(
        invoice_buffer,
        pageTemplates=[
            every_page_template,
        ],
        pagesize=A4,
    )  # showBoundary=Color(1, 0, 0))

    # Common
    col_width_head = [
        95 * mm,
        15 * mm,
        85 * mm,
    ]
    col_width_details = [28 * mm, 28 * mm, 71 * mm, 23 * mm, 41 * mm]
    FONT_SIZE_L = 12
    FONT_SIZE_M = 10
    FONT_SIZE_S = 8
    topLeftTableRowHeights = [
        23.5 * mm,
    ]
    topRightTableRowHeights = [
        7.8 * mm,
        15.6 * mm,
    ]

    styles = StyleSheet1()
    styles.add(
        ParagraphStyle(
            name='Normal',
            fontName='Helvetica',
            fontSize=FONT_SIZE_M,
            spaceBefore=2,  # space before paragraph
            spaceAfter=2,  # space after paragraph
            leading=11))  # space between lines
    styles.add(
        ParagraphStyle(name='BodyText', parent=styles['Normal'],
                       spaceBefore=6))
    styles.add(
        ParagraphStyle(name='Italic',
                       parent=styles['BodyText'],
                       fontName='Helvetica-Italic'))
    styles.add(
        ParagraphStyle(name='Bold',
                       parent=styles['BodyText'],
                       fontName='Helvetica-Bold',
                       alignment=TA_CENTER))
    styles.add(
        ParagraphStyle(name='Right',
                       parent=styles['BodyText'],
                       alignment=TA_RIGHT))
    styles.add(
        ParagraphStyle(name='Centre',
                       parent=styles['BodyText'],
                       alignment=TA_CENTER))

    court_date_qs = legal_case.court_proceedings.court_dates.all().order_by(
        'court_datetime')
    court_date_obj = None
    if court_date_qs:
        # Retrieve earliest one
        court_date_obj = court_date_qs[0]

    elements = []
    for offender in offenders:
        offender_full_name = ''
        court_date_txt = ''
        court_time_txt = ''
        court_place_txt = ''

        if offender.person:
            offender_full_name = offender.person.get_full_name()
        if court_date_obj and court_date_obj.court_datetime:
            local_datetime = court_date_obj.court_datetime.astimezone(
                pytz.timezone(TIME_ZONE))
            court_date_txt = local_datetime.strftime('%d/%m/%Y')
            court_time_txt = local_datetime.strftime('%H:%M')
        if court_date_obj and court_date_obj.court:
            court_place_txt = court_date_obj.court.location

        ###
        # 1st page
        ###

        # Header small text
        header_small_text_p1 = ParagraphOffeset(
            '<font size="' + str(FONT_SIZE_S) +
            '">Copy to be attached to court copy of prosecution notice</font>',
            styles['Right'],
            x_offset=-3 * mm,
            y_offset=0)

        # Head (col, row)
        invoice_table_style = TableStyle([
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ('GRID', (0, 0), (-1, -1), 0, colors.white),
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ])
        style_tbl_left = TableStyle([
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ])
        style_tbl_right = TableStyle([
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ])
        data_left = Table([[
            Paragraph(
                'MAGISTRATES COURT of WESTERN<br />'
                'AUSTRALIA<br />'
                '<strong><font size="' + str(FONT_SIZE_L) +
                '">COURT HEARING NOTICE</font></strong><br />'
                '<i>Criminal Procedure Act 2004</i><br />'
                'Criminal Procedure Regulations 2005 - Form 5',
                styles['Centre']),
        ]],
                          style=style_tbl_left,
                          rowHeights=topLeftTableRowHeights)
        data_right = Table([
            [Paragraph('Court number', styles['Normal']), ''],
            [Paragraph('Magistrates court at', styles['Normal']), ''],
        ],
                           style=style_tbl_right,
                           rowHeights=topRightTableRowHeights)
        tbl_head = Table(
            [[data_left, '', data_right]],
            style=invoice_table_style,
            colWidths=col_width_head,
        )

        # Accused's Details, etc
        rowHeights = [6 * mm, 6 * mm, 6 * mm, 30 * mm, 6 * mm]
        style_tbl_accused_details = TableStyle([
            ('VALIGN', (0, 0), (0, 0), 'MIDDLE'),
            ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
            ('SPAN', (0, 0), (0, 1)),
            ('SPAN', (2, 0), (4, 0)),
            ('SPAN', (2, 1), (4, 1)),
        ])
        data = []
        data.append([
            Paragraph('<strong>Accused\'s Details</strong><br />',
                      styles['Normal']),
            Paragraph('Full name', styles['Normal']),  # ,
            Paragraph(get_font_str(offender_full_name), styles['Normal']),
            '',
            '',
        ])
        data.append([
            '',
            Paragraph('Address', styles['Normal']),
            '',
            '',
            '',
        ])
        tbl_accused_details = Table(
            data,
            style=style_tbl_accused_details,
            colWidths=col_width_details,
        )  # rowHeights=rowHeights)

        # Hearing details, etc
        style_tbl_hearing_details = TableStyle([
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
            ('SPAN', (1, 0), (4, 0)),
            ('SPAN', (1, 2), (4, 2)),
        ])
        data = []
        data.append([
            Paragraph('<strong>Hearing details</strong>', styles['Normal']),
            Paragraph(
                'The charge(s) in the attached prosecution notice dated [insert date]<br />will be first dealt with by the above court at the time, date and place stated below.',
                styles['Normal']),
            '',
            '',
            '',
        ])
        data.append([
            Paragraph('<strong>Date and time</strong>', styles['Normal']),
            Paragraph('Date', styles['Normal']),
            Paragraph(get_font_str(court_date_txt), styles['Normal']),
            Paragraph('Time', styles['Normal']),
            Paragraph(get_font_str(court_time_txt), styles['Normal']),
        ])
        data.append([
            Paragraph('<strong>Place</strong>', styles['Normal']),
            Paragraph(get_font_str(court_place_txt), styles['Normal']),
            '',
            '',
            '',
        ])
        tbl_hearing_details = Table(
            data,
            style=style_tbl_hearing_details,
            colWidths=col_width_details,
        )  # rowHeights=rowHeights)

        # Notice to accused
        col_width_notice_to_accused = [
            28 * mm,
            163 * mm,
        ]
        style_tbl_notice_to_accused = TableStyle([
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('VALIGN', (0, 0), (0, -1), 'TOP'),
            ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ])
        data = []
        data.append([
            Paragraph('<strong>Notice to accused</strong>', styles['Normal']),
            Paragraph(
                '<strong>Your options are set out below. You should read them carefully.</strong><br />If you do not know what to do, you should get advice from a lawyer, the Legal Aid Commission or the Aboriginal Legal Service. If you will need an interpreter in court, please contact the court',
                styles['Normal']),
        ])
        data.append([
            Paragraph('<strong>Options</strong>', styles['Normal']),
            Paragraph(
                '1. You can attend the above hearing. <br />'
                '2. You can do nothing. <br />'
                '3. You can plead <u>not guilty</u> in writing. <br />'
                '4. You can plead <u>guilty</u> in writing. <br />'
                '<strong>Options 2, 3 and 4 are explained below.</strong>',
                styles['Normal']),
        ])
        data.append([
            [
                Paragraph('<strong>Doing nothing</strong>', styles['Normal']),
                Spacer(0, 5 * mm),
                Paragraph('<strong>[Options 2]</strong>', styles['Normal']),
            ],
            [
                Paragraph(
                    'If you do not appear at the above hearing and you do not send the court a written plea in time, the court may determine the charge(s) at the above hearing in your absence.',
                    styles['Normal']),
                Paragraph(
                    'In some cases the court can take as proved any allegation in the attached prosecution notice without hearing evidence.',
                    styles['Normal']),
                Paragraph(
                    'The court may decide to summons you to court or have you arrested and brought before the court.',
                    styles['Normal']),
                Paragraph(
                    'If the court finds you guilty, it may fine you and order you to pay court costs and the prosecutor’s costs.',
                    styles['Normal']),
            ],
        ])
        data.append([
            [
                Paragraph('<strong>Pleading not guilty in writing</strong>',
                          styles['Normal']),
                Spacer(0, 5 * mm),
                Paragraph('<strong>[Option 3]</strong>', styles['Normal']),
            ],
            [
                Paragraph(
                    'Pleading <u>not guilty</u> to a charge in the prosecution notice means you do not admit the charge.',
                    styles['Normal']),
                Paragraph(
                    'If you send the court a written plea of <u>not guilty</u>, you need not attend the above hearing. If the court receives your written plea in time it will send you a notice of another hearing, at which the court will deal with the charge(s) (in your absence if you are not there) and hear any evidence you wish to give and any witnesses you call.',
                    styles['Normal']),
                Paragraph(
                    'To send the court a written plea of not guilty, fill out page 2 of this form and send page 2 to the address on it at least three days before the above hearing date.',
                    styles['Normal']),
            ],
        ])
        data.append([
            [
                Paragraph('<strong>Pleading guilty in writing</strong>',
                          styles['Normal']),
                Spacer(0, 5 * mm),
                Paragraph('[Option 4]', styles['Normal']),
            ],
            [
                Paragraph(
                    'Pleading <u>guilty</u> to a charge in the prosecution notice means you admit the charge.',
                    styles['Normal']),
                Paragraph(
                    'If you send the court a written plea of <u>guilty</u>, you need not attend the above hearing unless you want to tell the court something.',
                    styles['Normal']),
                Paragraph(
                    'If the court receives your written plea in time it will deal with the charge(s) at the above hearing (in your absence if you are not there) and may fine you and order you to pay court costs and the prosecutor’s costs.',
                    styles['Normal']),
                Paragraph(
                    'To send the court a written plea of guilty, fill out page 2 of this form, include any written explanation or information you want the court to consider, and send it all to the address on the form at least three days before the above hearing date.',
                    styles['Normal']),
                Paragraph(
                    'The court might not accept your plea of guilty if what you tell the court suggests you do not admit the charge. If that happens you will be notified.',
                    styles['Normal']),
            ],
        ])
        tbl_notice_to_accused = Table(data,
                                      style=style_tbl_notice_to_accused,
                                      colWidths=col_width_notice_to_accused)

        # Issuing details
        col_width_issuing_details = col_width_notice_to_accused
        style_tbl_issuing_details = TableStyle([
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ])
        data = []
        data.append([
            Paragraph('<strong>Issuing details</strong>', styles['Normal']),
            [
                Paragraph('This notice is issued on [date]', styles['Normal']),
                Spacer(0, 8 * mm),
                BrokenLine(50 * mm),
                Paragraph('<i>[Title of person issuing notice]</i>',
                          styles['Normal']),
            ]
        ])
        tbl_issuing_details = Table(data,
                                    style=style_tbl_issuing_details,
                                    colWidths=col_width_issuing_details)

        # Service details
        col_width_service_details = col_width_notice_to_accused
        style_tbl_service_details = TableStyle([
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'), ('SPAN', (0, 0), (0, 1))
        ])
        data = []
        data.append([
            [
                Paragraph('<strong>Service details</strong>',
                          styles['Normal']),
                Spacer(0, 5 * mm),
                Paragraph('[*Police only]', styles['Normal']),
            ],
            Paragraph(
                '<i>[Service must be in one of the manners in the CPA Schedule 2 clauses 2, 3 or 4 (see s. 33(3)). Insert here whichever manner of service was used.]</i>',
                styles['Normal'])
        ])
        tbl_style_internal = TableStyle([
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ])
        data.append([
            '',
            [
                Paragraph(
                    'On' + gap(30) + '20' + gap(10) +
                    ', the accused was served with a copy of this notice and the prosecution notice referred to above in the following manner:',
                    styles['Normal']),
                Table([
                    [
                        Paragraph('Name of server:', styles['Normal']),
                        Paragraph('*Registered No:', styles['Normal'])
                    ],
                    [
                        Paragraph('Signature:', styles['Normal']),
                        Paragraph(gap(1) + 'Station:', styles['Normal'])
                    ],
                ],
                      style=tbl_style_internal,
                      rowHeights=[
                          8 * mm,
                          8 * mm,
                      ])
            ]
        ])
        tbl_service_details = Table(data,
                                    style=style_tbl_service_details,
                                    colWidths=col_width_service_details)

        ###
        # 2nd page
        ###
        # Head (col, row)
        data_left_p2 = Table([[
            Paragraph(
                'MAGISTRATES COURT of WESTERN<br />'
                'AUSTRALIA<br />'
                '<strong><font size="' + str(FONT_SIZE_L) +
                '">WRITTEN PLEA BY ACCUSED</font></strong><br />'
                '<i>Criminal Procedure Act 2004</i><br />'
                'Criminal Procedure Regulations 2005 - Form 5 page 2',
                styles['Centre']),
        ]],
                             style=style_tbl_left,
                             rowHeights=topLeftTableRowHeights)
        data_right_p2 = Table([
            [Paragraph('Court number', styles['Normal']), ''],
            [Paragraph('Magistrates court at', styles['Normal']), ''],
        ],
                              style=style_tbl_right,
                              rowHeights=topRightTableRowHeights)
        tbl_head_p2 = Table(
            [[data_left_p2, '', data_right_p2]],
            style=invoice_table_style,
            colWidths=col_width_head,
        )

        # Accused's Details
        # This is common among the pages

        # Accused's plea
        col_width_p2 = [28 * mm, 28 * mm, 71 * mm, 23 * mm, 41 * mm]
        tbl_style_p2 = (
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('VALIGN', (0, 0), (0, -1), 'TOP'),
            ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
            ('SPAN', (1, 0), (4, 0)),
            ('SPAN', (1, 1), (4, 1)),
            ('SPAN', (1, 2), (4, 2)),
            ('SPAN', (1, 3), (4, 3)),
            ('SPAN', (1, 4), (4, 4)),
            ('SPAN', (1, 5), (4, 5)),
            ('SPAN', (1, 6), (2, 6)),
            ('SPAN', (1, 7), (4, 7)),
            ('SPAN', (0, 5), (0, 6)),
        )
        data = []
        data.append([
            Paragraph('<strong>Accused\'s plea</strong>', styles['Normal']),
            [
                Paragraph(
                    'I have received a prosecution notice dated' + gap(40) +
                    'and a court hearing notice advising me of the hearing on [date]',
                    styles['Normal']),
                Paragraph(
                    'I understand or have had explained to me the charge(s) in the prosecution notice and the contents of the court hearing notice and I understand the effect of this written plea I am sending to the court.',
                    styles['Normal']),
            ],
            '',
            '',
            '',
        ])
        data.append([
            [
                Paragraph('<strong>Plea of guilty</strong>', styles['Normal']),
                Paragraph('[Tick on box]', styles['Normal']),
                Spacer(0, 20 * mm),
                Paragraph('[Tick on box]', styles['Normal']),
            ],
            [
                ParagraphCheckbox(
                    'I plead <u>guilty</u> to the charge(s) in the prosecution notice.',
                    styles['Normal']),
                ParagraphCheckbox(
                    'I plead <u>guilty</u> to the following charges in the prosecution notice.',
                    styles['Normal']),
                Paragraph(
                    '<i>[If the prosecution notice contains more than one charge and you want to plead guilty to only some of them, write the numbers of the charges here.]</i>',
                    styles['Normal']),
                Spacer(0, 8 * mm),
                Paragraph('Attendance at court:', styles['Normal']),
                ParagraphCheckbox(
                    'I will be attending the hearing on the above date.',
                    styles['Normal']),
                ParagraphCheckbox(
                    'I will not be attending the hearing on the above date.',
                    styles['Normal']),
                Paragraph(
                    'I would like the court to take account of the following:',
                    styles['Normal']),
                Paragraph(
                    '<i>[If you are pleading guilty you can (but need not) explain why you committed the offence(s) and give any information that you want the court to consider when deciding what sentence to impose on you.]</i>',
                    styles['Normal']),
                Spacer(0, 10 * mm),
            ],
            '',
            '',
            '',
        ])
        data.append([
            [
                Paragraph('<strong>Plea of not guilty</strong>',
                          styles['Normal']),
                Paragraph('[Tick on box]', styles['Normal']),
                Spacer(0, 20 * mm),
                Paragraph('[Tick on box]', styles['Normal']),
            ],
            [
                ParagraphCheckbox(
                    'I plead not guilty to the charge(s) in the prosecution notice.',
                    styles['Normal']),
                ParagraphCheckbox(
                    'I plead not guilty to the following charges in the prosecution notice.',
                    styles['Normal']),
                Paragraph(
                    '<i>[If the prosecution notice contains more than one charge and you want to plead not guilty to only some of them, write the numbers of them here]</i>',
                    styles['Normal']),
                Spacer(0, 8 * mm),
                Paragraph('Attendance at court:', styles['Normal']),
                ParagraphCheckbox(
                    'I will be attending the hearing on the above date.',
                    styles['Normal']),
                ParagraphCheckbox(
                    'I will not be attending the hearing on the above date.',
                    styles['Normal']),
                Paragraph(
                    'At the trial of the charge(s) I intend to call' +
                    gap(40) + 'witnesses (including myself).',
                    styles['Normal']),
                Paragraph(
                    '<i>[Please insert the number of witnesses to assist the court in deciding how long the trial might last]</i>',
                    styles['Normal']),
                Paragraph(
                    'When setting a date for the trial please take account of the following:',
                    styles['Normal']),
                Paragraph(
                    '<i>[Please provide any information that might assist the court when setting the date for the trial such as dates when you will be overseas or in hospital.]</i>',
                    styles['Normal']),
                Spacer(0, 10 * mm),
            ],
            '',
            '',
            '',
        ])
        data.append([
            Paragraph('<strong>Contact details</strong>', styles['Normal']),
            [
                Paragraph('My contact details are:', styles['Normal']),
                Spacer(0, 2 * mm),
                Paragraph('Address (if different to the one above):',
                          styles['Normal']),
                Spacer(0, 2 * mm),
                Paragraph(
                    'Telephone no.' + gap(40) + 'Fax no.' + gap(40) +
                    'Mobile no.', styles['Normal']),
            ],
            '',
            '',
            '',
        ])
        data.append([
            [
                Paragraph('<strong>Lawyer\'s details</strong>',
                          styles['Normal']),
                Paragraph('[If a lawyer will appear for you]',
                          styles['Normal']),
            ],
            [
                Paragraph('Name:', styles['Normal']),
                Paragraph('Firm name', styles['Normal']),
            ],
            '',
            '',
            '',
        ])
        data.append([
            Paragraph('<strong>Accused\'s signature</strong>',
                      styles['Normal']),
            Paragraph(
                '<i>This may be signed by the accused’s lawyer or, if the accused is a corporation, made in accordance with the Criminal Procedure Act 2004 section 154(1).</i>',
                styles['Normal']),
            '',
            '',
            '',
        ])
        data.append([
            '',
            '',
            '',
            Paragraph('Date', styles['Normal']),
            '',
        ])
        data.append([
            Paragraph('<strong>Court address</strong>', styles['Normal']),
            [
                Paragraph('Send this document to:', styles['Normal']),
                Spacer(0, 2 * mm),
                Paragraph('at:', styles['Normal']),
                Spacer(0, 2 * mm),
            ],
            '',
            '',
            '',
        ])
        tbl_main_p2 = Table(
            data,
            style=tbl_style_p2,
            colWidths=col_width_p2,
        )

        ###
        # 3rd page
        ###
        header_small_text_p3 = ParagraphOffeset(
            '<font size="' + str(FONT_SIZE_S) +
            '">Copy to be attached to accused copy of prosecution notice</font>',
            styles['Right'],
            x_offset=-3 * mm,
            y_offset=0)

        ###
        # 4th page
        ###
        # Same as 2nd page

        ###
        # 5th page
        ###
        header_small_text_p5 = ParagraphOffeset(
            '<font size="' + str(FONT_SIZE_S) +
            '">Return of service copy</font>',
            styles['Right'],
            x_offset=-3 * mm,
            y_offset=0)

        ###
        # 6th page
        ###

        gap_between_tables = 1.5 * mm
        odd_page = []
        odd_page.append(tbl_head)
        odd_page.append(tbl_accused_details)
        odd_page.append(Spacer(0, gap_between_tables))
        odd_page.append(tbl_hearing_details)
        odd_page.append(Spacer(0, gap_between_tables))
        odd_page.append(tbl_notice_to_accused)
        odd_page.append(Spacer(0, gap_between_tables))
        odd_page.append(tbl_issuing_details)
        odd_page.append(Spacer(0, gap_between_tables))
        odd_page.append(tbl_service_details)
        even_page = []
        even_page.append(tbl_head_p2)
        even_page.append(tbl_accused_details)
        even_page.append(Spacer(0, gap_between_tables))
        even_page.append(tbl_main_p2)

        # 1st page
        elements.append(header_small_text_p1)
        elements += odd_page
        elements.append(PageBreak())
        # 2nd page
        elements += even_page
        elements.append(PageBreak())
        # 3rd page
        elements.append(header_small_text_p3)
        elements += odd_page
        elements.append(PageBreak())
        # 4th page
        elements += even_page
        elements.append(PageBreak())
        # 5th page
        elements.append(header_small_text_p5)
        elements += odd_page
        elements.append(PageBreak())
        # 6th page
        elements += even_page

    doc.build(elements)
    return invoice_buffer
Ejemplo n.º 28
0
def _create_pdf(invoice_buffer, legal_case,
                brief_of_evidence_record_of_interviews):
    every_page_frame = Frame(
        PAGE_MARGIN,
        PAGE_MARGIN,
        PAGE_WIDTH - 2 * PAGE_MARGIN,
        PAGE_HEIGHT - 2 * PAGE_MARGIN,
        id='EveryPagesFrame',
    )  #showBoundary=Color(0, 1, 0))
    every_page_template = PageTemplate(
        id='EveryPages',
        frames=[
            every_page_frame,
        ],
    )
    doc = BaseDocTemplate(
        invoice_buffer,
        pageTemplates=[
            every_page_template,
        ],
        pagesize=A4,
    )  # showBoundary=Color(1, 0, 0))

    # Common
    col_width_head = [
        85 * mm,
        25 * mm,
        85 * mm,
    ]
    col_width_details = [27 * mm, 27 * mm, 71 * mm, 30 * mm, 36 * mm]
    col_width_for_court = [
        27 * mm, 24 * mm, 18 * mm, 58 * mm, 47 * mm, 17 * mm
    ]
    FONT_SIZE_L = 11
    FONT_SIZE_M = 10
    FONT_SIZE_S = 8

    styles = StyleSheet1()
    styles.add(
        ParagraphStyle(
            name='Normal',
            fontName='Helvetica',
            fontSize=FONT_SIZE_M,
            spaceBefore=7,  # space before paragraph
            spaceAfter=7,  # space after paragraph
            leading=12))  # space between lines
    styles.add(
        ParagraphStyle(name='BodyText', parent=styles['Normal'],
                       spaceBefore=6))
    styles.add(
        ParagraphStyle(name='Italic',
                       parent=styles['BodyText'],
                       fontName='Helvetica-Italic'))
    styles.add(
        ParagraphStyle(name='Bold',
                       parent=styles['BodyText'],
                       fontName='Helvetica-Bold',
                       alignment=TA_CENTER))
    styles.add(
        ParagraphStyle(name='Right',
                       parent=styles['BodyText'],
                       alignment=TA_RIGHT))
    styles.add(
        ParagraphStyle(name='Centre',
                       parent=styles['BodyText'],
                       alignment=TA_CENTER))
    elements = []
    for boe in brief_of_evidence_record_of_interviews:
        offender = boe.offender.person
        offence = boe.offence
        if not offender or not offence:
            continue

        # Generate texts
        accused_text = offender.get_full_name()
        accused_dob_text = offender.dob.strftime(
            '%d/%m/%Y') if offender.dob else ''
        accused_address_text = offender.residential_address
        offence_period = offence.occurrence_datetime_from.strftime("%d/%m/%Y")
        if offence.occurrence_from_to:
            offence_period += ' to ' + offence.occurrence_datetime_to.strftime(
                "%d/%m/%Y")
        offence_place = str(offence.location)
        offence_description = offence.details

        # Head (col, row)
        invoice_table_style = TableStyle([
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ('GRID', (0, 0), (-1, -1), 0, colors.white),
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ])
        style_tbl_left = TableStyle([
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ])
        style_tbl_right = TableStyle([
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ])
        data_left = Table([[
            Paragraph(
                'MAGISTRATES COURT of WESTERN<br />'
                'AUSTRALIA<br />'
                '<strong><font size="' + str(FONT_SIZE_L) +
                '">PROSECUTION NOTICE</font></strong><br />'
                '<i>Criminal Procedure Act 2004</i><br />'
                'Criminal Procedure Regulations 2005 - Form 3',
                styles['Centre']),
        ]],
                          style=style_tbl_left)
        data_right = Table([
            [Paragraph('Court number', styles['Normal']), ''],
            [Paragraph('Magistrates court at', styles['Normal']), ''],
            [Paragraph('Date lodged', styles['Normal']), ''],
        ],
                           style=style_tbl_right,
                           rowHeights=[
                               7.8 * mm,
                               7.8 * mm,
                               7.8 * mm,
                           ])
        tbl_head = Table(
            [[data_left, '', data_right]],
            style=invoice_table_style,
            colWidths=col_width_head,
        )

        # Details of alleged offence
        rowHeights = [6 * mm, 6 * mm, 6 * mm, 30 * mm, 6 * mm]
        style_tbl_details = TableStyle([
            ('VALIGN', (0, 0), (0, 0), 'TOP'),
            ('VALIGN', (1, 0), (-1, -1), 'MIDDLE'),
            ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
            ('SPAN', (0, 0), (0, 4)),
            ('SPAN', (2, 0), (4, 0)),
            ('SPAN', (2, 1), (4, 1)),
            ('SPAN', (2, 2), (4, 2)),
            ('SPAN', (2, 3), (4, 3)),
            ('SPAN', (2, 4), (4, 4)),
        ])

        data = []
        data.append([
            Paragraph(
                '<strong>Details of alleged offence</strong><br />'
                '<i><font size="' + str(FONT_SIZE_S) +
                '">[This description must comply with the CPA Schedule 1 clause 5.]</font></i>',
                styles['Normal']),
            Paragraph('Accused', styles['Normal']),
            Paragraph(get_font_str(accused_text), styles['Normal']),
            '',
            '',
        ])
        data.append([
            '',
            Paragraph('Date or period', styles['Normal']),
            Paragraph(get_font_str(offence_period), styles['Normal']), '', ''
        ])
        data.append([
            '',
            Paragraph('Place', styles['Normal']),
            Paragraph(get_font_str(offence_place), styles['Normal']), '', ''
        ])
        data.append([
            '',
            Paragraph('Description', styles['Normal']),
            Paragraph(get_font_str(offence_description), styles['Normal']), '',
            ''
        ])
        data.append(
            ['', Paragraph('Written law', styles['Normal']), '', '', ''])
        tbl_details = Table(data,
                            style=style_tbl_details,
                            colWidths=col_width_details,
                            rowHeights=rowHeights)

        # Notice to accused
        style_tbl_notice = TableStyle([
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
            ('SPAN', (1, 0), (4, 0)),
        ])
        data = []
        data.append([
            Paragraph('<strong>Notice to accused</strong>', styles['Normal']),
            Paragraph(
                'You are charged with the offence described above, or the offences described in any attachment to this notice. The charge(s) will be dealt with by the above court.',
                styles['Normal']),
            '',
            '',
            '',
        ])
        tbl_notice = Table(data,
                           style=style_tbl_notice,
                           colWidths=col_width_details)

        # Accused's Details
        rowHeights = [4.5 * mm, 6 * mm, 6 * mm]
        style_tbl_accused = TableStyle([
            ('VALIGN', (0, 0), (0, -1), 'TOP'),
            ('VALIGN', (1, 0), (-1, -1), 'MIDDLE'),
            ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
            ('SPAN', (0, 0), (0, 2)),
            ('SPAN', (1, 0), (4, 0)),
            ('SPAN', (3, 1), (4, 1)),
            ('SPAN', (2, 2), (4, 2)),
        ])
        data = []
        data.append([
            Paragraph('<strong>Accused\'s Details</strong>', styles['Normal']),
            Paragraph(
                '<i><font size="' + str(FONT_SIZE_S) +
                '">[This description must comply with the CPA Schedule 1 clause 4.]</font></i>',
                styles['Normal']),
            '',
            '',
            '',
        ])
        data.append([
            '',
            Paragraph('Date of Birth', styles['Normal']),
            Paragraph(get_font_str(accused_dob_text), styles['Normal']),
            Paragraph('Male / Female', styles['Normal']),
            '',
        ])
        data.append([
            '',
            Paragraph('Address', styles['Normal']),
            Paragraph(get_font_str(accused_address_text), styles['Normal']),
            '',
            '',
        ])
        tbl_accused = Table(data,
                            style=style_tbl_accused,
                            colWidths=col_width_details,
                            rowHeights=rowHeights)

        # Prosecutor
        rowHeights = [
            4.5 * mm, 6 * mm, 6 * mm, 6 * mm, 15 * mm, 4.5 * mm, 15 * mm,
            6 * mm
        ]
        style_tbl_prosecutor = TableStyle([
            ('VALIGN', (0, 0), (0, -1), 'TOP'),
            ('VALIGN', (1, 0), (-1, -1), 'MIDDLE'),
            ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
            ('VALIGN', (2, 6), (-1, 6), 'BOTTOM'),
            ('SPAN', (0, 0), (0, 1)),  # col: Prosecutor
            ('SPAN', (0, 2), (0, 6)),  # col: Person issuing this notice
            ('SPAN', (1, 5), (1, 6)),  # col: Witness's signature
            ('SPAN', (1, 0), (4, 0)),
            ('SPAN', (1, 1), (4, 1)),
            ('SPAN', (2, 4), (4, 4)),
            ('SPAN', (2, 5), (4, 5)),
            ('SPAN', (2, 6), (4, 6)),
            ('SPAN', (1, 7), (4, 7)),
        ])
        data = []
        data.append([
            Paragraph('<strong>Prosecutor</strong>', styles['Normal']),
            Paragraph(
                '<i><font size="' + str(FONT_SIZE_S) +
                '">[Identify the prosecutor in accordance with the CPA Schedule 1 clause 3.]</font></i>',
                styles['Normal']),
            '',
            '',
            '',
        ])
        data.append([
            '',
            '',
            '',
            '',
            '',
        ])
        data.append([
            Paragraph('<strong>Person issuing this notice</strong>',
                      styles['Normal']),
            Paragraph('Full name', styles['Normal']),
            '',
            Paragraph('official title', styles['Normal']),
            '',
        ])
        data.append([
            '',
            Paragraph('Work address', styles['Normal']),
            '',
            Paragraph('Work telephone', styles['Normal']),
            '',
        ])
        data.append([
            '',
            Paragraph('Signature', styles['Normal']),
            '',
            '',
            '',
        ])
        data.append([
            '',
            Paragraph('Witness\'s Signature', styles['Normal']),
            Paragraph(
                '<i><font size="' + str(FONT_SIZE_S) +
                '">[A witness may not be needed. See the CPA section 23.]</font></i>',
                styles['Normal']),
            '',
            '',
        ])
        data.append([
            '',
            '',
            Paragraph(
                '<font size="' + str(FONT_SIZE_S) +
                '">Justice of the Peace or Prescribed Court Officer</font>',
                styles['Normal']),
            '',
            '',
        ])
        data.append([
            Paragraph('<strong>Date</strong>', styles['Normal']),
            Paragraph('This prosecution notice is signed on',
                      styles['Normal']),
            '',
            '',
            '',
        ])
        tbl_prosecutor = Table(data,
                               style=style_tbl_prosecutor,
                               colWidths=col_width_details,
                               rowHeights=rowHeights)

        # For Court Use Only
        rowHeights_court = [
            6 * mm, 10 * mm, 6 * mm, 6 * mm, 6 * mm, 6 * mm, 6 * mm, 6 * mm,
            6 * mm, 6 * mm, 23 * mm, 17 * mm
        ]
        style_tbl_for_court = TableStyle([
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('VALIGN', (3, 11), (5, 11), 'BOTTOM'),
            ('VALIGN', (0, 10), (2, 11), 'TOP'),
            ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
            ('SPAN', (0, 0), (5, 0)),
            ('SPAN', (3, 1), (4, 1)),
            ('SPAN', (3, 2), (4, 2)),
            ('SPAN', (3, 3), (4, 3)),
            ('SPAN', (3, 4), (4, 4)),
            ('SPAN', (3, 5), (4, 5)),
            ('SPAN', (3, 6), (4, 6)),
            ('SPAN', (1, 7), (2, 7)),  # Guilty / not guilty
            ('SPAN', (1, 8), (2, 8)),
            ('SPAN', (1, 9), (2, 9)),  # Convicted / acquitted
            ('SPAN', (3, 7), (5, 10)),  # Penalty and other orders
            ('SPAN', (4, 11), (5, 11)),
            ('SPAN', (0, 10), (2, 11)),  # <== This has a bug...?
        ])
        data = []
        data.append([
            Paragraph('<i>For Court User Only</i>', styles['Bold']), '', '',
            '', '', ''
        ])
        data.append([
            Paragraph('Date', styles['Centre']),
            Paragraph('Appearance by accused', styles['Centre']),
            Paragraph('Counsel', styles['Centre']),
            Paragraph('Record of court proceedings', styles['Centre']),
            '',
            Paragraph('Judicial officer', styles['Centre']),
        ])
        data.append(['', Paragraph('Y / N', styles['Bold']), '', '', '', ''])
        data.append(['', Paragraph('Y / N', styles['Bold']), '', '', '', ''])
        data.append(['', Paragraph('Y / N', styles['Bold']), '', '', '', ''])
        data.append(['', Paragraph('Y / N', styles['Bold']), '', '', '', ''])
        data.append(['', Paragraph('Y / N', styles['Bold']), '', '', '', ''])
        data.append([
            Paragraph('Plea', styles['Bold']),
            Paragraph('Guilty / not guilty', styles['Bold']),
            '',
            [
                Paragraph('Penalty and other orders', styles['Centre']),
                Paragraph('<strong>Fine</strong>', styles['Normal']),
                Paragraph('<strong>Costs</strong>', styles['Normal']),
                Paragraph('<strong>Other</strong>', styles['Normal'])
            ],
            '',
            '',
        ])
        data.append([
            Paragraph('Date of plea', styles['Bold']),
            '',
            '',
            '',
            '',
            '',
        ])
        data.append([
            Paragraph('<strong>Judgement</strong>', styles['Centre']),
            Paragraph('<strong>Conficted / acquitted</strong>',
                      styles['Centre']),
            '',
            '',
            '',
            '',
        ])
        data.append([
            Paragraph('<strong>Victim impact statement available</strong>',
                      styles['Centre']), '', '', '', '', ''
        ])
        data.append([
            '',
            '',
            '',
            Paragraph('<strong>Judicial officer</strong>', styles['Centre']),
            Paragraph('<strong>Date:</strong>', styles['Normal']),
            '',
        ])
        tbl_for_court = Table(data,
                              style=style_tbl_for_court,
                              colWidths=col_width_for_court,
                              rowHeights=rowHeights_court)

        #############
        # PageBreak #
        #############

        # Court Number
        rowHeights = [
            10 * mm,
        ]
        col_width_court_number = [
            30 * mm,
            70 * mm,
        ]
        style_tbl_for_court_number = TableStyle([
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
        ])
        data = []
        data.append([Paragraph('Court number', styles['Normal']), ''])
        tbl_for_court_number = OffsetTable(data,
                                           x_offset=45.5 * mm,
                                           style=style_tbl_for_court_number,
                                           colWidths=col_width_court_number,
                                           rowHeights=rowHeights)

        # Table above
        style_array = [
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
        ]
        for row_num in range(0, 29):
            style_array.append(('SPAN', (3, row_num), (4, row_num)))
        style_tbl_above = TableStyle(style_array)
        data = []
        data.append([
            Paragraph('Date', styles['Centre']),
            Paragraph('Appearance by accused', styles['Centre']),
            Paragraph('Counsel', styles['Centre']),
            Paragraph('Record of court proceedings', styles['Centre']),
            '',
            Paragraph('Judicial officer', styles['Centre']),
        ])
        for row_num in range(0, 28):
            data.append([
                '',
                Paragraph('<strong>Y / N</strong>', styles['Centre']), '', '',
                '', ''
            ])
        tbl_above = Table(data,
                          style=style_tbl_above,
                          colWidths=col_width_for_court)

        # Table below
        style_array = [
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
        ]
        for row_num in range(0, 8):
            style_array.append(('SPAN', (2, row_num), (5, row_num)))
        style_tbl_below = TableStyle(style_array)
        data = []
        data.append([
            Paragraph('Date', styles['Centre']),
            Paragraph('Clerk\'s Initial', styles['Centre']),
            Paragraph('Registry record', styles['Centre']),
            '',
            '',
            '',
        ])
        for row_num in range(0, 7):
            data.append(['', '', '', '', '', ''])
        tbl_below = Table(data,
                          style=style_tbl_below,
                          colWidths=col_width_for_court,
                          rowHeights=8.5 * mm)

        # Append tables to the elements to build
        gap_between_tables = 1.5 * mm
        elements.append(tbl_head)
        elements.append(tbl_details)
        elements.append(Spacer(0, gap_between_tables))
        elements.append(tbl_notice)
        elements.append(Spacer(0, gap_between_tables))
        elements.append(tbl_accused)
        elements.append(Spacer(0, gap_between_tables))
        elements.append(tbl_prosecutor)
        elements.append(Spacer(0, gap_between_tables))
        elements.append(tbl_for_court)
        elements.append(PageBreak())
        elements.append(tbl_for_court_number)
        elements.append(Spacer(0, gap_between_tables))
        elements.append(tbl_above)
        elements.append(Spacer(0, gap_between_tables))
        elements.append(tbl_below)

    doc.build(elements)
    return invoice_buffer
Ejemplo n.º 29
0
    def build_pdf(self, response):

        cleaned_data = self.filterset.form.cleaned_data

        impresso = cleaned_data['impresso']

        fs = int(impresso.fontsize)
        if cleaned_data['fontsize']:
            fs = int(cleaned_data['fontsize'])

        stylesheet = StyleSheet1()
        stylesheet.add(
            ParagraphStyle(name='pronome_style',
                           fontName="Helvetica",
                           fontSize=fs * 0.8,
                           leading=fs))
        stylesheet.add(
            ParagraphStyle(name='nome_style',
                           fontName="Helvetica-Bold",
                           fontSize=fs,
                           leading=fs * 1.3))
        stylesheet.add(
            ParagraphStyle(name='endereco_style',
                           fontName="Helvetica",
                           fontSize=fs * 0.9,
                           leading=fs))

        pagesize = (float(impresso.largura_pagina) * cm,
                    float(impresso.altura_pagina) * cm)

        ms = pagesize[1] - float(impresso.margem_superior) * cm
        me = float(impresso.margem_esquerda) * cm

        ae = float(impresso.alturaetiqueta) * cm
        le = float(impresso.larguraetiqueta) * cm

        el = float(impresso.entre_linhas) * cm
        ec = float(impresso.entre_colunas) * cm

        col = float(impresso.colunasfolha)
        row = float(impresso.linhasfolha)
        cr = int(col * row)

        p = canvas.Canvas(response, pagesize=pagesize)

        if impresso.rotate:
            p.translate(pagesize[1], 0)
            p.rotate(90)

        i = -1
        for contato in self.object_list.all():
            i += 1
            if i != 0 and i % cr == 0:
                p.showPage()

                if impresso.rotate:
                    p.translate(pagesize[1], 0)
                    p.rotate(90)

            q = floor(i / col) % row
            r = i % int(col)

            l = me + r * ec + r * le
            b = ms - (q + 1) * ae - q * el

            f = Frame(l,
                      b,
                      le,
                      ae,
                      leftPadding=fs / 3,
                      bottomPadding=fs / 3,
                      topPadding=fs / 3,
                      rightPadding=fs / 3,
                      showBoundary=0)
            # f.drawBoundary(p)
            f.addFromList(self.createParagraphs(contato, stylesheet), p)

        p.showPage()
        p.save()
Ejemplo n.º 30
0
    def __init__(self, flist, font_path=None, style_path=None, def_dpi=300):
        log.info('Using stylesheets: %s' % ','.join(flist))
        # find base path
        if hasattr(sys, 'frozen'):
            self.PATH = abspath(dirname(sys.executable))
        else:
            self.PATH = abspath(dirname(__file__))

        # flist is a list of stylesheet filenames.
        # They will be loaded and merged in order.
        # but the two default stylesheets will always
        # be loaded first
        flist = [
            join(self.PATH, 'styles', 'styles.style'),
            join(self.PATH, 'styles', 'default.style')
        ] + flist

        self.def_dpi = def_dpi
        if font_path is None:
            font_path = []
        font_path += ['.', os.path.join(self.PATH, 'fonts')]
        self.FontSearchPath = list(map(os.path.expanduser, font_path))

        if style_path is None:
            style_path = []
        style_path += [
            '.', os.path.join(self.PATH, 'styles'), '~/.rst2pdf/styles'
        ]
        self.StyleSearchPath = list(map(os.path.expanduser, style_path))

        # Remove duplicates but preserve order. Not very efficient, but these are short lists
        self.FontSearchPath = [x for (i,x) in enumerate(self.FontSearchPath) if self.FontSearchPath.index(x) == i]
        self.StyleSearchPath = [x for (i,x) in enumerate(self.StyleSearchPath) if self.StyleSearchPath.index(x) == i]

        log.info('FontPath:%s' % self.FontSearchPath)
        log.info('StylePath:%s' % self.StyleSearchPath)

        findfonts.flist = self.FontSearchPath
        # Page width, height
        self.pw = 0
        self.ph = 0

        # Page size [w,h]
        self.ps = None

        # Margins (top,bottom,left,right,gutter)
        self.tm = 0
        self.bm = 0
        self.lm = 0
        self.rm = 0
        self.gm = 0

        # text width
        self.tw = 0

        # Default emsize, later it will be the fontSize of the base style
        self.emsize = 10

        self.languages = []

        ssdata = self.readSheets(flist)

        # Get pageSetup data from all stylessheets in order:
        self.ps = pagesizes.A4
        self.page = {}
        for data, ssname in ssdata:
            page = data.get('pageSetup', {})
            if page:
                self.page.update(page)
                pgs = page.get('size', None)
                if pgs:  # A standard size
                    pgs = pgs.upper()
                    if pgs in pagesizes.__dict__:
                        self.ps = list(pagesizes.__dict__[pgs])
                        self.psname = pgs
                        if 'width' in self.page:
                            del(self.page['width'])
                        if 'height' in self.page:
                            del(self.page['height'])
                    elif pgs.endswith('-LANDSCAPE'):
                        self.psname = pgs.split('-')[0]
                        self.ps = list(pagesizes.landscape(pagesizes.__dict__[self.psname]))
                        if 'width' in self.page:
                            del(self.page['width'])
                        if 'height' in self.page:
                            del(self.page['height'])
                    else:
                        log.critical('Unknown page size %s in stylesheet %s' %
                                     (page['size'], ssname))
                        continue
                else:  # A custom size
                    if 'size'in self.page:
                        del(self.page['size'])
                    # The sizes are expressed in some unit.
                    # For example, 2cm is 2 centimeters, and we need
                    # to do 2*cm (cm comes from reportlab.lib.units)
                    if 'width' in page:
                        self.ps[0] = self.adjustUnits(page['width'])
                    if 'height' in page:
                        self.ps[1] = self.adjustUnits(page['height'])
                self.pw, self.ph = self.ps
                if 'margin-left' in page:
                    self.lm = self.adjustUnits(page['margin-left'])
                if 'margin-right' in page:
                    self.rm = self.adjustUnits(page['margin-right'])
                if 'margin-top' in page:
                    self.tm = self.adjustUnits(page['margin-top'])
                if 'margin-bottom' in page:
                    self.bm = self.adjustUnits(page['margin-bottom'])
                if 'margin-gutter' in page:
                    self.gm = self.adjustUnits(page['margin-gutter'])
                if 'spacing-header' in page:
                    self.ts = self.adjustUnits(page['spacing-header'])
                if 'spacing-footer' in page:
                    self.bs = self.adjustUnits(page['spacing-footer'])
                if 'firstTemplate' in page:
                    self.firstTemplate = page['firstTemplate']

                # tw is the text width.
                # We need it to calculate header-footer height
                # and compress literal blocks.
                self.tw = self.pw - self.lm - self.rm - self.gm

        # Get page templates from all stylesheets
        self.pageTemplates = {}
        for data, ssname in ssdata:
            templates = data.get('pageTemplates', {})
            # templates is a dictionary of pageTemplates
            for key in templates:
                template = templates[key]
                # template is a dict.
                # template[´frames'] is a list of frames
                if key in self.pageTemplates:
                    self.pageTemplates[key].update(template)
                else:
                    self.pageTemplates[key] = template

        # Get font aliases from all stylesheets in order
        self.fontsAlias = {}
        for data, ssname in ssdata:
            self.fontsAlias.update(data.get('fontsAlias', {}))

        embedded_fontnames = []
        self.embedded = []
        # Embed all fonts indicated in all stylesheets
        for data, ssname in ssdata:
            embedded = data.get('embeddedFonts', [])

            for font in embedded:
                try:
                    # Just a font name, try to embed it
                    if isinstance(font, six.string_types):
                        # See if we can find the font
                        fname, pos = findfonts.guessFont(font)
                        if font in embedded_fontnames:
                            pass
                        else:
                            fontList = findfonts.autoEmbed(font)
                            if fontList:
                                embedded_fontnames.append(font)
                        if not fontList:
                            if (fname, pos) in embedded_fontnames:
                                fontList = None
                            else:
                                fontList = findfonts.autoEmbed(fname)
                        if fontList is not None:
                            self.embedded += fontList
                            # Maybe the font we got is not called
                            # the same as the one we gave
                            # so check that out
                            suff = ["", "-Oblique", "-Bold", "-BoldOblique"]
                            if not fontList[0].startswith(font):
                                # We need to create font aliases, and use them
                                for fname, aliasname in zip(
                                        fontList,
                                        [font + suffix for suffix in suff]):
                                    self.fontsAlias[aliasname] = fname
                        continue

                    # Each "font" is a list of four files, which will be
                    # used for regular / bold / italic / bold+italic
                    # versions of the font.
                    # If your font doesn't have one of them, just repeat
                    # the regular font.

                    # Example, using the Tuffy font from
                    # http://tulrich.com/fonts/
                    # "embeddedFonts" : [
                    #                    ["Tuffy.ttf",
                    #                     "Tuffy_Bold.ttf",
                    #                     "Tuffy_Italic.ttf",
                    #                     "Tuffy_Bold_Italic.ttf"]
                    #                   ],

                    # The fonts will be registered with the file name,
                    # minus the extension.

                    if font[0].lower().endswith('.ttf'):  # A True Type font
                        for variant in font:
                            location = self.findFont(variant)
                            pdfmetrics.registerFont(
                                TTFont(str(variant.split('.')[0]), location))
                            log.info('Registering font: %s from %s' % (str(
                                variant.split('.')[0]), location))
                            self.embedded.append(str(variant.split('.')[0]))

                        # And map them all together
                        regular, bold, italic, bolditalic = [
                            variant.split('.')[0] for variant in font]
                        addMapping(regular, 0, 0, regular)
                        addMapping(regular, 0, 1, italic)
                        addMapping(regular, 1, 0, bold)
                        addMapping(regular, 1, 1, bolditalic)
                    else:  # A Type 1 font
                        # For type 1 fonts we require
                        # [FontName,regular,italic,bold,bolditalic]
                        # where each variant is a (pfbfile,afmfile) pair.
                        # For example, for the URW palladio from TeX:
                        # ["Palatino",("uplr8a.pfb","uplr8a.afm"),
                        #             ("uplri8a.pfb","uplri8a.afm"),
                        #             ("uplb8a.pfb","uplb8a.afm"),
                        #             ("uplbi8a.pfb","uplbi8a.afm")]
                        regular = pdfmetrics.EmbeddedType1Face(*font[1])
                        italic = pdfmetrics.EmbeddedType1Face(*font[2])
                        bold = pdfmetrics.EmbeddedType1Face(*font[3])
                        bolditalic = pdfmetrics.EmbeddedType1Face(*font[4])

                except Exception as e:
                    try:
                        if isinstance(font, list):
                            fname = font[0]
                        else:
                            fname = font
                        log.error("Error processing font %s: %s",
                                  os.path.splitext(fname)[0], str(e))
                        log.error("Registering %s as Helvetica alias", fname)
                        self.fontsAlias[fname] = 'Helvetica'
                    except Exception as e:
                        log.critical("Error processing font %s: %s", fname,
                                     str(e))
                        continue

        # Go though all styles in all stylesheets and find all fontNames.
        # Then decide what to do with them
        for data, ssname in ssdata:
            for [skey, style] in self.stylepairs(data):
                for key in style:
                    if key == 'fontName' or key.endswith('FontName'):
                        # It's an alias, replace it
                        if style[key] in self.fontsAlias:
                            style[key] = self.fontsAlias[style[key]]
                        # Embedded already, nothing to do
                        if style[key] in self.embedded:
                            continue
                        # Standard font, nothing to do
                        if style[key] in (
                                    "Courier",
                                    "Courier-Bold",
                                    "Courier-BoldOblique",
                                    "Courier-Oblique",
                                    "Helvetica",
                                    "Helvetica-Bold",
                                    "Helvetica-BoldOblique",
                                    "Helvetica-Oblique",
                                    "Symbol",
                                    "Times-Bold",
                                    "Times-BoldItalic",
                                    "Times-Italic",
                                    "Times-Roman",
                                    "ZapfDingbats"):
                            continue
                        # Now we need to do something
                        # See if we can find the font
                        fname, pos = findfonts.guessFont(style[key])

                        if style[key] in embedded_fontnames:
                            pass
                        else:
                            fontList = findfonts.autoEmbed(style[key])
                            if fontList:
                                embedded_fontnames.append(style[key])
                        if not fontList:
                            if (fname, pos) in embedded_fontnames:
                                fontList = None
                            else:
                                fontList = findfonts.autoEmbed(fname)
                            if fontList:
                                embedded_fontnames.append((fname, pos))
                        if fontList:
                            self.embedded += fontList
                            # Maybe the font we got is not called
                            # the same as the one we gave so check that out
                            suff = ["", "-Bold", "-Oblique", "-BoldOblique"]
                            if not fontList[0].startswith(style[key]):
                                # We need to create font aliases, and use them
                                basefname = style[key].split('-')[0]
                                for fname, aliasname in zip(
                                        fontList,
                                        [basefname + suffix for suffix in suff]):
                                    self.fontsAlias[aliasname] = fname
                                style[key] = self.fontsAlias[basefname +
                                                             suff[pos]]
                        else:
                            log.error("Unknown font: \"%s\","
                                      "replacing with Helvetica", style[key])
                            style[key] = "Helvetica"

        # Get styles from all stylesheets in order
        self.stylesheet = {}
        self.styles = []
        self.linkColor = 'navy'
        # FIXME: linkColor should probably not be a global
        #        style, and tocColor should probably not
        #        be a special case, but for now I'm going
        #        with the flow...
        self.tocColor = None
        for data, ssname in ssdata:
            self.linkColor = data.get('linkColor') or self.linkColor
            self.tocColor = data.get('tocColor') or self.tocColor
            for [skey, style] in self.stylepairs(data):
                sdict = {}
                # FIXME: this is done completely backwards
                for key in style:
                    # Handle color references by name
                    if key == 'color' or key.endswith('Color') and style[key]:
                        style[key] = formatColor(style[key])
                    elif key == 'commands':
                        style[key] = validateCommands(style[key])

                    # Handle alignment constants
                    elif key == 'alignment':
                        style[key] = dict(TA_LEFT=0,
                                          LEFT=0,
                                          TA_CENTER=1,
                                          CENTER=1,
                                          TA_CENTRE=1,
                                          CENTRE=1,
                                          TA_RIGHT=2,
                                          RIGHT=2,
                                          TA_JUSTIFY=4,
                                          JUSTIFY=4,
                                          DECIMAL=8, )[style[key].upper()]

                    elif key == 'language':
                        if not style[key] in self.languages:
                            self.languages.append(style[key])

                    sdict[key] = style[key]
                    sdict['name'] = skey
                # If the style already exists, update it
                if skey in self.stylesheet:
                    self.stylesheet[skey].update(sdict)
                else:  # New style
                    self.stylesheet[skey] = sdict
                    self.styles.append(sdict)

        # If the stylesheet has a style name docutils won't reach
        # make a copy with a sanitized name.
        # This may make name collisions possible but that should be
        # rare (who would have custom_name and custom-name in the
        # same stylesheet? ;-)
        # Issue 339

        styles2 = []
        for s in self.styles:
            if not re.match("^[a-z](-?[a-z0-9]+)*$", s['name']):
                s2 = copy(s)
                s2['name'] = docutils.nodes.make_id(s['name'])
                log.warning(
                    '%s is an invalid docutils class name, adding alias %s' %
                    (s['name'], s2['name']))
                styles2.append(s2)
        self.styles.extend(styles2)

        # And create  reportlabs stylesheet
        self.StyleSheet = StyleSheet1()

        dirty = True
        while dirty:
            dirty = False
            for s in self.styles:
                if s['name'] in self.StyleSheet:
                    continue
                try:
                    if 'parent' in s:
                        if s['parent'] is None:
                            if s['name'] != 'base':
                                s['parent'] = self.StyleSheet['base']
                            else:
                                del(s['parent'])
                        else:
                            s['parent'] = self.StyleSheet[s['parent']]
                    else:
                        if s['name'] != 'base':
                            s['parent'] = self.StyleSheet['base']
                except KeyError:
                    dirty = True
                    continue

                # If the style has no bulletFontName but it has a fontName, set it
                if ('bulletFontName' not in s) and ('fontName' in s):
                    s['bulletFontName'] = s['fontName']

                hasFS = True
                # Adjust fontsize units
                if 'fontSize' not in s:
                    s['fontSize'] = s['parent'].fontSize
                    s['trueFontSize'] = None
                    hasFS = False
                elif 'parent' in s:
                    # This means you can set the fontSize to
                    # "2cm" or to "150%" which will be calculated
                    # relative to the parent style
                    s['fontSize'] = self.adjustUnits(s['fontSize'],
                                                    s['parent'].fontSize)
                    s['trueFontSize'] = s['fontSize']
                else:
                    # If s has no parent, it's base, which has
                    # an explicit point size by default and %
                    # makes no sense, but guess it as % of 10pt
                    s['fontSize'] = self.adjustUnits(s['fontSize'], 10)

                # If the leading is not set, but the size is, set it
                if 'leading' not in s and hasFS:
                    s['leading'] = 1.2*s['fontSize']

                # If the bullet font size is not set, set it as fontSize
                if ('bulletFontSize' not in s) and ('fontSize' in s):
                    s['bulletFontSize'] = s['fontSize']

                # If the borderPadding is a list and wordaxe <=0.3.2,
                # convert it to an integer. Workaround for Issue
                if 'borderPadding' in s and (
                    ((HAS_WORDAXE and wordaxe_version <= 'wordaxe 0.3.2')
                    or reportlab.Version < "2.3")
                        and isinstance(s['borderPadding'], list)):
                    log.warning(
                        'Using a borderPadding list in '
                        'style %s with wordaxe <= 0.3.2 or Reportlab < 2.3. That is not '
                        'supported, so it will probably look wrong' % s['name'])
                    s['borderPadding'] = s['borderPadding'][0]
                if 'spaceBefore' in s:
                    if isinstance(s['spaceBefore'], str) and s['spaceBefore'].startswith('-'):
                        log.warning('A negative spaceBefore is the same as 0')
                    s['spaceBefore'] = self.adjustUnits(s['spaceBefore'])
                if 'spaceAfter' in s:
                    if isinstance(s['spaceAfter'], str) and s['spaceAfter'].startswith('-'):
                        log.warning('A negative spaceAfter is the same as 0')
                    s['spaceAfter'] = self.adjustUnits(s['spaceAfter'])

                self.StyleSheet.add(ParagraphStyle(**s))

        self.emsize = self['base'].fontSize
        # Make stdFont the basefont, for Issue 65
        reportlab.rl_config.canvas_basefontname = self['base'].fontName
        # Make stdFont the default font for table cell styles (Issue 65)
        reportlab.platypus.tables.CellStyle.fontname = self['base'].fontName
Ejemplo n.º 31
0
    def fableMeStyleSheet(self):
        """Returns the FableMe stylesheet """

        stylesheet = StyleSheet1()

        stylesheet.add(
            ParagraphStyle(name='Normal',
                           fontName=_baseFontName,
                           firstLineIndent=5,
                           alignment=TA_JUSTIFY,
                           fontSize=16,
                           leading=24,
                           spaceBefore=4,
                           spaceAfter=4))

        stylesheet.add(
            ParagraphStyle(name='BodyText',
                           parent=stylesheet['Normal'],
                           spaceBefore=6))
        stylesheet.add(
            ParagraphStyle(name='Italic',
                           parent=stylesheet['BodyText'],
                           fontName=_baseFontNameI))

        stylesheet.add(ParagraphStyle(name='Title',
                                      parent=stylesheet['Normal'],
                                      fontName=_baseFontNameB,
                                      fontSize=26,
                                      leading=24,
                                      alignment=TA_CENTER,
                                      spaceAfter=6),
                       alias='title')

        stylesheet.add(ParagraphStyle(name='Dedication',
                                      parent=stylesheet['Normal'],
                                      fontName=_baseFontNameI,
                                      fontSize=16,
                                      leading=24,
                                      spaceBefore=8,
                                      alignment=TA_CENTER,
                                      spaceAfter=3,
                                      textColor=darkblue),
                       alias='dedication')

        stylesheet.add(ParagraphStyle(name='Chapter',
                                      parent=stylesheet['Normal'],
                                      fontName=_baseFontNameI,
                                      fontSize=18,
                                      leading=18,
                                      spaceBefore=12,
                                      spaceAfter=20,
                                      textColor=darkblue),
                       alias='chapter')

        stylesheet.add(ParagraphStyle(name='Heading3',
                                      parent=stylesheet['Normal'],
                                      fontName=_baseFontNameBI,
                                      fontSize=12,
                                      leading=14,
                                      spaceBefore=12,
                                      spaceAfter=6),
                       alias='h3')

        stylesheet.add(ParagraphStyle(name='Heading4',
                                      parent=stylesheet['Normal'],
                                      fontName=_baseFontNameBI,
                                      fontSize=10,
                                      leading=12,
                                      spaceBefore=10,
                                      spaceAfter=4),
                       alias='h4')

        stylesheet.add(ParagraphStyle(name='Heading5',
                                      parent=stylesheet['Normal'],
                                      fontName=_baseFontNameB,
                                      fontSize=9,
                                      leading=10.8,
                                      spaceBefore=8,
                                      spaceAfter=4),
                       alias='h5')

        stylesheet.add(ParagraphStyle(name='Heading6',
                                      parent=stylesheet['Normal'],
                                      fontName=_baseFontNameB,
                                      fontSize=7,
                                      leading=8.4,
                                      spaceBefore=6,
                                      spaceAfter=2),
                       alias='h6')

        stylesheet.add(ParagraphStyle(name='Bullet',
                                      parent=stylesheet['Normal'],
                                      firstLineIndent=0,
                                      spaceBefore=3),
                       alias='bu')

        stylesheet.add(ParagraphStyle(name='Definition',
                                      parent=stylesheet['Normal'],
                                      firstLineIndent=0,
                                      leftIndent=36,
                                      bulletIndent=0,
                                      spaceBefore=6,
                                      bulletFontName=_baseFontNameBI),
                       alias='df')

        stylesheet.add(
            ParagraphStyle(name='Code',
                           parent=stylesheet['Normal'],
                           fontName='Courier',
                           fontSize=8,
                           leading=8.8,
                           firstLineIndent=0,
                           leftIndent=36))

        return stylesheet