示例#1
0
 def ejcritRejsolution(self, tropDeSolutions, nbRejsolutions,
                       nbCellulesOccupees, valeurs, verts):
     # commence par afficher les grilles en attente
     self.pdfGrilles()
     miniGrilleStyle = self.grilleStyle()
     miniGrilleStyle.extend([('FONTSIZE', (0, 0), (-1, -1), 7),
                             ('TOPPADDING', (0, 0), (-1, -1), 4)])
     texte = '''
     Un programme qui n'est pas du tout anthropomorphique celui-là, a rejsolu prejventivement 
     la grille proposeje...
     <br/>qui a %d cellules dejjah affectejes...       
     <br/>''' % (nbCellulesOccupees)
     if nbRejsolutions == 0:
         texte += """<b>Cette grille n'a aucune solution !! </b>
         <br/>Le sudoku anthropomorphique n'en trouvera donc pas...
         """
     elif tropDeSolutions:
         texte += """<b>Cette grille a plus de %d solutions !!</b>
         <br/>Le sudoku anthropomorphique n'en trouvera donc pas parce qu'il ne sait pas faire de choix...
         """ % (nbRejsolutions)
     elif nbRejsolutions == 1:
         texte += """<b>Cette grille a une solution et une seule ! </b>
         <br/>Le sudoku anthropomorphique va faire ce qu'il peut pour la trouver...
         """
     else:
         texte += """<b>Cette grille a %d solutions ! </b>
         <br/>Le sudoku anthropomorphique n'en trouvera donc pas parce qu'il ne sait pas faire de choix...
         """ % (nbRejsolutions)
     if nbRejsolutions == 1:
         grilleValeurs = [['' for i in range(9)] for i in range(9)]
         for (x, y), valeur in valeurs:
             grilleValeurs[x][y] = str(valeur)
         for x, y in verts:
             miniGrilleStyle.append(
                 ('BACKGROUND', (y, x), (y, x), colors.lightgreen))
         #cree la table avec les valeurs et la taille de chaque cellule
         grille = Table(grilleValeurs, C_CEL2, C_CEL2)
         grille.setStyle(miniGrilleStyle)
         table = Table([[Paragraph(texte, self.explicationsStyle), grille]],
                       [14.2 * cm, C_TAB2 + 2 * C_CEL2])
         table.setStyle([
             #('INNERGRID', (0,0), (-1,-1), 0.1, colors.black),
             #('BOX', (0,0), (-1,-1), 0.1, colors.black),
             ('LEFTPADDING', (0, 0), (-1, -1), 0),
             ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
             ('VALIGN', (0, 0), (-1, -1), 'TOP')
         ])
         table.hAlign = "LEFT"
         self.flowables.append(KeepTogether(table))
     else:
         self.flowables.append(
             KeepTogether(Paragraph(texte, self.explicationsStyle)))
示例#2
0
    def doSubscriptions(self):
        style = self.getStyle()
        text = """There have been 21 subscription requests this week. 
        All have been approved| X were approved, Y rejected, 
        Z are still to be considered. """

        png = 'Picture 1.png'

        subscriptionsPara = [
            Spacer(inch * .25, inch * .25),
            Paragraph('Subscriptions', style['SectionTitle']),
            Paragraph(text, style=style["Normal_just_rind"]),
            Spacer(inch * .125, inch * .125),
            Paragraph(self.doRequests(), style=style["Normal_just_rind"]),
            Spacer(inch * .25, inch * .25)
        ]
        subscriptionsImg = ImageAndFlowables(Image(png, width=180, height=180),
                                             subscriptionsPara,
                                             imageLeftPadding=0,
                                             imageRightPadding=0,
                                             imageSide='right')

        return KeepTogether(
            [subscriptionsImg,
             Spacer(inch * .125, inch * .125)])
示例#3
0
 def plateLayouts(self,plates):
     PLATE_STYLE = TableStyle(
         [
         ('FONTSIZE',(0,0),(-1,-1),5),
         ('VALIGN',(0,0),(-1,0),'BOTTOM'),
         ('VALIGN',(0,1),(-1,-1),'MIDDLE'),
         ('ALIGN',(0,1),(-1,-1),'LEFT'),
         ('ALIGN',(0,0),(-1,0),'CENTER'),
         ('INNERGRID', (1,1), (-1,-1), 0.25, colors.grey),
         ('BOX', (1,1), (-1,-1), 0.25, colors.grey),
         ('BACKGROUND',(0,1),(0,-1),colors.snow),
         ('BACKGROUND',(1,0),(-1,0),colors.snow),
         ('LEFTPADDING',(1,1),(-1,-1),1),
         ('RIGHTPADDING',(1,1),(-1,-1),1)
         ])
     for plateNumber, data in enumerate(plates):
         self.elements.append(Paragraph('Plate%s' % str(plateNumber+1), self.styles["Heading4"]))
         data = [ [ chr(ord('A')+i) ] + r for i,r in enumerate(data) ]  # add row names
         data = [ [ str(c) if c else '' for c in range(len(data[0])) ] ] + data  # add column names
         # Make paragraphs
         for i,r in enumerate(data):
             for j,c in enumerate(r):
                 data[i][j] = Paragraph(c,self.styles['tiny']) if i and j else Paragraph(c,self.styles['small'])
         t = Table(data, colWidths=1.2*cm, rowHeights=0.5*cm)
         t.setStyle(PLATE_STYLE)
         self.elements.append(KeepTogether(t))
         self.elements.append(Spacer(1, 12))
示例#4
0
 def volumeLists(self,reactions,mastermix,qsolution,excess,program):
     # batch mix
     data = [['Reagent','Quantity','LOT','Expiry','','Reactions', str(reactions) ],
         ['MasterMix', str((1.+excess)*reactions*mastermix)+' µl', '', '', '', 'Excess', str((excess)*100)+' %' ],
         ['Q-Solution', str((1.+excess)*reactions*qsolution)+' µl', '', '', '', 'PCR Program', program ],
         ['TOTAL', str((1.+excess)*reactions*(mastermix+qsolution))+' µl', '', '', '', 'PCR Block','']]
     t = Table(data, colWidths=[2.5*cm,2.5*cm,2.5*cm,2.5*cm,0.3*cm,2.7*cm,2.5*cm], rowHeights=0.6*cm)
     t.setStyle(TableStyle([
         ('FONTSIZE',(0,1),(0,-1),10),
         ('FONTSIZE',(1,0),(4,0),10),
         ('FONTSIZE',(1,1),(4,-1),8),
         ('FONTSIZE',(5,0),(5,-1),10),
         ('FONTSIZE',(6,0),(6,-1),8),
         ('INNERGRID', (0,0), (3,-1), 0.25, colors.black),
         ('INNERGRID', (5,0), (6,-1), 0.25, colors.black),
         ('LINEABOVE', (0,1),(3,1), 1, colors.black),
         ('BACKGROUND',(2,-1),(3,-1),colors.lightgrey),
         ('BACKGROUND', (0,0), (3,0), colors.bisque),
         ('VALIGN',(0,0),(-1,-1),'MIDDLE'),
         ('ALIGN',(0,0),(-1,-1),'RIGHT'),
         ('BOX', (0,0), (3,-1), 1, colors.black),
         ('BOX', (5,0), (6,-1), 1, colors.black)
         ]))
     self.elements.append(Spacer(1, 12))
     self.elements.append(KeepTogether(t))
     self.elements.append(Spacer(1, 12))
    def create_document(self):
        # elements will contain flowables for the build function
        elements = []
        # Paragraph for Heading and meta information
        paragraph = '<font size={}><strong>{}<i>{}</i><br/> vs.<br/>{}<i>{}</i></strong></font><br/>'.format(
            self.font_size + 2,
            self.game.headers.get('White'),
            ' [{}]'.format(self.game.headers.get('WhiteElo')) if self.game.headers.get('WhiteElo') else '',
            self.game.headers.get('Black'),
            ' [{}]'.format(self.game.headers.get('BlackElo')) if self.game.headers.get('BlackElo') else '')
        for key in self.game.headers.keys():
            if key != 'White' and key != 'Black' and key != 'WhiteElo' and key != 'BlackElo' and self.game.headers.get(key) != '?':
                paragraph += '<br/>{}: {}'.format(key, self.game.headers.get(key))
        elements.append(Paragraph(paragraph, self.styles['Header']))
        # Generate paragraphs with move text and board diagramms
        paragraph = str()
        mainline_variations = []
        for i, move in enumerate(self.game.mainline()):
            # if move.comment and '<*>' in move.comment or any([i == halfmove for halfmove in self.halfmoves_to_be_printed]):
            if move.has_variation:
                elements.append(Paragraph(paragraph, self.styles['Move_Text']))
                elements.append(KeepTogether(self.board_from_FEN(move.board().fen())))
                paragraph = str()
            # After print of a board diagramm if it's black's move print move number
            if any([i == halfmove for halfmove in self.halfmoves_to_be_printed]) and i % 2 == 1:
                paragraph += '<strong>{}...</strong> {} '.format(int((i + 2) / 2), self.print_move_and_variations(move, i).replace('<*>', '').strip())
            else:
                paragraph += self.print_move_and_variations(move, i).replace('<*>', '').strip() + ' '
        

        elements.append(Paragraph(paragraph, self.styles['Move_Text']))
        self.doc.build(elements)
示例#6
0
 def pdfInsejcable(self):
     # si le titre est dans l'affichage, insehre un peu d'espace
     if len(self.insejcable) > 1:
         self.flowables.append(Spacer(C_CEL, C_CEL))
     table = Table(self.insejcable)
     table.hAlign = "LEFT"
     self.flowables.append(KeepTogether(table))
     self.insejcable.clear()
示例#7
0
def export(listino, luogoDiRiferimento):
    response = http.HttpResponse(content_type='application/pdf')
    width, height = portrait(A4)

    pageTemplates = [
        PageTemplate(id='Listino', onPage=onPageListino),
    ]

    doc = BaseDocTemplate(
        response,
        pagesize=(width, height),
        leftMargin=1 * cm,
        rightMargin=1 * cm,
        bottomMargin=1.5 * cm,
        topMargin=1 * cm,
        showBoundary=test,
        pageTemplates=pageTemplates,
    )

    doc.listino = listino  # arricchisco il doc

    righe_prezzo = listino.prezzolistino_set.all()

    story = []

    listinoEsclusivo = getTabellaListino(doc, righe_prezzo, 'T', luogoDiRiferimento)
    if listinoEsclusivo:
        title = Paragraph("SERVIZIO TAXI ESCLUSIVO", normalStyle)
        story.append(title)
        story.append(listinoEsclusivo)

    listinoCollettivo = getTabellaListino(doc, righe_prezzo, 'C', luogoDiRiferimento)
    if listinoEsclusivo and listinoCollettivo:
        story.append(Spacer(1, 1.5 * cm))
    if listinoCollettivo:
        title = Paragraph("SEVIZIO COLLETIVO MINIBUS", normalStyle)
        story.append(KeepTogether([title, listinoCollettivo]))

    if not listinoCollettivo and not listinoEsclusivo:
        story.append(
            Paragraph("Non abbiamo nessuna corsa specificata nel listino.", normal_style)
        )

    # footer
    footer_style = ParagraphStyle(name='Justify', alignment=TA_JUSTIFY, fontSize=8)
    # footer_height = 0
    if LISTINO_FOOTER:
        note_finali_lines = [LISTINO_FOOTER]
        story.append(Spacer(1, 1 * cm))
        note_finali = Paragraph("<br/>".join(note_finali_lines),
                                footer_style)
        # note_finali.wrap(width - doc.rightMargin - doc.leftMargin, 5 * cm)
        # note_finali.drawOn(canvas, doc.leftMargin, doc.bottomMargin)
        # footer_height = note_finali.height
        story.append(note_finali)

    doc.build(story, canvasmaker=NumberedCanvas)
    return response
示例#8
0
def create_table(data, align, fontcolor, backcolor, box, together=True):
    """create table for data as nested list of table rows"""

    data = copy(data)

    # nrow, ncol
    nrow = len(data)
    ncol = len(data[0])

    if align == "NA":
        align = zeros((nrow, ncol)).tolist()
        for i in range(nrow):
            for j in range(ncol):
                align[i][j] = 'LEFT'

    if fontcolor == "NA":  # fontcolor per cell
        fontcolor = array(['black'] * nrow * ncol,
                          dtype=object).reshape(nrow, ncol)

    if backcolor == "NA":  # background color per cell
        backcolor = array(['white'] * nrow * ncol,
                          dtype=object).reshape(nrow, ncol)

    # decimal formatting if int or float
    for i in range(nrow):
        for j in range(ncol):
            if isinstance(data[i][j], float):
                data[i][j] = "{:.2f}".format(float(data[i][j]))  # dec = 2

    # setting TableStyle per cell
    table_styles = []
    for i in range(nrow):
        for j in range(ncol):
            # pylint: disable=E1121 # too many positional arguments for constructor call
            # reportlab colors.toColor works as expected
            reportlab_color = colors.toColor(backcolor[i][j])
            table_styles.extend([
                ('BACKGROUND', (j, i), (j, i), reportlab_color),
                ('ALIGN', (j, i), (j, i), align[i][j]),
                ('TEXTCOLOR', (j, i), (j, i), getattr(colors,
                                                      fontcolor[i][j])),
            ])
    # type instead of box != "NA": avoid FutureWarning
    if not isinstance(box, str):
        for i in range(box.shape[0]):
            table_styles += [('BOX', (box[i, 1], box[i, 0]),
                              (box[i, 3], box[i, 2]), 1, colors.black)]

    # creating table
    table = Table(data)
    table.setStyle(TableStyle(table_styles))
    # don't split tables over pages
    if together:
        table = KeepTogether(table)

    return table
示例#9
0
    def _draw_section_two(self, story):
        t1 = Table([["Section 2: Follow-up Reports"]], (18 * cm))
        self.set_table_style(t1, bg_cmd=self.bg_cmd)
        total = self.ae_initial.ae_follow_ups.count()
        row_text = f"There {p.plural_verb('is', total)} {p.no('follow-up report', total)}."
        t2 = Table([[row_text]], (18 * cm))
        self.set_table_style(t2)
        story.append(KeepTogether([t1, t2]))

        story.append(Spacer(0.1 * cm, 0.5 * cm))

        for index, obj in enumerate(self.ae_initial.ae_follow_ups):
            self._draw_followup_story(story, obj, index + 1, total)
            story.append(Spacer(0.1 * cm, 0.5 * cm))
            story.append(Spacer(0.1 * cm, 0.5 * cm))
示例#10
0
def create_agenda_item_table(items, Document):
    """
    Creates the agenda items tables.
    """
    for item in items:
        # Create the heading sub-table
        raw_title = 'Item ' + str(item.item_no) + ':&nbsp;&nbsp;' + item.title
        title = fit_to_table_cell(raw_title, 165*mm,
                                  font_name=itemHeadingStyle.fontName,
                                  font_size=itemHeadingStyle.fontSize)
        if item.time_limit:
            time_limit_content = Paragraph(str(item.time_limit) + ' mins',
                                           itemHeadingRightStyle)
        else: 
            time_limit_content = ''
        heading_t = Table([((
                Paragraph(title, itemHeadingStyle),
                time_limit_content,
                ))],
            colWidths=[150*mm,20*mm]
            )
        heading_t.setStyle(AGENDA_ITEM_HEADING_STYLE)
        # Create the explainer sub-table
        if item.explainer:
            explainer_t = Table([((
                          Paragraph('To be introduced by '+str(item.explainer),
                           shadedStyle),))
                          ],
                  colWidths=[printable_width])
            explainer_t.setStyle(SHADED_STYLE)
        # Create the background sub-table            
        if item.background:
            background_t = create_item_table(item.background)
        #Create the item table
        item_contents = [[(heading_t,)]]
        if item.explainer:
            item_contents.append([(explainer_t,)])
        if item.background:
            item_contents.append([(background_t,)])
        t = Table(item_contents, colWidths=[printable_width])
        t.setStyle(SUPERSTRUCTURE_STYLE)
        #Add the item table to the document
        Document.append(KeepTogether(t))
        Document.append(Spacer(0,7*mm))
    
    Document.append(Paragraph('NOTE: A summary of tasks for review is on the '
                              'next page.', normalStyle))
    Document.append(PageBreak())
示例#11
0
 def doImport(self):
     style = self.getStyle()
     text = '''Import transfer rates and quality for %s. 
     Maximum daily rate is 237MB/s, minimum rate is 100MB/s, 
     average 169/MB/s. Average quality for the week is 30 percent.''' % self.site
     importPara = [
         Spacer(inch * .25, inch * .25),
         Paragraph('Data Import', style['SectionTitle']),
         Paragraph(text, style=style["Normal_just"])
     ]
     png = 'Picture 1.png'
     importImg = ImageAndFlowables(Image(png, width=340, height=240),
                                   importPara,
                                   imageLeftPadding=0,
                                   imageRightPadding=20,
                                   imageSide='left')
     return KeepTogether([importImg, Spacer(inch * .125, inch * .125)])
示例#12
0
 def main():
     from reportlab.graphics.barcode.code128 import Code128
     from reportlab.platypus import Spacer, SimpleDocTemplate
     from reportlab.lib.units import inch, cm
     from reportlab.lib.styles import getSampleStyleSheet
     from reportlab.platypus.paragraph import Paragraph
     from reportlab.platypus.flowables import KeepTogether
     import os
     styles = getSampleStyleSheet()
     styleN = styles['Normal']
     styleH = styles['Heading1']
     story = []
     storyAdd = story.append
     for s in (
             'BBBB123456BBB',
             'BBBB12345BBB',
             'BBBB1234BBB',
             'BBBB123BBB',
             'BBBB12BBB',
             'BBBB1BBB',
             'BBBB123456aa',
             'BBBB1234aa',
             'BBBB123aa',
             'BBBB12aa',
             'BBBB1aa',
             'BBBB123456',
             'BBBB12345',
             'BBBB1234',
             'BBBB123',
             'BBBB12',
             'BBBB1',
             '\xf11234B',
             'Ba\xf11234B',
             'Ba12',
             'Ba123B',
             'Ba1234B',
             'BBBB1234567',
             'BBBB1234567aa',
     ):
         storyAdd(
             KeepTogether(
                 [Paragraph('Code 128 %r' % s, styleN),
                  Code128(s)]))
         storyAdd(Spacer(inch, inch))
     SimpleDocTemplate('code128-out.pdf').build(story)
示例#13
0
def coursesList(courses):
    getMetaData("5cb0b321ab661b1fea0178be")
    tableTitleList = [[set_H2("PERIODO JUNIO - AGOSTO 2018")]]
    tableCoursesList = [[
        'No.',
        set_N('Nombre de los cursos'), 'Objetivo',
        set_N('Periodo de Realizacion'), 'Lugar',
        set_N('No. de horas x Curso'), 'Instructor', 'Dirigido a:',
        'Observaciones'
    ]]
    for x in range(0, len(courses)):
        tableCoursesList.append([
            str(x + 1),
            set_N(courses[x][0]),
            set_N(courses[x][1]),
            set_N(periodOfTime(courses[x][2], courses[x][3])),
            set_N(courses[x][4]),
            set_N(courses[x][5]),
            set_N(courses[x][6]),
            set_N(courses[x][7]), ''
        ])
    tableSignsList = [["Elaboró", "Aprobó"], ["", ""],
                      ["Nombre y firma", "Nombre y firma"],
                      ["Fecha:", "Fecha:"]]
    tableTitle = Table(tableTitleList)
    tableCourses = Table(tableCoursesList,
                         style=[('GRID', (0, 0), (-1, -1), 0.5, colors.black),
                                ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                                ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                                ('FONTSIZE', (0, 0), (-1, -1), 8)],
                         colWidths=(30, 80, 80, 80, 60, 50, 60, 80, 80))
    tableSigns = Table(tableSignsList,
                       style=[('GRID', (0, 0), (-1, -1), 0.5, colors.black),
                              ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                              ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                              ('FONTSIZE', (0, 0), (-1, -1), 8)],
                       colWidths=200,
                       rowHeights=(10, 20, 10, 10))
    story = []
    story.append(tableTitle)
    story.append(tableCourses)
    story.append(Spacer(1, inch / 4))
    story.append(KeepTogether(tableSigns))
    return returnPDF(story, "ListaDeCursos", landscape(letter), 105)
示例#14
0
def create_pdf_doc(glossar_files, output_file):
    """
    Creates a PDF file from Moodle glossar that were exported into the XML
    file format.
    
    :param glossar_files: tuple of file names or string containing a single
                          file name, that file should contain the glossars
                          in Moodle's XML format.
    :param output_file: file name for output PDF file
    """
    logger.info('Creating PDF file from Moodle Glossar...')
    # define styles for page elements
    heading_paragraph_style = ParagraphStyle(name='Normal', fontName='Helvetica', fontSize=16) 
    question_paragraph_style = ParagraphStyle(name='Normal', fontName='Helvetica-Bold', fontSize=11) 
    answer_paragraph_style = ParagraphStyle(name='Normal', fontName='Helvetica', fontSize=11, embeddedHyphenation=1, linkUnderline=1)
    centered = ParagraphStyle(name='centered', fontSize=30, leading=16, alignment=1, spaceAfter=20)
    h1 = ParagraphStyle(name='Heading1', fontSize=14, leading=16)
    h2 = ParagraphStyle(name='Heading2', fontSize=12, leading=14)
    # set title for document
    global TITLE
    if len(glossar_files) == 1:
        TITLE = os.path.splitext(os.path.basename(glossar_files[0]))[0]
    doc = SimpleDocTemplate(output_file, author=AUTHOR, title=TITLE)
    story = []
    # build document
    for f in glossar_files:
        with open(f, 'r', encoding='utf8') as glossar_data:
            bs = BeautifulSoup(glossar_data.read(), features="xml")
        # create heading
        heading = str(bs.find('NAME').get_text())
        story.append(Paragraph(heading, heading_paragraph_style))
        # TODO: Set bookmark for heading in PDF file.
        story.append(Spacer(0, 1.0*cm))
        # build paragraphs for questions
        for e in bs.find('ENTRIES').find_all('ENTRY'):
            question = handle_html_from_xml(e.find('CONCEPT').text)
            answer = handle_html_from_xml(e.find('DEFINITION').text)
            story.append(KeepTogether([Paragraph(question, question_paragraph_style),
                                    Paragraph(answer, answer_paragraph_style),
                                    Spacer(0, 0.75*cm)]))
            # TODO: Set bookmark for question in PDF file.
        story.append(PageBreak())
    logger.info('Writing Moodle glossar to PDF file: {}.'.format(output_file))
    doc.build(story, onFirstPage=create_page_margins, onLaterPages=create_page_margins)
示例#15
0
def go():
    doc = SimpleDocTemplate("docs/donimoes.pdf")
    styles = getSampleStyleSheet()
    paragraph_style = styles[Styles.Normal]
    list_style = ListStyle('default_list',
                           bulletFontSize=paragraph_style.fontSize,
                           bulletFormat='%s.')
    story = []
    f = open('docs/rules.md')
    group = []
    bulleted = []
    first_bullet = None
    states = parse(f.read())
    for state in states:
        if state.style == Styles.Diagram:
            flowable = Diagram(state.text)
        else:
            flowable = Paragraph(state.text, styles[state.style])
        if state.style.startswith(Styles.Heading):
            group.append(flowable)
        elif state.bullet:
            bulleted.append(flowable)
            first_bullet = first_bullet or state.bullet
        else:
            if bulleted:
                story.append(
                    ListFlowable(bulleted,
                                 style=list_style,
                                 start=first_bullet))
                bulleted = []
                first_bullet = None
                story.append(Spacer(1, 0.055 * inch))
            if not group:
                story.append(flowable)
            else:
                group.append(flowable)
                story.append(KeepTogether(group))
                group = []
            story.append(Spacer(1, 0.055 * inch))
    if bulleted:
        story.append(
            ListFlowable(bulleted, style=list_style, start=first_bullet))
    doc.build(story, onFirstPage=firstPage)
示例#16
0
    def doErrors(self):
        style = self.getStyle()
        title = "Error Summary"
        text = """Below is a summary of the top errors to and from %s
        for the week beginning %s.""" % (self.site, self.getDate())
        errors = """*** ERRORS from T2_Estonia_Buffer:***
    942   transfer expired in the download agent queue
    777   Canceled (null)
    140   transfer timed out after 3630 seconds with signal 15
     77   transfer timed out after 3645 seconds with signal 9
     53   Failed on SRM put: SRM getRequestStatus timed out on put
     50   no detail - validate failed: [unknown reason - inspect log]
      7   the gridFTP transfer timed out"""

        return KeepTogether([
            Paragraph(title, style=style['SectionTitle']),
            Paragraph(text, style=style["Normal_just"]),
            Spacer(inch * .125, inch * .125),
            Preformatted(errors, style=style["Preformatted"])
        ])
def synthesis_paragraphs(flags):

    story = []

    if 'target' in flags.keys():
        story.append(Paragraph('Target material: {}'.format(flags['target']), styles['Normal']))
        story.append(Spacer(1, 10))
    if 'ref' in flags.keys():
        story.append(Paragraph('Reference: {}'.format(flags['ref']), styles['Normal']))
        story.append(Spacer(1, 10))
    if 'temp' in flags.keys():
        story.append(Paragraph('Temperature [K]: {0}'.format(flags['temp']), styles['Normal']))
        story.append(Spacer(1, 10))
    if 'cryst' in flags.keys():
        story.append(Paragraph('Crystallization time [h]: {0}'.format(flags['cryst']), styles['Normal']))
    if 'desc' in flags.keys():
        story.append(KeepTogether([Spacer(1, 10),
                                   Paragraph("Description", styles['Section']),
                                   Spacer(1, 12),
                                   Paragraph(flags['desc'], styles['Normal'])]))
    return story
示例#18
0
    def generate(self):
        # self._doc = SimpleDocTemplate(
        #     self._filename, pagesize=letter)
        self._doc = BaseDocTemplate(self._filename, pagesize=letter)
        page_width, page_height = letter
        self._frame = Frame(self._doc.leftMargin,
                            self._doc.bottomMargin,
                            self._doc.width,
                            self._doc.height,
                            leftPadding=10,
                            rightPadding=10,
                            showBoundary=0)
        self._doc.addPageTemplates([
            PageTemplate(id='Col',
                         onPage=self._add_page_number,
                         frames=[self._frame]),
        ])

        self._story.append(self._render_header())
        self._story.append(Spacer(page_width, 30))
        if hasattr(
                self._data,
                'recurring_charges') and self._data.recurring_charges:  ######
            self._story.append(self._render_summary())
        if hasattr(self._data, 'transaction_summary') and len(
                self._data.transaction_summary):
            self._story.append(
                KeepTogether(self._render_transaction_summary_analysis()))
        # if self._data['show_authorization_code_summary']:
        #     self._story.append(KeepTogether(self._render_authorization_code_summary_report()))
        # if self._data['show_all_area_codes_summary']:
        #     self._story.append(KeepTogether(self._render_all_area_codes_summary_report()))
        # if self._data['show_origination_lata_summary']:
        #     self._story.append(KeepTogether(self._render_origination_lata_summary_report()))
        self._story.append(Spacer(page_width, 30))
        self._story.append(self._render_footer())

        self._doc.build(self._story)

        return True
示例#19
0
    def collect_xml_data(self, events):
        """Traverse the parsed xml data and gather collected event data

        The collected XML data then is passed to the table_manager and all arranged
        data is return.

        :param List[XMLRow] events: a list of the items from which the texts shall be
            extracted into a nicely formatted table
        :returns: list of all table rows containing the relevant
            event data
        :rtype: List[KeepTogether]
        """
        if events:
            for event in events:
                self._table_manager.distribute_row(XMLRow(event))
            subtable_elements = self._table_manager.subtables
            self._elements.extend([
                KeepTogether(subtable_element)
                for subtable_element in subtable_elements
            ])
            return self._elements

        return warnings.warn("There were no items to print.", RuntimeWarning)
示例#20
0
    def doOutstanding(self):
        style = self.getStyle()
        title = "Outstanding Transfer Requests"
        text = """The following transfer requests are older than a week and 
have not been completed. Please investigate and resolve the failing transfers, 
or remove the subscriptions if the data is no longer required."""
        data = [
            [
                Paragraph("Data set/File Block", style["TableHeader"]),
                Paragraph("Age", style["TableHeader"])
            ],
            [
                HypenatedParagraph("/LaserSim/CMSSW_1_4_4-CSA07-2075/GEN-SIM",
                                   style["TableMain"],
                                   width=((6 * A4[0]) / 8)),
                Paragraph("5 weeks", style["TableMain_cent"])
            ],
            [
                HypenatedParagraph(
                    "/RelVal160pre410MuonsPt10/CMSSW_1_6_0_pre4-RelVal-1184752200/GEN-SIM-DIGI-RECO",
                    style["TableMain"],
                    width=((6 * A4[0]) / 8)),
                Paragraph("2 weeks", style["TableMain_cent"])
            ]
        ]
        return KeepTogether([
            Paragraph(title, style=style['SectionTitle']),
            Paragraph(text, style=style["Normal_just"]),
            Spacer(inch * .125, inch * .125),
            Table(data,
                  colWidths=((6 * A4[0]) / 8, A4[0] / 8),
                  style=[('BACKGROUND', (0, 0), (-1, 0), '#dddddd'),
                         ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.grey),
                         ('BOX', (0, 0), (-1, -1), 0.5, colors.black),
                         ('VALIGN', (0, 0), (-1, -1), 'MIDDLE')]),
            Spacer(inch * .125, inch * .125)
        ])
def create_pdf(path, model, flags):

    doc = SimpleDocTemplate(path, pagesize=A4, rightMargin=25, leftMargin=25,
                            topMargin=25, bottomMargin=25)

    story = []
    header = create_header(model, no_moles=False, **flags)
    comps = components_table(model)
    batch = batch_table(model)

    story.extend(header)
    story.append(Spacer(1, 15))

    story.extend(synthesis_paragraphs(flags))
    story.append(Spacer(1, 15))

    if flags['composition']:
        story.append(KeepTogether([Paragraph("Composition Matrix [C]", styles['Section']),
                                   Spacer(1, 15), comps, Spacer(1, 10)]))
    if flags['batch']:
        story.append(KeepTogether([Paragraph("Batch Matrix [B]", styles['Section']),
                                   Spacer(1, 15), batch, Spacer(1, 10)]))
    if flags['rescale_all']:
        story.append(KeepTogether([Paragraph("Results [X] (SF={0:8.4f})".format(model.scale_all), styles['Section']),
                                  Spacer(1, 15), results_table(model, scale="all"), Spacer(1, 10)]))
    if flags['rescale_to']:
        story.append(KeepTogether([Paragraph("Results [X] (SF={0:8.4f})".format(model.sample_scale), styles['Section']),
                                   Spacer(1, 15), results_table(model, scale="sample"), Spacer(1, 10)]))
    if flags['rescale_item']:
        story.append(KeepTogether([Paragraph("Results [X] (SF={0:8.4f})".format(model.item_scale), styles['Section']),
                                   Spacer(1, 15), results_table(model, scale="item"), Spacer(1, 10)]))
    if flags['comment'] != "":
        story.append(KeepTogether([Spacer(1, 10),
                                   Paragraph("Comments", styles['Section']),
                                   Spacer(1, 12),
                                   Paragraph(flags['comment'], styles['Normal'])]))
    doc.build(story)
示例#22
0
    def pcrProgram(self, tableTitle=None,program=''):
        if tableTitle:
            self.elements.append(Paragraph(tableTitle, self.styles["Heading4"]))
            self.elements.append(Spacer(1, 2))

        if program == 'ngsconfirm':
            data = [['','Temp','Time','No. of Cycles'],
            ['Stage 1', '95', '15m', '1'],
            ['Stage 2', '94', '30s', '35'],
            ['', '60', '1m30s', ''],
            ['', '72', '1m', ''],
            ['Stage 3', '72', '10m', '1'],
            ['Stage 4', '10', '10m', '1']]
            t = Table(data, colWidths=[2.5*cm,2.0*cm,2.0*cm,3.0*cm], rowHeights=0.6*cm)
            t.setStyle(TableStyle([
                ('BOX', (0,0), (3,-1), 1, colors.black),
                ('FONTSIZE', (0,0), (3,0), 10),
                ('FONTSIZE', (0,1), (0,4), 10),
                ('FONTSIZE', (1,1), (3,-1), 8),
                ('INNERGRID', (0,0), (3,1), 0.25, colors.black),
                ('LINEABOVE', (0,2), (3,2), 0.25, colors.black),
                ('LINEBEFORE', (1,2), (1,-1), 0.25, colors.black),
                ('LINEBEFORE', (3,0), (3,-1), 0.25, colors.black),
                ('INNERGRID', (1,2), (2,-1), 0.25, colors.black),
                ('LINEABOVE', (0,-2), (3,-2), 0.25, colors.black),
                ('LINEABOVE', (0,-1), (3,-1), 0.25, colors.black),
                ('VALIGN',(0,0),(-1,-1),'MIDDLE'),
                ('ALIGN',(0,0),(2,-1),'LEFT'),
                ('ALIGN',(-1,1),(-1,-1),'CENTER'),
                ]))
            self.elements.append(Spacer(1, 12))
            self.elements.append(KeepTogether(t))
            self.elements.append(Spacer(1, 12))

        if program == 'A1_TD':
            data = [['','Temp','Time','No. of Cycles'],
            ['Stage 1', '94', '14m', '1'],
            ['Stage 2', '95', '30s', '5'],
            ['', '62', '30s', ''],
            ['', '72', '1m 30s', ''],
            ['Stage 3', '95', '30s', '5'],
            ['', '60', '30s', ''],
            ['', '72', '1m 30s', ''],
            ['Stage 4', '95', '30s', '35'],
            ['', '58', '30s', ''],
            ['', '72', '1m 30s', ''],
            ['Stage 5', '10', '10m', '1']]
            t = Table(data, colWidths=[2.5*cm,2.0*cm,2.0*cm,3.0*cm], rowHeights=0.6*cm)
            t.setStyle(TableStyle([
                ('BOX', (0,0), (3,-1), 1, colors.black),
                ('FONTSIZE', (0,0), (3,0), 10),
                ('FONTSIZE', (0,1), (0,5), 10),
                ('FONTSIZE', (1,1), (-1,-1), 8),
                ('INNERGRID', (0,0), (3,1), 0.25, colors.black),
                ('LINEABOVE', (0,2), (3,2), 0.25, colors.black),
                ('LINEBEFORE', (1,2), (1,-1), 0.25, colors.black),
                ('LINEBEFORE', (3,0), (3,-1), 0.25, colors.black),
                ('INNERGRID', (1,2), (2,-1), 0.25, colors.black),
                ('LINEABOVE', (0,5), (3,5), 0.25, colors.black),
                ('LINEABOVE', (0,-4), (3,-4), 0.25, colors.black),
                ('LINEABOVE', (0,-1), (3,-1), 0.25, colors.black),
                ]))
            self.elements.append(Spacer(1, 12))
            self.elements.append(KeepTogether(t))
            self.elements.append(Spacer(1, 12))
示例#23
0
def make_invoice(fp, purchase, org, pgnum, tickets, **kw):
    """
    make pdf invoice. Should be called with the same parameters
    as the render_template with the html template.
    """
    doc = BaseDocTemplate(fp, pagesize=A4)
    styles = getSampleStyleSheet()

    args = dict(date=purchase.date[0],
                rcptaddr=[purchase.buyerName[0]],
                senderaddr=[org.name[0]],
                orgnum=org.orgnum[0],
                fskatt=org.fskatt[0],
                kind=purchase.kind[0],
                ocr=purchase.ocr[0],
                conditions='30 dagar netto',
                latefee=u'Efter förfallodatum debiteras '
                u'dröjsmålsränta enligt räntelagen.',
                total=purchase.total[0],
                pgnum=pgnum,
                styles=styles)

    qrcode = {
        'uqr': 1,
        'tp': 1,
        'nme': org.name[0],
        'cid': org.orgnum[0],
        'idt': time.strftime('%Y%m%d', time.localtime(purchase.date[0])),
        'iref': purchase.ocr[0],
        'due': str(purchase.total[0]),
        'pt': 'PG',
        'acc': pgnum[:-1] + '-' + pgnum[-1:]
    }

    if purchase.buyerAddress:
        args['rcptaddr'] += purchase.buyerAddress[0].split('\n')
    if org.address:
        args['senderaddr'] += org.address[0].split('\n')
    if org.phone:
        args['phone'] = org.phone[0]
    if org.email:
        args['email'] = org.email[0]
    if org.url:
        args['url'] = org.url[0]
    if org.seat:
        args['seat'] = org.seat[0]
    if org.vatnum:
        args['vatnum'] = org.vatnum[0]
    if purchase.buyerReference:
        args['buyerref'] = purchase.buyerReference[0]
    if purchase.buyerAnnotation:
        args['annotation'] = purchase.buyerAnnotation[0].split('\n')
    for (code, pct, value) in purchase.vat:
        qrcode[{'10': 'vh', '11': 'vm', '12': 'vl'}[code]] = str(value)
    try:
        args['expiryDate'] = purchase.expiryDate[0]
        qrcode['ddt'] = time.strftime('%Y%m%d',
                                      time.localtime(purchase.expiryDate[0]))
    except (AttributeError, IndexError):
        qrcode['ddt'] = time.strftime('%Y%m%d')

    args['qrcode'] = json.dumps(qrcode)

    tmpl = InvoiceTemplate(name='invoice', **args)
    tmpl2 = Invoice2Template(name='invoice2', **args)

    doc.addPageTemplates([tmpl, tmpl2])

    elements = [NextPageTemplate('invoice'), NextPageTemplate('invoice2')]

    indentedsmallstyle = ParagraphStyle('Small',
                                        fontName='Helvetica',
                                        fontSize=8,
                                        leading=9,
                                        leftIndent=5 * mm)
    boldstyle = ParagraphStyle('Bold',
                               fontName='Helvetica-Bold',
                               fontSize=10,
                               leading=12)
    boldrightstyle = ParagraphStyle('Bold',
                                    fontName='Helvetica-Bold',
                                    fontSize=10,
                                    leading=12,
                                    alignment=TA_RIGHT)
    mycellstyle = CellStyle('mycellstyle')
    mycellstyle.topPadding = mycellstyle.bottomPadding = 0
    tabledata = [
        Table(
            [[
                Paragraph(_('Item'), boldstyle),
                Paragraph(_('Price'), boldrightstyle),
                Paragraph(_('Quantity'), boldrightstyle),
                Paragraph(_('Total'), boldrightstyle)
            ]],
            colWidths=[115 * mm, 20 * mm, 20 * mm, 25 * mm],
            style=TableStyle([
                ('ALIGN', (1, 0), (-1, -1), 'RIGHT'),
                ('TOPPADDING', (0, 0), (-1, -1), 0),
                ('BOTTOMPADDING', (0, 0), (-1, -1), 0),
                #('BOX', (0,0), (-1, -1), 0.25, colors.black),
            ]))
    ]
    for item in purchase.items:
        celldata = [
            Table(
                [[
                    item.name[0],
                    formatters.money(item.price[0], True), item.quantity[0],
                    formatters.money(item.total[0], True)
                ]],
                colWidths=[115 * mm, 20 * mm, 20 * mm, 25 * mm],
                style=TableStyle([
                    ('ALIGN', (1, 0), (-1, -1), 'RIGHT'),
                    ('TOPPADDING', (0, 0), (-1, -1), 0),
                    ('BOTTOMPADDING', (0, 0), (-1, -1), 0),
                    #('BOX', (0,0), (-1, -1), 0.25, colors.black),
                    #('ALIGN', (0,0), (-1, 0), 'LEFT')
                ]),
            )
        ]
        if item.options:
            for opt, val in item.optionsWithValue:
                celldata.append(
                    Paragraph('%s: <i>%s</i>' % (opt, val),
                              indentedsmallstyle))
        tabledata.append(celldata)

    # Sum and VAT
    tabledata.append([
        Table(
            [[
                '',
                Paragraph(_('Total'), boldrightstyle),
                Paragraph(formatters.money(purchase.total[0], True),
                          boldrightstyle)
            ]],
            colWidths=[115 * mm, 40 * mm, 25 * mm],
            style=TableStyle([
                ('ALIGN', (1, 0), (-1, -1), 'RIGHT'),
                ('TOPPADDING', (0, 0), (-1, -1), 0),
                ('BOTTOMPADDING', (0, 0), (-1, -1), 0),
                #('BOX', (0,0), (-1, -1), 0.25, colors.black),
                #('ALIGN', (0,0), (-1, 0), 'LEFT')
            ]),
        )
    ])

    #vats = [(25, decimal.Decimal('11.37')), (12, decimal.Decimal('6.78'))]

    for code, percentage, amount in purchase.vat:
        tabledata.append([
            Table(
                [[
                    '',
                    Paragraph(
                        _('Including %s%% VAT') %
                        py3txt(formatters.vatpercentage(percentage)),
                        boldrightstyle),
                    Paragraph(formatters.money(amount, True), boldrightstyle)
                ]],
                colWidths=[115 * mm, 40 * mm, 25 * mm],
                style=TableStyle([
                    ('ALIGN', (1, 0), (-1, -1), 'RIGHT'),
                    ('TOPPADDING', (0, 0), (-1, -1), 0),
                    ('BOTTOMPADDING', (0, 0), (-1, -1), 0),
                    #('BOX', (0,0), (-1, -1), 0.25, colors.black),
                    #('ALIGN', (0,0), (-1, 0), 'LEFT')
                ]),
            )
        ])

    t = Table(
        [[t] for t in tabledata],
        colWidths=[180 * mm],
        repeatRows=1,
        style=TableStyle([
            ('LEFTPADDING', (0, 0), (0, -1), 0),
            ('RIGHTPADDING', (0, -1), (-1, -1), 0),
            #('BOX', (0,0), (-1, -1), 0.25, colors.black)
        ]))

    elements.append(t)

    extraText = purchase.extraText
    if extraText:
        textElements = []
        text_style = ParagraphStyle('Text',
                                    fontName='Helvetica',
                                    fontSize=8,
                                    leading=9)
        for text in extraText:
            textElements.append(Paragraph(text, text_style))
        elements.append(KeepTogether(textElements))

    doc.multiBuild(elements)
示例#24
0
def assistantList(teachers, courseTeacher, course):
    getMetaData("5cb0c0beab661b261edfea32")
    tableTitleList = [[set_H2("lista de asistencia")]]
    presential = virtual = " "
    if course["modality"] == "Presencial":
        presential = "X"
    else:
        virtual = "X"
    tableDataCourseList = [['', '', '', '', 'FOLIO:', course["serial"]],
                           ['NOMBRE DEL EVENTO:', course["courseName"]],
                           [
                               'NOMBRE DEL INSTRUCTOR:', courseTeacher[0],
                               'DURACION:',
                               "{} Hrs.".format(course["totalHours"]),
                               'HORARIO:', course["timetable"]
                           ],
                           [
                               'PERIODO: ',
                               periodOfTime(course['dateStart'],
                                            course['dateEnd']), "SEDE:",
                               course["place"]
                           ],
                           [
                               'MODALIDAD: ', 'PRESENCIAL(' + presential + ')',
                               'VIRTUAL(' + virtual + ')'
                           ]]
    arrayDays = []
    for x in range(0, 5):
        arrayDays.append((course['dateStart'] + td(days=x)).day)
    tableDataTeacherList = [[
        'No.', 'NOMBRE DEL PARTICIPANTE', 'R.F.C.', 'DEPARTAMENTO ACADÉMICO',
        set_N('CUMPLIMIENTO DE ACTIVIDADES'), 'ASISTENCIA'
    ], ['', '', '', '', '', 'L', 'M', 'M', 'J', 'V'],
                            [
                                '', '', '', '', '%', arrayDays[0],
                                arrayDays[1], arrayDays[2], arrayDays[3],
                                arrayDays[4]
                            ]]
    for x in range(0, len(teachers)):
        tableDataTeacherList.append([
            str(x + 1), teachers[x][0], teachers[x][1], teachers[x][2], '', '',
            '', '', '', ''
        ])
    tableSignsList = [[
        set_NU(courseTeacher[0]),
        set_N('ME. CLAUDIA CRUZ NAVARRO')
    ],
                      [
                          set_N("NOMBRE Y FIRMA DEL INSTRUCTOR"),
                          set_N("NOMBRE Y FIRMA DEL INSTRUCTOR")
                      ], [set_N("R.F.C.: {}".format(courseTeacher[1]))],
                      [set_N('C.U.R.P.: campoSinAgregarxd')]]
    tableTitle = Table(tableTitleList)
    tableDataCourse = Table(
        tableDataCourseList,
        style=[
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('FONTSIZE', (0, 0), (-1, -1), 8.5),
            ('SPAN', (3, 3), (5, 3)),
            ('LINEBELOW', (5, 0), (6, 0), 0.5, colors.black),  #Folio
            ('LINEBELOW', (1, 1), (6, 1), 0.5,
             colors.black),  #Nombre del evento
            ('LINEBELOW', (1, 2), (1, 2), 0.5,
             colors.black),  #Nombre del instructor
            ('LINEBELOW', (1, 3), (1, 3), 0.5, colors.black),  #Periodo
            ('LINEBELOW', (3, 2), (3, 2), 0.5, colors.black),  #Duracion
            ('LINEBELOW', (5, 2), (5, 2), 0.5, colors.black),  #Horario
            ('LINEBELOW', (3, 3), (5, 3), 0.5, colors.black)  #Sede
        ],
        rowHeights=12,
        colWidths=(130, 200, 60, 90, 50, 70))
    tableDataTeacher = Table(tableDataTeacherList,
                             style=[('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                                    ('ALIGN', (0, 0), (-1, 2), 'CENTER'),
                                    ('GRID', (0, 0), (-1, -1), 0.5,
                                     colors.black), ('SPAN', (5, 0), (9, 0)),
                                    ('SPAN', (4, 0), (4, 1)),
                                    ('SPAN', (3, 0), (3, 2)),
                                    ('SPAN', (2, 0), (2, 2)),
                                    ('SPAN', (1, 0), (1, 2)),
                                    ('SPAN', (0, 0), (0, 2)),
                                    ('FONTSIZE', (0, 0), (-1, -1), 8)],
                             colWidths=(16, 170, 120, 170, 80, 16, 16, 16, 16,
                                        16),
                             rowHeights=11)
    tableSigns = Table(tableSignsList,
                       style=[
                           ('LINEBELOW', (0, 0), (-1, 0), 1, colors.black),
                           ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                       ],
                       colWidths=180,
                       rowHeights=10)
    title = course["courseName"].replace(" ", "")
    story = []
    story.append(tableTitle)
    story.append(tableDataCourse)
    story.append(Spacer(1, inch / 5))
    story.append(tableDataTeacher)
    story.append(Spacer(1, inch * 3 / 4))
    story.append(KeepTogether(tableSigns))
    return returnPDF(story, title, landscape(letter), 105)
示例#25
0
def create_next_meeting_table(meeting, Document):
    """
    Creates a table in minutes for details of the next meeting.
    """
    date = meeting.next_meeting_date
    start_time = meeting.next_meeting_start_time
    location = insert_line_breaks(meeting.next_meeting_location)
    facilitator = meeting.next_meeting_facilitator
    minute_taker = meeting.next_meeting_minute_taker
    notes = insert_line_breaks(meeting.next_meeting_instructions)
    # Trim contents to fit cells where necessary
    if facilitator:
        facilitator = fit_to_table_cell(str(facilitator), 64*mm)
    if minute_taker:
        minute_taker = fit_to_table_cell(str(minute_taker), 64*mm)
    # Set up the heading row as a sub-table   
    heading_t = Table([((
                Paragraph('Details of next meeting', itemHeadingStyle),
                ))],
            colWidths=[printable_width/2]
            )    
    heading_t.setStyle(MINUTES_ITEM_HEADING_STYLE)
    # Set up the contents rows
    contents = []
    if date:
        contents.append(
            (Paragraph('Date', shadedStyle),
                Paragraph(date.strftime("%A %B %d, %Y"), normalStyle)))
    if start_time:
        contents.append(
            (Paragraph('Start time', shadedStyle),
             Paragraph(start_time.strftime("%I:%M %p").lstrip('0').lower(),
                       normalStyle)))  
    if location:
        contents.append(
            (Paragraph('Location', shadedStyle),
             Paragraph(location, normalStyle)))
    if facilitator:
       contents.append(
            (Paragraph('Facilitator', shadedStyle),
             Paragraph(facilitator, normalStyle)))
    if minute_taker:
        contents.append(
            (Paragraph('Minutes', shadedStyle),
             Paragraph(minute_taker, normalStyle)))
    if notes:
        contents.append(
            (Paragraph('Notes', shadedStyle),
                Paragraph(notes, normalStyle)))
    # Set up the body sub-table                                  
    if contents:
        body_t = Table(contents, colWidths=[21*mm,64*mm])
        body_t.setStyle(MEETING_DETAILS_STYLE)
        # Set up the whole table
        table_contents = [[(heading_t,)], [(body_t,)]]
        t = Table(table_contents, colWidths=[printable_width/2])
        t.setStyle(SUPERSTRUCTURE_STYLE)
        t.hAlign = 'LEFT'
        Document.append(KeepTogether(t))
        Document.append(Spacer(0,5*mm))
    Document.append(Paragraph('NOTE: A summary of tasks assigned in this '
                              'meeting is on the next page.', shadedStyle))
    Document.append(PageBreak())
示例#26
0
 def _flowable(self, node):
     if node.localName == 'para':
         style = self.styles.para_style_get(node)
         return platypus.Paragraph(
             self._textual(node), style,
             **(utils.attr_get(node, [], {'bulletText': 'str'})))
     elif node.localName == 'name':
         self.styles.names[node.getAttribute('id')] = node.getAttribute(
             'value')
         return None
     elif node.localName == 'xpre':
         style = self.styles.para_style_get(node)
         return platypus.XPreformatted(
             self._textual(node), style,
             **(utils.attr_get(node, [], {
                 'bulletText': 'str',
                 'dedent': 'int',
                 'frags': 'int'
             })))
     elif node.localName == 'pre':
         style = self.styles.para_style_get(node)
         return platypus.Preformatted(
             self._textual(node), style,
             **(utils.attr_get(node, [], {
                 'bulletText': 'str',
                 'dedent': 'int'
             })))
     elif node.localName == 'illustration':
         return self._illustration(node)
     elif node.localName == 'blockTable':
         return KeepTogether(self._table(node))
     elif node.localName == 'title':
         styles = reportlab.lib.styles.getSampleStyleSheet()
         style = styles['Title']
         return platypus.Paragraph(
             self._textual(node), style,
             **(utils.attr_get(node, [], {'bulletText': 'str'})))
     elif node.localName == 'h1':
         styles = reportlab.lib.styles.getSampleStyleSheet()
         style = styles['Heading1']
         return platypus.Paragraph(
             self._textual(node), style,
             **(utils.attr_get(node, [], {'bulletText': 'str'})))
     elif node.localName == 'h2':
         styles = reportlab.lib.styles.getSampleStyleSheet()
         style = styles['Heading2']
         return platypus.Paragraph(
             self._textual(node), style,
             **(utils.attr_get(node, [], {'bulletText': 'str'})))
     elif node.localName == 'h3':
         styles = reportlab.lib.styles.getSampleStyleSheet()
         style = styles['Heading3']
         return platypus.Paragraph(
             self._textual(node), style,
             **(utils.attr_get(node, [], {'bulletText': 'str'})))
     elif node.localName == 'image':
         return platypus.Image(
             node.getAttribute('file'),
             mask=(250, 255, 250, 255, 250, 255),
             **(utils.attr_get(
                 node,
                 ['width', 'height', 'preserveAspectRatio', 'anchor'])))
     elif node.localName == 'spacer':
         if node.hasAttribute('width'):
             width = utils.unit_get(node.getAttribute('width'))
         else:
             width = utils.unit_get('1cm')
         length = utils.unit_get(node.getAttribute('length'))
         return platypus.Spacer(width=width, height=length)
     elif node.localName == 'barCode':
         return code39.Extended39(self._textual(node))
     elif node.localName == 'pageBreak':
         return platypus.PageBreak()
     elif node.localName == 'condPageBreak':
         return platypus.CondPageBreak(**(utils.attr_get(node, ['height'])))
     elif node.localName == 'setNextTemplate':
         return platypus.NextPageTemplate(str(node.getAttribute('name')))
     elif node.localName == 'nextFrame':
         return platypus.FrameBreak()
         # return platypus.CondPageBreak(1000)  # TODO: change the 1000 !
     elif node.localName == 'ul':
         return self._list(node)
     elif node.localName == 'keepInFrame':
         substory = self.render(node)
         kwargs = {
             "maxWidth": 0,
             "maxHeight": 0,
             "content": substory,
         }
         mode = node.getAttribute("onOverflow")
         if mode:
             kwargs["mode"] = mode
         name = node.getAttribute("id")
         if name:
             kwargs["name"] = name
         kwargs.update(
             utils.attr_get(node, ['maxWidth', 'maxHeight', 'mergeSpace'], {
                 'maxWidth': 'int',
                 'maxHeight': 'int'
             }))
         return platypus.KeepInFrame(**kwargs)
     else:
         sys.stderr.write('Warning: flowable not yet implemented: %s !\n' %
                          (node.localName, ))
         return None
示例#27
0
def print_order_report(dao, order_id, test_mode=False):
    global header_text,sub_header_text

    mainlog.debug('print_order_report order_id={}'.format(order_id))

    o = dao.order_dao.find_by_id(order_id)

    header_text = u"{} [{}]".format(o.customer.fullname, o.customer_order_name)
    sub_header_text = u"Mode op\u00E9ratoire"

    big_order_nr = ParagraphStyle(name = "subtitle", fontName = 'Helvetica-Bold', fontSize=24, leading=26)

    topstyle = ParagraphStyle(name = "zou", fontName = 'Helvetica', fontSize=16)

    p = platypus.Paragraph(u"<b>Client {}, commande #{}</b>".format(o.customer.customer_id,o.accounting_label),topstyle)
    spacer = platypus.Spacer(1,50)

    centered = ParagraphStyle(name = "zou", fontName = 'Helvetica-bold', alignment=TA_CENTER, fontSize=14) #, borderWidth=1, borderColor=colors.black)
    s = ParagraphStyle(name = "zou", fontName = 'Helvetica', fontSize=14, leading=16) #, borderWidth=1, borderColor=colors.black)
    page_number_style = ParagraphStyle(name = "page_number_style", fontName = 'Helvetica', alignment=TA_RIGHT, fontSize=12, leading=12) #, borderWidth=1, borderColor=colors.black)
    opNumberStyle = ParagraphStyle(name = "zou", fontName = 'Helvetica-bold', alignment=TA_CENTER, fontSize=28,leading=28) #, borderWidth=1, borderColor=colors.black)
    complete_document = []

    global satisfied
    satisfied = False
    sections.clear()
    headings_frame = HeadingsFrame(*basic_frame_dimensions)
    # complete_document.append(DocAssign("i",0))

    for part in o.parts:

        # Build up a table with accompanying style

        # data_ops = [ ['Poste',None,u'Op\u00E9ration',None] ]

        # We build up a data model and the appropriate styling information

        titles_row = []

        if part.production_file and len(part.production_file[0].operations) > 0:

            data_ops = [[Paragraph(part.human_identifier,big_order_nr),
                         Paragraph(escape_html(part.description),subtitle_style)],
                        [SubSectionNumber(part.human_identifier, page_number_style),
                         Paragraph(_("Quantity : {} - Deadline: {}").format(part.qty, date_to_dmy(part.deadline)),subtitle_style)]]

            ts = platypus.TableStyle()
            ts.add('GRID',(0,0),(-1,-1),0.5,colors.black)
            ts.add('VALIGN', (0, 0), (-1, -1), 'TOP')
            ts.add('ALIGN', (0, 1), (-1, 1), 'RIGHT')


            start_mark = PageMarker()
            complete_document.append( start_mark)

            header_maker = HeaderMaker(data_ops, ts, col_widths=compute_strut([3.8*cm, None], A4[0]-1*cm))
            complete_document.append(HeaderSetter( header_maker))

            operation_ndx = 1
            for op in part.production_file[0].operations:
                complete_document.append(
                    KeepTogether( [
                        make_boxes(operation_ndx, op, test_mode),
                        platypus.Spacer(1,0.1*cm) ] ))

                operation_ndx += 1

            end_mark = PageMarker()
            complete_document.append( end_mark)
            sections[part.human_identifier] = (start_mark, end_mark)

            complete_document.append(HeaderSetter(None))
            complete_document.append(PageBreak())
            # complete_document.append(platypus.Spacer(1,30))

    session().close() # FIXME Dirty

    if len(complete_document) > 0:
        filename = make_pdf_filename("OrderAndParts_{}_".format(order_id))
        ladderDoc = basic_PDF(filename,body_frame=headings_frame)
        ladderDoc.subject = u"Mode op\u00E9ratoire"
        ladderDoc.title = u"Client {}".format(o.customer.customer_id)

        ladderDoc.multiBuild(complete_document,canvasmaker=NumberedCanvas)
        open_pdf(filename)
        return True
    else:
        raise ServerException( ServerErrors.printing_an_empty_report)
示例#28
0
def invoice_pdf(request, number, correction=False):
    invoice = get_object_or_404(Invoice, number=number)
    if correction:
        invoice = invoice.correction
    from reportlab.lib.units import mm
    from reportlab.platypus import Paragraph
    from reportlab.platypus.flowables import Spacer
    from reportlab.platypus.flowables import KeepTogether

    from dinbrief.document import Document
    from dinbrief.invoice import ItemTable, TotalTable
    from dinbrief.styles import styles
    from dinbrief.template import BriefTemplate

    with trans_override(invoice.language):

        response = HttpResponse(content_type='application/pdf')
        if 'download' in request.GET:
            filename = '%s.pdf' % invoice.number
            response[
                'Content-Disposition'] = 'attachment; filename=%s' % filename

        if invoice.type == Invoice.TYPE_INVOICE:
            if callable(INVOICE_TERMS):
                terms = INVOICE_TERMS(invoice)
            else:
                terms = [
                    Paragraph(term, styles['Terms']) for term in INVOICE_TERMS
                ]
        else:
            terms = []

        template = BriefTemplate()
        document = Document(
            sender=invoice.sender_lines,
            recipient=invoice.recipient_lines,
            date=date_format(invoice.created, 'SHORT_DATE_FORMAT'),
            content=[
                Paragraph(
                    '%s %s' %
                    (invoice.get_type_display() if not correction else
                     gettext(u'Correction of invoice'), invoice.number),
                    styles['Subject']),
                Spacer(template.CONTENT_WIDTH, 2 * mm),
                ItemTable(template, invoice),
                KeepTogether(TotalTable(template, invoice)),
                Spacer(template.CONTENT_WIDTH, 10 * mm),
            ] + terms)

        if settings.SHARK['INVOICE']['BACKGROUND']:
            with tempfile.TemporaryFile() as tmp:
                # Create content in a temporary file
                template.render(document, tmp)
                # Combine background with the content
                writer = PdfFileWriter()
                content = PdfFileReader(tmp)
                info_dict = writer._info.getObject()
                info_dict.update(content.getDocumentInfo())
                first_bg = PdfFileReader(
                    open(settings.SHARK['INVOICE']['BACKGROUND']['FIRST_PAGE'],
                         'rb'))
                later_bg = PdfFileReader(
                    open(settings.SHARK['INVOICE']['BACKGROUND']['LATER_PAGE'],
                         'rb'))
                bg = [first_bg.getPage(0), later_bg.getPage(0)]
                for i, page in enumerate(content.pages):
                    page.mergePage(bg[min(i, 1)])
                    page.compressContentStreams()
                    writer.addPage(page)
                writer.write(response)
        else:
            # Render content directly to the HTTP response object if no
            # background images are configured.
            template.render(document, response)

    return response
示例#29
0
def fullTest(fileName="test_full.pdf"):
    """Creates large-ish test document with a variety of parameters"""

    story = []

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

    story.append(
        Paragraph('ReportLab Barcode Test Suite - full output', styleH))
    story.append(Paragraph('Generated on %s' % time.ctime(time.time()),
                           styleN))

    story.append(Paragraph('', styleN))
    story.append(Paragraph('Repository information for this build:', styleN))
    #see if we can figure out where it was built, if we're running in source
    if os.path.split(os.getcwd())[-1] == 'barcode' and os.path.isdir('.svn'):
        #runnning in a filesystem svn copy
        infoLines = os.popen('svn info').read()
        story.append(Preformatted(infoLines, styles["Code"]))

    story.append(Paragraph('About this document', styleH2))
    story.append(Paragraph('History and Status', styleH2))

    story.append(
        Paragraph(
            """
        This is the test suite and docoumentation for the ReportLab open source barcode API,
        being re-released as part of the forthcoming ReportLab 2.0 release.
        """, styleN))

    story.append(
        Paragraph(
            """
        Several years ago Ty Sarna contributed a barcode module to the ReportLab community.
        Several of the codes were used by him in hiw work and to the best of our knowledge
        this was correct.  These were written as flowable objects and were available in PDFs,
        but not in our graphics framework.  However, we had no knowledge of barcodes ourselves
        and did not advertise or extend the package.
        """, styleN))

    story.append(
        Paragraph(
            """
        We "wrapped" the barcodes to be usable within our graphics framework; they are now available
        as Drawing objects which can be rendered to EPS files or bitmaps.  For the last 2 years this
        has been available in our Diagra and Report Markup Language products.  However, we did not
        charge separately and use was on an "as is" basis.
        """, styleN))

    story.append(
        Paragraph(
            """
        A major licensee of our technology has kindly agreed to part-fund proper productisation
        of this code on an open source basis in Q1 2006.  This has involved addition of EAN codes
        as well as a proper testing program.  Henceforth we intend to publicise the code more widely,
        gather feedback, accept contributions of code and treat it as "supported".  
        """, styleN))

    story.append(
        Paragraph(
            """
        This involved making available both downloads and testing resources.  This PDF document
        is the output of the current test suite.  It contains codes you can scan (if you use a nice sharp
        laser printer!), and will be extended over coming weeks to include usage examples and notes on
        each barcode and how widely tested they are.  This is being done through documentation strings in
        the barcode objects themselves so should always be up to date.
        """, styleN))

    story.append(Paragraph('Usage examples', styleH2))
    story.append(Paragraph("""
        To be completed
        """, styleN))

    story.append(Paragraph('The codes', styleH2))
    story.append(
        Paragraph(
            """
        Below we show a scannable code from each barcode, with and without human-readable text.
        These are magnified about 2x from the natural size done by the original author to aid
        inspection.  This will be expanded to include several test cases per code, and to add
        explanations of checksums.  Be aware that (a) if you enter numeric codes which are too
        short they may be prefixed for you (e.g. "123" for an 8-digit code becomes "00000123"),
        and that the scanned results and readable text will generally include extra checksums
        at the end.
        """, styleN))

    codeNames = getCodeNames()
    from reportlab.lib.utils import flatten
    width = [float(x[8:]) for x in sys.argv if x.startswith('--width=')]
    height = [float(x[9:]) for x in sys.argv if x.startswith('--height=')]
    isoScale = [int(x[11:]) for x in sys.argv if x.startswith('--isoscale=')]
    options = {}
    if width: options['width'] = width[0]
    if height: options['height'] = height[0]
    if isoScale: options['isoScale'] = isoScale[0]
    scales = [x[8:].split(',') for x in sys.argv if x.startswith('--scale=')]
    scales = list(map(float, scales and flatten(scales) or [1]))
    scales = list(map(float, scales and flatten(scales) or [1]))
    for scale in scales:
        story.append(PageBreak())
        story.append(Paragraph('Scale = %.1f' % scale, styleH2))
        story.append(Spacer(36, 12))
        for codeName in codeNames:
            s = [Paragraph('Code: ' + codeName, styleH2)]
            for hr in (0, 1):
                s.append(Spacer(36, 12))
                dr = createBarcodeDrawing(codeName,
                                          humanReadable=hr,
                                          **options)
                dr.renderScale = scale
                s.append(dr)
                s.append(Spacer(36, 12))
            s.append(Paragraph('Barcode should say: ' + dr._bc.value, styleN))
            story.append(KeepTogether(s))

    SimpleDocTemplate(fileName).build(story)
    print('created', fileName)
示例#30
0
    def checkBoxes(self,title='Checks',table=[],tableHeader=['Task','Date','Checker'],tickbox=[],tickboxNames=['YES','NO'],textLines={}):
        # title
        if title:
            self.elements.append(Paragraph(title, self.styles["Heading4"]))
            self.elements.append(Spacer(1, 2))
        # Task table
        if table:
            # right justified checkboxes with appropriate names
            TABLE_STYLE = TableStyle([
                ('ALIGN',(0,0),(-1,-1),'RIGHT'),
                ('VALIGN',(0,0),(-1,-1),'MIDDLE'),
                ('FONTSIZE',(0,1),(-1,-1),8),
                ('BOX', (0,0), (-1,-1), 1, colors.black),
                ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
                ('LINEABOVE', (0,1), (-1,1), 1, colors.black),
                ('BACKGROUND', (0,0), (-1,0), colors.bisque)
                ])
            data = [tableHeader]
            for i in range(len(table)):
                data.append([ table[i], '', '' ])
            t = Table(data, colWidths=[7.5*cm,4*cm,4*cm], rowHeights=0.6*cm)
            t.setStyle(TABLE_STYLE)
            self.elements.append(KeepTogether(t))
            self.elements.append(Spacer(1, 6))

        if tickbox:
            stylesheet = [
                ('VALIGN',(0,0),(-1,-1),'MIDDLE'),
                ('ALIGN',(1,0),(-1,-1),'LEFT'),
                ('ALIGN',(0,0), (0,-1),'RIGHT'),
                ('FONTSIZE',(0,0),(-1,-1),9)
            ]
            # set column width
            colWidths = [3*cm]
            for t in tickboxNames:
                colWidths += [0.6*cm,1.2*cm]
            # set row heights
            rowHeights = []
            # compile data
            data = []
            for i, b in enumerate(tickbox):
                data.append([ b ])
                for j, t in enumerate(tickboxNames):
                    data[-1] += [ '', t ]
                    stylesheet += [ ('BOX', (2*j+1,i*2), (2*j+1,i*2), 1, colors.black) ]
                data.append(['']*len(data[-1]))  # empty line
                rowHeights += [0.6*cm,0.3*cm]
            t = Table(data, colWidths=colWidths, rowHeights=rowHeights)
            t.setStyle(TableStyle(stylesheet))
            self.elements.append(KeepTogether(t))
            self.elements.append(Spacer(1, 6))

        if textLines:
            stylesheet = [
                ('VALIGN',(0,0),(-1,-1),'MIDDLE'),
                ('ALIGN',(1,0),(-1,-1),'LEFT'),
                ('ALIGN',(0,0), (0,-1),'RIGHT'),
                ('FONTSIZE',(0,0),(0,-1),12),
                ('LINEBELOW', (1,0), (1,-1), 1.0, colors.black)
            ]
            data = []
            for t,l in textLines.items():
                for i in range(l):
                    data.append([ t+':' if i==0 else '', ''])
            t = Table(data, colWidths=[4*cm,11.5*cm], rowHeights=0.6*cm)
            t.setStyle(TableStyle(stylesheet))
            self.elements.append(KeepTogether(t))
            self.elements.append(Spacer(1, 6))
        self.elements.append(Spacer(1, 6))