Esempio n. 1
0
    def __budgets_spent(self):
        self.l = 800
        p = PageBreak()
        p.drawOn(self.c, 0, 1000)
        self.c.showPage()

        self.c.setFont('Courier', 14)
        self.c.drawString(30, self.l, 'Budgets')

        header = ['Nombre', 'Gastado', 'Balance', 'Limite']
        data = [header]

        for bud in self.budgets:
            data.append([bud.name, bud.spent,
                bud.balance, bud.limit])

        self.l -= len(data) * 19
        t = Table(data)
        t.setStyle(TableStyle([('INNERGRID', (0,0), (-1,-1), 0.25, black),
            ('BOX', (0,0), (-1,-1), 0.25, black),
            ('FONTNAME', (0,0), (-1,0), 'Courier-Bold'),
            ('BACKGROUND', (0,0), (-1,0), HexColor('#efeded')),
            ('BACKGROUND', (0,0), (0,-1), HexColor('#efeded')),
            ('FONTSIZE', (0,0), (-1,0), 12),
            ('FONTSIZE', (0,1), (-1,-1), 8),
            ('FONTNAME', (0,1), (-1,-1), 'Courier')]))
        t.wrapOn(self.c, 30, self.l)
        t.drawOn(self.c, 30, self.l)
Esempio n. 2
0
    def __reminders(self):
        self.l = 800
        p = PageBreak()
        p.drawOn(self.c, 0, 1000)
        self.c.showPage()

        self.c.setFont('Courier', 14)
        self.c.drawString(30, self.l, 'Recordatorio de pagos')

        header = ['Fecha', 'Descripcion', 'Monto']
        data = [header]

        for rem in self.reminders:
            data.append([rem.start_date, rem.description,
                rem.amount])

        self.l -= len(data) * 19
        t = Table(data)
        t.setStyle(TableStyle([('INNERGRID', (0,0), (-1,-1), 0.25, black),
            ('BOX', (0,0), (-1,-1), 0.25, black),
            ('FONTNAME', (0,0), (-1,0), 'Courier-Bold'),
            ('BACKGROUND', (0,0), (-1,0), HexColor('#efeded')),
            ('BACKGROUND', (0,0), (0,-1), HexColor('#efeded')),
            ('FONTSIZE', (0,0), (-1,0), 12),
            ('FONTSIZE', (0,1), (-1,-1), 8),
            ('FONTNAME', (0,1), (-1,-1), 'Courier')]))
        t.wrapOn(self.c, 30, self.l)
        t.drawOn(self.c, 30, self.l)
Esempio n. 3
0
def iter_table_story(data, available, make_table, table_name=None):
    """
    Create and yield "story" elements for a new table.

    Args:
      available: the space available for the table as a pair (width, height).
    """
    assert table_name is not None
    available_width = available[0]

    column_counts = compute_column_counts(make_table,
                                          data=data,
                                          width=available_width)
    _log.debug(
        f'will split table along columns into {len(column_counts)}: {column_counts}'
    )

    # Display the header on each page.
    table = make_table(data, repeatRows=1)

    # First split the table along rows.
    tables = split_table_along_rows(table, available)
    _log.debug(f'split table along rows into {len(tables)}')

    for row_number, table in enumerate(tables, start=1):
        # Then split each sub-table along columns, using the column
        # counts we already computed.
        new_tables = split_table_along_columns(make_table,
                                               table=table,
                                               column_counts=column_counts,
                                               table_name=table_name,
                                               grid_row=row_number)

        for new_table in new_tables:
            yield new_table
            # Force a page break after each part of the table.
            yield PageBreak()
Esempio n. 4
0
 def append_to_pdf(self, story):
     motion_id = self.kwargs['motion_id']
     if motion_id is None:  #print all motions
         title = config["motion_pdf_title"]
         story.append(Paragraph(title, stylesheet['Heading1']))
         preamble = config["motion_pdf_preamble"]
         if preamble:
             story.append(
                 Paragraph("%s" % preamble.replace('\r\n', '<br/>'),
                           stylesheet['Paragraph']))
         story.append(Spacer(0, 0.75 * cm))
         motions = Motion.objects.all()
         if not motions:  # No motions existing
             story.append(
                 Paragraph(_("No motions available."),
                           stylesheet['Heading3']))
         else:  # Print all Motions
             # List of motions
             for motion in motions:
                 if motion.number:
                     story.append(
                         Paragraph(
                             _("Motion No.") + " %s: %s" %
                             (motion.number, motion.title),
                             stylesheet['Heading3']))
                 else:
                     story.append(
                         Paragraph(
                             _("Motion No.") + "&nbsp;&nbsp;&nbsp;: %s" %
                             (motion.title), stylesheet['Heading3']))
             # Motions details (each motion on single page)
             for motion in motions:
                 story.append(PageBreak())
                 story = self.get_motion(motion, story)
     else:  # print selected motion
         motion = Motion.objects.get(id=motion_id)
         story = self.get_motion(motion, story)
Esempio n. 5
0
def getSampleStory(depth=3):
    """Makes a story with lots of paragraphs.  Uses the random
    TOC data and makes paragraphs to correspond to each."""
    from reportlab.platypus.doctemplate import randomText
    from random import randint

    styles = getSampleStyleSheet()
    TOCData = getSampleTOCData(depth)

    story = [
        Paragraph("This is a demo of the table of contents object",
                  styles['Heading1'])
    ]

    toc = TableOfContents0()  # empty on first pass
    #toc.addEntries(TOCData)  # init with random page numbers
    story.append(toc)

    # the next full page should switch to internal page style
    story.append(NextPageTemplate("Body"))

    # now make some paragraphs to correspond to it
    for (level, text, pageNum) in TOCData:
        if level == 0:
            #page break before chapter
            story.append(PageBreak())

        headingStyle = (styles['Heading1'], styles['Heading2'],
                        styles['Heading3'])[level]
        headingPara = Paragraph(text, headingStyle)
        story.append(headingPara)
        # now make some body text
        for i in range(randint(1, 6)):
            bodyPara = Paragraph(randomText(), styles['Normal'])
            story.append(bodyPara)

    return story
Esempio n. 6
0
    def genTaskPDF(self, order):
        story = []
        # 首页内容
        story.append(Spacer(1, 20 * mm))
        story.append(Spacer(1, 10 * mm))
        story.append(Paragraph("Order", self.title_style))
        story.append(Spacer(1, 20 * mm))
        story.append(Paragraph("Designed by lovehome", self.sub_title_style))
        story.append(Spacer(1, 45 * mm))
        story.append(Paragraph("OrderId : " + order.id, self.content_style))
        story.append(
            Paragraph("OrderPath : " + order.info.live_addr,
                      self.content_style))
        story.append(
            Paragraph("CustomName : " + order.baseuser.user.username,
                      self.content_style))
        story.append(
            Paragraph("CustomTelephone : " + order.baseuser.user.telephone,
                      self.content_style))
        story.append(
            Paragraph("CustomAddress : " + order.baseuser.user.username,
                      self.content_style))
        story.append(
            Paragraph("OrderType : " + str(order.info.serviceType),
                      self.content_style))

        story.append(Spacer(1, 40 * mm))
        story.append(Paragraph("Copyright by lovehome", self.foot_style))
        story.append(PageBreak())
        doc = SimpleDocTemplate(
            self.file_path + self.filename + ".pdf",
            leftMargin=20 * mm,
            rightMargin=20 * mm,
            topMargin=20 * mm,
            bottomMargin=20 * mm,
        )
        doc.build(story)
Esempio n. 7
0
def makepdf(book):
    
    root = book['root']
    pages = book['pages']
    # A4 纸的宽高
    __a4_w, __a4_h = landscape(A4)
    #print(landscape(A4))
    bookDoc = SimpleDocTemplate(root+'''.pdf''', pagesize=A4, rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=18)
    i = 1
    bookPagesData=[]
    while i < pages :
        page = root + (os.sep) + str(i) + ".jpg"
        #print(page)
        try:
            img_w, img_h = ImageTools().getImageSize(page)
            # img_w = img.imageWidth
            # img_h = img.imageHeight
        except:
            i = i + 1
            continue
            
        if __a4_w / img_w < __a4_h / img_h:
            ratio = __a4_w / img_w
        else:
            ratio = __a4_h / img_h
        data = Image(page, img_w * ratio, img_h * ratio)
        #data = Image(page)
        bookPagesData.append(data)
        bookPagesData.append(PageBreak())
        i = i + 1
    try:
        #print(bookDoc)
        bookDoc.build(bookPagesData)
        
    except Exception as err:
        print("[*][转换PDF] : 错误. [名称] > [%s]" % (root))
        print("[*] Exception >>>> ", err)
Esempio n. 8
0
def paperIee(nombreDocumento, resumenpdf, autores, autoresC, lugar, mail,
             intro, cuerpopdf, recomendaciones, conclusiones, referencias,
             titulo):
    mipaper = []
    mipaper.append(Paragraph(titulo, h3))
    mipaper.append(Paragraph(autores, h5))
    mipaper.append(Paragraph(autoresC, h5))
    mipaper.append(Paragraph(lugar, h5))
    mipaper.append(Paragraph(mail, h5))

    mipaper.append(Paragraph("Abstract", h1))
    for i in range(len(resumenpdf)):
        mipaper.append(Paragraph(resumenpdf[i], h7))

    mipaper.append(Paragraph("1.- Introduccion", h1))
    for i in range(len(intro)):
        mipaper.append(Paragraph(intro[i], h8))
    mipaper.append(PageBreak())

    mipaper.append(Paragraph("2.- Estado del arte", h1))
    for i in range(len(cuerpopdf)):
        mipaper.append(Paragraph(cuerpopdf[i], h8))

    mipaper.append(Paragraph("3.- Recomendaciones", h1))
    for i in range(len(recomendaciones)):
        mipaper.append(Paragraph(recomendaciones[i], h8))

    mipaper.append(Paragraph("4.- Conclusiones", h1))
    for i in range(len(conclusiones)):
        mipaper.append(Paragraph(conclusiones[i], h8))

    mipaper.append(Paragraph("5.- Referencias", h1))
    for i in range(len(referencias)):
        mipaper.append(Paragraph("[" + str(i + 1) + "] " + referencias[i], h8))

    doc = MyDocTemplate(nombreDocumento)
    doc.multiBuild(mipaper)
Esempio n. 9
0
 def frameAction(self, frame):
     frame._generated_content = []
     if self.breakTo == 'any':  # Break only once. None if at top of page
         if not frame._atTop:
             frame._generated_content.append(
                 SetNextTemplate(self.templateName))
             frame._generated_content.append(PageBreak())
     elif self.breakTo == 'odd':  # Break once if on even page, twice
         # on odd page, none if on top of odd page
         if frame._pagenum % 2:  # odd pageNum
             if not frame._atTop:
                 # Blank pages get no heading or footer
                 frame._generated_content.append(
                     SetNextTemplate(self.templateName))
                 frame._generated_content.append(
                     SetNextTemplate('emptyPage'))
                 frame._generated_content.append(PageBreak())
                 frame._generated_content.append(ResetNextTemplate())
                 frame._generated_content.append(PageBreak())
         else:  # even
             frame._generated_content.append(
                 SetNextTemplate(self.templateName))
             frame._generated_content.append(PageBreak())
     elif self.breakTo == 'even':  # Break once if on odd page, twice
         # on even page, none if on top of even page
         if frame._pagenum % 2:  # odd pageNum
             frame._generated_content.append(
                 SetNextTemplate(self.templateName))
             frame._generated_content.append(PageBreak())
         else:  # even
             if not frame._atTop:
                 # Blank pages get no heading or footer
                 frame._generated_content.append(
                     SetNextTemplate(self.templateName))
                 frame._generated_content.append(
                     SetNextTemplate('emptyPage'))
                 frame._generated_content.append(PageBreak())
                 frame._generated_content.append(ResetNextTemplate())
                 frame._generated_content.append(PageBreak())
Esempio n. 10
0
    def add_to_story(self, ctx):
        ctx.update(self.context)
        s = self.template.render(**ctx)
        try:
            js = json.loads(s)
        except ValueError as e:
            if self.debug:
                print("JSON parse failed. Template output:")
                print(s)
                print("------------------------")
                print("JSON parse failed: %s" % e)
                print("see template output above.")
                sys.exit(1)
            else:
                raise Exception("JSON parse failed.")

        if 'border' not in js:
            js['border'] = self.border
        self.story.append(JinjaFlowable(js, self.staticdir))

        if 'forcebreaks' not in js:
            js['forcebreaks'] = self.pagebreaks
        if js.get('forcebreaks', False):
            self.story.append(PageBreak())
Esempio n. 11
0
    def get_cover_page(self, report_id, recipient):
        # title = f"{self.report_title} No.: {report_id}"

        styles = getSampleStyleSheet()
        headline_style = styles["Heading1"]
        headline_style.alignment = TA_CENTER
        headline_style.fontSize = 48
        subtitle_style = styles["Heading2"]
        subtitle_style.fontSize = 24
        subtitle_style.leading = 26
        subtitle_style.alignment = TA_CENTER

        CoverPage = []
        logo = os.path.join(settings.BASE_DIR, self.logo_path)

        image = Image(logo, 3 * inch, 3 * inch)
        CoverPage.append(image)
        CoverPage.append(Spacer(1, 18))
        CoverPage.append(Paragraph("CONFIDENTIAL", headline_style))
        # paragraph = Paragraph(
        #     f"Intended for: {recipient}, Title IX Coordinator", subtitle_style)
        # CoverPage.append(paragraph)
        CoverPage.append(PageBreak())
        return CoverPage
Esempio n. 12
0
def build_pdf_tables(story, tables, report):
    """ Builds formatted tables sections for a list of tables

    @param story: list, pdf elements
    @param tables: list, tables to build
    @param report: Report object
    """
    stylesheet = styles()
    style = stylesheet.get('styles')
    table_style = stylesheet.get('table_style')
    for t, d in tables.items():
        table_name = d.get('title')
        cols = report.tables.get(table_name).get('columns')
        data = report.tables.get(table_name).get('data')

        story.append(Paragraph(table_name, style['Heading4']))
        story.append(Paragraph(d.get('paragraph'), style['Normal']))
        if 'note' in d:
            story.append(
                Paragraph(f"<sub>{d.get('note')}</sub>", style['Normal']))
        story.append(
            Table(df_to_np(cols, data), hAlign='LEFT', style=table_style))
        if len(df_to_np(cols, data)) > 15:
            story.append(PageBreak())
Esempio n. 13
0
def export_production(submission):
    table_substances = tuple(mk_table_substances(submission))

    comments_section = get_comments_section(submission, 'hat_production')

    style = lambda data: (TABLE_IMPORTS_HEADER_STYLE + TABLE_STYLES +
                          (() if data else TABLE_ROW_EMPTY_STYLE_IMP))

    subst_table = table_from_data(data=table_substances,
                                  isBlend=False,
                                  header=TABLE_IMPORTS_HEADER(False, 'produc'),
                                  colWidths=None,
                                  style=style(table_substances),
                                  repeatRows=2,
                                  emptyData=TABLE_ROW_EMPTY_IMP)

    prod_page = (
        Paragraph(_('2.1 Substances'), STYLES['Heading2']),
        subst_table,
        PageBreak(),
        Paragraph(_('2.2 Comments'), STYLES['Heading2']),
    )

    return (page_title(_('PRODUCTION')), ) + prod_page + comments_section
Esempio n. 14
0
    def new_competition(self, competition):
        """
        Add a competition on a new page
        :param competition: New competition
        :type competition: Competition
        """
        logging.debug("New competition: " + competition.titre())

        if not self.story:
            # For the first page
            self.competition = competition
        else:
            self.story.append(NextPageTemplate(competition))
            self.story.append(PageBreak())

        self.competition_header(competition)
        for c in competition.linked:
            self.competition_header(c)

        if competition.reunions:
            for reunion in competition.reunions:
                self.new_reunion(reunion)
        else:
            self.story.append(Paragraph("Pas de résultats trouvés pour cette compétition", sNormal))
Esempio n. 15
0
    def firstPage( self ):

        img = Image( 'ejercito_tierra_logo.png', kind = 'proportional' )
        img.drawHeight = 1 * mm * 25.4
        img.drawWidth = 2.4 * mm * 25.4
        img.hAlign = 'LEFT'
        self.elements.append( img )

        spacer = Spacer( 30, 100 )
        self.elements.append( spacer )

        img = Image( 'Portada.png' )
        img.drawHeight = 2.5 * mm * 25.4
        img.drawWidth = 4.5 * mm * 25.4
        self.elements.append( img )

        spacer = Spacer( 10, 250 )
        self.elements.append( spacer )

        psDetalle = ParagraphStyle( 'Resumen', 
                                    fontSize = 10, 
                                    leading = 14, 
                                    justifyBreaks = 1, 
                                    alignment = TA_LEFT, 
                                    justifyLastLine = 1
                                )

        text = """REPORTE DE SERVICIOS PROFESIONALES    <br/><br/>
                  Empresa: Nombre del Cliente           <br/>
                  Fecha de Inicio: 23-Oct-2019          <br/>
                  Fecha de actualización: 01-Abril-2020 <br/>
               """
        paragraphReportSummary = Paragraph( text, psDetalle )

        self.elements.append( paragraphReportSummary )
        self.elements.append( PageBreak( ) )
Esempio n. 16
0
    def create(self, strategy, template, data):
        header = strategy.create_header(data)
        customer_section = strategy.create_customer_table(data)
        invoice_footer = strategy.create_invoice_footer(data)
        footer = strategy.create_footer(data)

        story = [NextPageTemplate(template.FIRST_PAGE_TEMPLATE_ID)]

        rows_chunks = chunks(data.rows, strategy.MAX_ROWS_PER_TABLE,
                             strategy.FILL_ROWS_WITH)

        for counter, row_chunk in enumerate(rows_chunks):
            is_first_page = counter == 0
            is_last_page = len(rows_chunks) == counter + 1

            story.extend(header)
            story.extend(
                strategy.create_metadata_table(counter + 1, len(rows_chunks),
                                               data))

            if is_first_page:
                story.extend(customer_section)

            story.append(
                strategy.create_rows_table(row_chunk, data, is_last_page))

            if is_last_page:
                story.extend(invoice_footer)

            story.extend(footer)
            story.append(NextPageTemplate(template.LATER_PAGES_TEMPLATE_ID))

            if not is_last_page:
                story.append(PageBreak())

        return story
Esempio n. 17
0
    def newPage(self):
        """Jumps to a new page, aka pageBreak."""

        self.__flow.append(PageBreak())
Esempio n. 18
0
def make_ad(fi, di, fo, tax, exc):
    fhi = open(fi, "r")
    doc = SimpleDocTemplate(fo,
                            pagesize=letter,
                            rightMargin=72,
                            leftMargin=72,
                            topMargin=72,
                            bottomMargin=18)
    styles = getSampleStyleSheet()
    styles.add(
        ParagraphStyle(name='mytitle',
                       fontName='Helvetica-Bold',
                       fontSize=18,
                       leading=25,
                       spaceafter=25))
    styles.add(ParagraphStyle(name='mytext', leading=16, alignment=TA_LEFT))
    styles.add(ParagraphStyle(name='mydetail', leading=14, alignment=TA_LEFT))

    story = []
    fhi.readline()
    for line in fhi:
        lst = line.strip("\n").split("\t")
        if len(lst) < 10: break
        mid, name, wprice, nprice, col, colCode, imgNum, url, note, detl = lst
        imgNum = int(imgNum)
        wprice = wprice.replace(",", "")
        nprice = nprice.replace(",", "")
        if nprice == '': continue
        wprice, nprice = float(wprice), float(nprice)
        if nprice < 150: continue
        uprice = (wprice * (1 + tax / 100) + 60 + 20) * exc
        rprice = (nprice * (1 + tax / 100) + 60 + 20) * exc
        uprice = str(int(uprice))
        rprice = str(int(rprice))

        title = "%s" % name
        story.append(Paragraph(title, styles["mytitle"]))

        keys = ['MFID', 'Color', 'MSRP (RMB)', 'Sale (RMB)']
        vals = [mid, col, uprice, rprice]
        ptext = "<br />".join([
            "<font size=10>%s:</font><font size=12> %s</font>" %
            (keys[i], vals[i]) for i in range(0, len(keys))
        ])
        ptext = "<br />" + ptext
        ltxt = Paragraph(ptext, styles['mytext'])

        lines = detl.split(";")
        detl = "<br />".join(["<font size = 10>%s</font>" % l for l in lines])
        rtxt = Paragraph(detl, styles['mydetail'])

        t1 = Table([[ltxt, rtxt]])
        t1.setStyle(
            TableStyle([
                ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
                ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ]))
        story.append(t1)
        story.append(Spacer(1, 12))

        imglayout = [['', ''], ['', '']]
        for i in range(0, imgNum):
            imgpath = op.join(di, "%s-%s-%d.jpg" % (mid, colCode, i + 1))
            iw, ih = utils.ImageReader(imgpath).getSize()
            aspect = ih / float(iw)
            wd = 3
            ht = wd * aspect
            img = Image(imgpath)  #, wd*inch, ht*inch)
            if i == 0:
                imglayout[0][0] = img
            elif i == 1:
                imglayout[0][1] = img
            elif i == 2:
                imglayout[1][0] = img
            else:
                imglayout[1][1] = img
        t = Table(imglayout)
        story.append(t)
        story.append(PageBreak())
    doc.build(story)
    return True
    elements.append(Spacer(doc.width, styles['TitlePage'].fontSize + 10))


h1 = ParagraphStyle(name='Heading1', fontSize=14, leading=16)
h2 = ParagraphStyle(name='Heading2', fontSize=12, leading=14, leftIndent=5)

frameT = Frame(doc.leftMargin,
               doc.bottomMargin,
               doc.width,
               doc.height,
               id='normal',
               showBoundary=0)
# First page
Elements.append(Paragraph("", styles['Normal']))
Elements.append(NextPageTemplate('OneCol'))
Elements.append(PageBreak())

title(Elements, "Table of contents")
toc = TableOfContents()
# For conciseness we use the same styles for headings and TOC entries
toc.levelStyles = [h1, h2]
Elements.append(toc)
Elements.append(PageBreak())

# Retrospective ( to keep )
title(Elements, "Retrospective")
Elements.append(retroToKeep(getRetroToKeep()))
Elements.append(PageBreak())

# Retrospective ( to improve and actions )
title(Elements, "Retrospective")
Esempio n. 20
0
    def afterFlowable(self, flowable):
        "Registers TOC entries."
        if flowable.__class__.__name__ == 'Paragraph':
            text = flowable.getPlainText()
            style = flowable.style.name
            if style == 'Heading1':
                self.notify('TOCEntry', (0, text, self.page))
            if style == 'Heading2':
                self.notify('TOCEntry', (1, text, self.page))


h1 = PS(name='Heading1', fontSize=14, leading=16)
h2 = PS(name='Heading2', fontSize=12, leading=14)
# Build story.
story = []
toc = TableOfContents()
# For conciseness we use the same styles for headings and TOC entries
toc.levelStyles = [h1, h2]
story.append(toc)
story.append(PageBreak())
story.append(Paragraph('First heading', h1))
story.append(Paragraph('Text in first heading', PS('body')))
story.append(Paragraph('First sub heading', h2))
story.append(Paragraph('Text in first sub heading', PS('body')))
story.append(PageBreak())
story.append(Paragraph('Second sub heading', h2))
story.append(Paragraph('Text in second sub heading', PS('body')))
story.append(Paragraph('Last heading', h1))
doc = MyDocTemplate('mintoc.pdf')
doc.multiBuild(story)
		measurement_table_values = Table(measurement_values_data, [2.25*inch-6, 2.25*inch-6], sub_table_heights)
		measurement_table_values.setStyle(accuracy_values)

		data = [["Wafer Used:", wafers[count]], ["Measurement Method:", "Image Recognition \n*Typical measurement uncertainty is +-1um\n**See Map on following page for die tested"]
		, [measurement_table_headings, measurement_table_values]]
		measurement_table = Table(data, column_widths, overall_rows)
		measurement_table.setStyle(accuracy_table)

		Story.append(measurement_table)
		Story.append(Spacer(1*inch, space_after_accuracy_table*mm))
		count+=1


	signature_table_data = [["Performed by: ", user_name], ["Date: ", datetime.date.today().strftime("%d %b %Y")]]
	signature_table = Table(signature_table_data, column_widths)
	signature_table.setStyle(signature_style)
	Story.append(signature_table)

	Story.append(Spacer(1*inch, above_signature))
	ptext = "<font size = 12>Signature: _________________________________________________</font>"
	Story.append(Paragraph(ptext, styles['Normal']))
	Story.append(NextPageTemplate('second_template'))
	Story.append(PageBreak())

	for grid in grids:

		Story.append(grid)
		Story.append(PageBreak())

	create_pdfdoc(doc_name, Story)
Esempio n. 22
0
    def __per_account_statistic(self):

        for acc in self.accounts:
            p = PageBreak()
            p.drawOn(self.c, 0, 1000)
            self.c.showPage()
            self.l = 760

            self.c.setFont('Courier', 14)
            self.c.drawString(30, 800, 'Cuenta: %s' % \
                acc.name)

            header = ['Fecha', 'Tipo', 'Monto', 'Description']
            data   = [header]
            g_data = list()
            g_labe = list()
            total  = 0

            for tra in self.transactions:
                if tra.account == acc.name:
                    if tra.t_type in ['expense', 'transfer']:
                        tipo = self.__translate_type(tra.t_type)
                        data.append([tra.date, tipo.upper(),
                            '$%2.f' % tra.amount, tra.description])
                        total += tra.amount

                        g_data.append(tra.amount)
                        g_labe.append(tra.description.encode('utf-8'))

            data.append(['TOTAL', '', '$%.2f' % total, ''])

            if len(g_data) == 0 or len(g_labe) == 0:
                self.c.setFont('Courier', 12)
                self.c.drawString(30, 770, 'Sin movimientos negativos')
                continue
 
            from_title = 35
            if len(data) != 2:
                self.l -= ((len(data) * len(data)) + len(data)) + from_title

            t = Table(data)
            t.setStyle(TableStyle([('INNERGRID', (0,0), (-1,-1), 0.25, black),
                ('BOX', (0,0), (-1,-1), 0.25, black),
                ('FONTNAME', (0,0), (-1,0), 'Courier-Bold'),
                ('BACKGROUND', (0,0), (-1,0), HexColor('#efeded')),
                ('BACKGROUND', (0,0), (0,-1), HexColor('#efeded')),
                ('FONTSIZE', (0,0), (-1,0), 12),
                ('FONTSIZE', (0,1), (-1,-1), 8),
                ('FONTNAME', (0,1), (-1,-1), 'Courier'),
                ('BACKGROUND', (0,-1), (-1,-1), red),
                ('TEXTCOLOR', (0,-1), (-1,-1), white)]))

            t.wrapOn(self.c, 30, self.l)
            t.drawOn(self.c, 30, self.l)

            drawing = Drawing(200, 100)

            pie = Pie()
            pie.x = 30
            pie.y = self.l - 300
            pie.height = 200
            pie.width = 200
            pie.data = g_data
            pie.labels = g_labe
            pie.simpleLabels = 1
            pie.slices.strokeWidth = 1
            pie.slices.strokeColor = black
            pie.slices.label_visible = 0
            pie.slices.popout        = 1
            #pie.labels   = map(str, pie.data)

            
            legend = Legend()
            legend.x = 250
            legend.y = self.l - 250
            legend.dx              = 8
            legend.dy              = 8
            legend.fontName        = 'Helvetica'
            legend.fontSize        = 7
            legend.boxAnchor       = 'w'
            legend.columnMaximum   = 10
            legend.strokeWidth     = 1
            legend.strokeColor     = black
            legend.deltax          = 75
            legend.deltay          = 10
            legend.autoXPadding    = 5
            legend.yGap            = 0
            legend.dxTextSpace     = 5
            legend.alignment       = 'right'
            legend.dividerLines    = 1|2|4
            legend.dividerOffsY    = 4.5
            legend.subCols.rpad    = 30
            n = len(pie.data)
            self.__setItems(n,pie.slices,
                'fillColor',self.pdf_chart_colors)

            legend.colorNamePairs = [(pie.slices[i].fillColor, 
                (pie.labels[i][0:20],'$%0.2f' % pie.data[i])) for i in xrange(n)]
            

            drawing.add(pie)
            drawing.add(legend)
            x, y = 0, 10

            renderPDF.draw(drawing, self.c, x, y, showBoundary=False)
Esempio n. 23
0
 def add_page_break(self) -> None:
     self.parts.append(PageBreak())
    def __init__(self,
                 dictValeurs={},
                 dictOptions={},
                 IDmodele=None,
                 ouverture=True,
                 nomFichier=None):
        """ Impression """
        global DICT_VALEURS, DICT_OPTIONS
        DICT_VALEURS = dictValeurs
        DICT_OPTIONS = dictOptions

        # Initialisation du document
        if nomFichier == None:
            nomDoc = FonctionsPerso.GenerationNomDoc("INSCRIPTIONS", "pdf")
        else:
            nomDoc = nomFichier
        doc = BaseDocTemplate(nomDoc, pagesize=TAILLE_PAGE, showBoundary=False)

        # Mémorise le ID du modèle
        modeleDoc = DLG_Noedoc.ModeleDoc(IDmodele=IDmodele)
        doc.modeleDoc = modeleDoc

        # Importe le template de la première page
        doc.addPageTemplates(MyPageTemplate(pageSize=TAILLE_PAGE, doc=doc))

        story = []
        styleSheet = getSampleStyleSheet()
        h3 = styleSheet['Heading3']
        styleTexte = styleSheet['BodyText']
        styleTexte.fontName = "Helvetica"
        styleTexte.fontSize = 9
        styleTexte.borderPadding = 9
        styleTexte.leading = 12

        # ----------- Insertion du contenu des frames --------------
        listeLabels = []
        for IDinscription, dictValeur in dictValeurs.items():
            listeLabels.append((dictValeur["{FAMILLE_NOM}"], IDinscription))
        listeLabels.sort()

        for labelDoc, IDinscription in listeLabels:
            dictValeur = dictValeurs[IDinscription]
            if dictValeur["select"] == True:
                story.append(DocAssign("IDinscription", IDinscription))
                nomSansCivilite = dictValeur["{FAMILLE_NOM}"]
                story.append(Bookmark(nomSansCivilite, str(IDinscription)))

                # ----------- Insertion du cadre principal --------------
                cadre_principal = doc.modeleDoc.FindObjet("cadre_principal")
                if cadre_principal != None:

                    if "intro" in DICT_OPTIONS and DICT_OPTIONS[
                            "intro"] != None or "tableau" in DICT_OPTIONS and DICT_VALEURS[
                                "tableau"] == True:
                        # ------------------- TITRE -----------------
                        dataTableau = []
                        largeursColonnes = [
                            TAILLE_CADRE_CONTENU[2],
                        ]
                        dataTableau.append(
                            (_(u"Confirmation d'inscription"), ))
                        dataTableau.append((u"", ))
                        style = TableStyle([
                            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                            ('FONT', (0, 0), (0, 0), "Helvetica-Bold", 19),
                            ('FONT', (0, 1), (0, 1), "Helvetica", 8),
                            ('LINEBELOW', (0, 0), (0, 0), 0.25, colors.black),
                            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
                        ])
                        tableau = Table(dataTableau, largeursColonnes)
                        tableau.setStyle(style)
                        story.append(tableau)
                        story.append(Spacer(0, 10))

                        # TEXTE D'INTRODUCTION
                        paraStyleIntro = ParagraphStyle(
                            name="intro",
                            fontName="Helvetica",
                            fontSize=11,
                            leading=14,
                            spaceBefore=0,
                            spaceafter=0,
                            leftIndent=0,
                            rightIndent=0,
                            alignment=0,
                        )

                    if "intro" in DICT_OPTIONS and DICT_OPTIONS[
                            "intro"] != None:
                        texteIntro = DICT_VALEURS["intro"]
                        story.append(
                            Paragraph(u"<i>%s</i>" % texteIntro,
                                      paraStyleIntro))
                        story.append(Spacer(0, 20))

                    if "tableau" in DICT_OPTIONS and DICT_OPTIONS[
                            "tableau"] == True:
                        # ------------------- TABLEAU CONTENU -----------------
                        dataTableau = []
                        largeursColonnes = [80, 280]
                        paraStyle = ParagraphStyle(
                            name="detail",
                            fontName="Helvetica-Bold",
                            fontSize=9,
                        )
                        dataTableau.append(
                            (_(u"Nom"),
                             Paragraph(DICT_VALEURS["{INDIVIDU_NOM}"],
                                       paraStyle)))
                        dataTableau.append(
                            (_(u"Prénom"),
                             Paragraph(DICT_VALEURS["{INDIVIDU_PRENOM}"],
                                       paraStyle)))
                        dataTableau.append(
                            (_(u"Activité"),
                             Paragraph(DICT_VALEURS["{ACTIVITE_NOM_LONG}"],
                                       paraStyle)))
                        dataTableau.append(
                            (_(u"Groupe"),
                             Paragraph(DICT_VALEURS["{GROUPE_NOM_LONG}"],
                                       paraStyle)))
                        dataTableau.append(
                            (_(u"Catégorie"),
                             Paragraph(DICT_VALEURS["{NOM_CATEGORIE_TARIF}"],
                                       paraStyle)))

                        style = TableStyle([
                            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                            ('FONT', (0, 0), (0, -1), "Helvetica", 9),
                            ('GRID', (0, 0), (-1, -1), 0.25, colors.black),
                            ('ALIGN', (0, 0), (0, -1), 'RIGHT'),
                        ])
                        tableau = Table(dataTableau, largeursColonnes)
                        tableau.setStyle(style)
                        story.append(tableau)

                # Saut de page
                story.append(PageBreak())

        # Finalisation du PDF
        doc.build(story)

        # Ouverture du PDF
        if ouverture == True:
            FonctionsPerso.LanceFichierExterne(nomDoc)
Esempio n. 25
0
def _create_pdf(invoice_buffer, sanction_outcome):
    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_frame2 = Frame(
        PAGE_MARGIN,
        PAGE_MARGIN,
        PAGE_WIDTH - 2 * PAGE_MARGIN,
        PAGE_HEIGHT - 2 * PAGE_MARGIN,
        id='EveryPagesFrame2',
    )  # showBoundary=Color(0, 0, 1))
    # every_page_template = PageTemplate(id='EveryPages', frames=[every_page_frame,], onPage=_create_header)
    every_page_template = PageTemplate(
        id='EveryPages',
        frames=[
            every_page_frame,
        ],
    )
    every_page_template2 = PageTemplate(
        id='EveryPages2',
        frames=[
            every_page_frame2,
        ],
    )
    doc = BaseDocTemplate(
        invoice_buffer,
        pageTemplates=[
            every_page_template,
            every_page_template2,
        ],
        pagesize=A4,
    )  # showBoundary=Color(1, 0, 0))

    t1 = get_infringement_notice_table(sanction_outcome)

    data_tbl2 = []
    # Notice to alleged offender  (1)
    body = []
    body.append(
        Paragraph(
            'It is alleged that you have committed the above offence.</p>',
            styles['Normal']))
    body.append(
        Paragraph(
            'If you do not want to be prosecuted in court for the offence, pay the modified penalty within 28 days after the date of this notice.',
            styles['Normal']))
    body.append(Paragraph('How to pay', styles['Normal']))
    body.append(
        Paragraph(
            '<strong>By post:</strong>Send a cheque or money order (payable to ‘Approved Officer — Biodiversity Conservation Act 2016’) to:',
            styles['Normal']))
    body.append(
        Paragraph(
            'Approved Officer — Biodiversity Conservation Act 2016<br />Department of Biodiversity, Conservation and Attractions<br />Locked Bag 104<br />Bentley Delivery Centre WA 6983',
            styles['Normal']))
    body.append(Spacer(1, 10))
    body.append(
        Paragraph(
            '<strong>In person:</strong> Pay the cashier at any office of the Department of Biodiversity, Conservation and Attractions, or pay over the telephone by credit card by calling the general telephone number of any office of the Department of Biodiversity, Conservation and Attractions.',
            styles['Normal']))
    data_tbl2.append([
        Paragraph('<strong>Notice to alleged offender</strong>',
                  styles['Normal']), body, ''
    ])

    # Notice to alleged offender  (2)
    body = []
    body.append(
        Paragraph(
            '<strong>If you do not pay</strong> the modified penalty within 28 days, you may be prosecuted or enforcement action may be taken under the Fines, Penalties and Infringement Notices Enforcement Act 1994. Under that Act, some or all of the following action may be taken — your driver’s licence may be suspended; your vehicle licence may be suspended or cancelled; your details may be published on a website; your vehicle may be immobilised or have its number plates removed; your property may be seized and sold.',
            styles['Normal']))
    body.append(Spacer(1, 10))
    body.append(
        Paragraph(
            '<strong>If you need more time.</strong> to pay the modified penalty, you can apply for an extension of time by writing to the Approved Officer at the above postal address.',
            styles['Normal']))
    data_tbl2.append(['', body, ''])

    # Notice to alleged offender  (3)
    body = []
    body.append(
        Paragraph(
            '<strong>If you want this matter to be dealt with by prosecution in court</strong>, sign here <u>'
            + gap(80) +
            '</u> and post this notice to the Approved Officer at the above postal address within 28 days after the date of this notice.',
            styles['Normal']))
    data_tbl2.append(['', body, ''])

    # Create 2nd table
    invoice_table_style2 = TableStyle([
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ('GRID', (0, 0), (-1, -1), 1, colors.black),
        ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        # Notice to alleged offender
        ('SPAN', (0, 0), (0, 2)),
        ('SPAN', (1, 0), (2, 0)),
        ('SPAN', (1, 1), (2, 1)),
        ('SPAN', (1, 2), (2, 2)),
    ])
    col_width = [
        40 * mm,
        60 * mm,
        80 * mm,
    ]
    t2 = Table(data_tbl2, style=invoice_table_style2, colWidths=col_width)

    elements = []
    # elements.append(NextPageTemplate('EveryPages2'))
    elements.append(t1)
    elements.append(PageBreak())
    elements.append(t2)

    doc.build(elements)
    return invoice_buffer
Esempio n. 26
0
    def genPrintLabelPDFs(self,
                          labelDataInput,
                          defaultFileName=None,
                          returnBytes=False):
        """labelDataInput = list of dictionaries formatted as: {DWC Column:'field value'}
           defaultFileName = the filename to use as the default when saving the pdf file."""

        # strip out the site number rows
        try:
            labelDataInput = [
                x for x in labelDataInput if x.get('specimenNumber') != "#"
            ]
        except AttributeError:
            labelDataInput = [
                x for x in labelDataInput
                if "#" not in x.get('otherCatalogNumbers').split('-')[-1]
            ]
        if len(labelDataInput) < 1:  # exit early if nothing is left
            return None

        # decent default values 140, 90
        self.xPaperSize = int(self.settings.get('value_X', 140)) * mm
        self.yPaperSize = int(self.settings.get('value_Y', 90)) * mm
        self.relFont = int(self.settings.get('value_RelFont', 12))
        # TODO explore adding font options which are already bundled with reportlab

        self.allowSplitting = 0
        self.xMarginProportion = 0
        self.yMarginProportion = 0  #Padding on tables are functionally the margins in our use. (We're claiming most of paper)
        self.xMargin = self.xMarginProportion * self.xPaperSize  #Margin set up (dynamically depending on paper sizes.
        self.yMargin = self.xMarginProportion * self.yPaperSize
        self.customPageSize = (self.xPaperSize, self.yPaperSize)

        # check some of the optional label settings, & make adjustments.
        additionalData = {}
        if self.settings.get('value_inc_VerifiedBy'):
            additionalData['verifiedBy'] = self.settings.get(
                'value_VerifiedBy')
        else:
            additionalData['verifiedBy'] = ''
        if self.settings.get('value_inc_CollectionName'):
            additionalData['collectionName'] = self.settings.get(
                'value_CollectionName')
        else:
            additionalData['collectionName'] = ''
        # setting these now, to avoid redundant .get calls.
        incAssociated = self.settings.get('value_inc_Associated')
        maxAssociated = int(self.settings.get('value_max_Associated'))
        if not incAssociated:
            additionalData['associatedTaxa'] = ''
        for rowData in labelDataInput:
            if incAssociated:
                associatedTaxa = rowData['associatedTaxa']
                associatedTaxaItems = associatedTaxa.split(', ')
                if len(
                        associatedTaxaItems
                ) > maxAssociated:  #if it is too large, trunicate it, and append "..." to indicate trunication.
                    associatedTaxa = ', '.join(
                        associatedTaxaItems[:maxAssociated]) + ' ...'
                    rowData['associatedTaxa'] = associatedTaxa
                for key, value in additionalData.items():
                    rowData[key] = value

        tableSty = [  #Default table style
            ('LEFTPADDING', (0, 0), (-1, -1), 0),
            ('RIGHTPADDING', (0, 0), (-1, -1), 0),
            ('TOPPADDING', (0, 0), (-1, -1), 0),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 0)
        ]

        #helper functions to keep the 'flowables' code more legible.

        def Para(textField1, styleKey, prefix='', suffix=''):
            if len(
                    dfl(textField1)
            ) > 0:  #If the field has a value insert it, otherwise blank row
                return Paragraph(
                    ('<b>{}</b>'.format(prefix)) + dfl(textField1) + suffix,
                    style=self.stylesheet(styleKey))
            else:
                return Paragraph('', style=self.stylesheet(styleKey))

        def verifiedByPara(textField1, styleKey):
            if len(
                    dfl(textField1)
            ) > 0:  #If the field has a value insert it, otherwise blank row
                return Paragraph('<i>Verified by {}</i>'.format(
                    dfl(textField1)),
                                 style=self.stylesheet(styleKey))
            else:
                return Paragraph('', style=self.stylesheet(styleKey))

        def sciName(textfield1, textfield2, styleKey, prefix=''):
            if len(dfl(textfield1)) > 0:
                return Paragraph(('<i>{}</i>'.format(dfl(textfield1))) + ' ' +
                                 dfl(textfield2),
                                 style=self.stylesheet(styleKey))
            else:
                return Paragraph('', style=self.stylesheet(styleKey))

        def collectedByPara(textfield1, textfield2, styleKey, prefix=''):
            if len(dfl(textfield1)) > 0:
                if len(dfl(textfield2)) > 0:
                    return Paragraph(
                        ('<b>{}</b>'.format(prefix)) + dfl(textfield1) +
                        ' with ' + dfl(textfield2),
                        style=self.stylesheet(styleKey))
                else:
                    return Paragraph(
                        ('<b>{}</b>'.format(prefix)) + dfl(textfield1),
                        style=self.stylesheet(styleKey))
            else:
                return Paragraph('', style=self.stylesheet(styleKey))

        def cultivationStatusChecker(textfield1, styleKey):
            if str(dfl(textfield1)) == 'cultivated':
                return Paragraph('<b>Cultivated specimen</b>',
                                 style=self.stylesheet(styleKey))
            else:
                return Paragraph('', style=self.stylesheet('default'))

        def gpsCoordStringer(textfield1, textfield2, textfield3, textfield4,
                             styleKey):
            gpsString = []
            if len(dfl(textfield1)) > 0:
                if (dfl(textfield1) and dfl(textfield2)):
                    # min([len(dfl(textfield1)),len(dfl(textfield2))]) testing length control.
                    gpsString.append('<b>GPS: </b>' + dfl(textfield1) + ', ' +
                                     dfl(textfield2))
                if dfl(textfield3):
                    gpsString.append(
                        ' ± ' +
                        str(round(float(dfl(textfield3)), 0)).split('.')[0] +
                        'm')
                if dfl(textfield4):
                    gpsString.append(', <b>Elevation: </b>' + dfl(textfield4) +
                                     'm')

                return Paragraph(''.join(gpsString),
                                 style=self.stylesheet(styleKey))

        #############Logo Work#################################
        ##############################################################################
        #
        #logoPath = 'ucht.jpg'   # This should be determined by the user dialog open option.
        #
        #def getLogo(logoPath):
        #    if logoPath:
        #        return Image(logoPath, width = 40, height =30.6) #These values should be handled dynamically!
        ######Barcode work(Catalog Number)######

        def newHumanText(self):
            return self.stop and self.encoded[1:-1] or self.encoded

        def createBarCodes(
        ):  #Unsure of the benefits downsides of using extended vs standard?
            if len(dfl('catalogNumber')) > 0:
                barcodeValue = dfl('catalogNumber')
            else:
                barcodeValue = self.settings.dummyCatNumber
            if barcodeValue:
                code39._Code39Base._humanText = newHumanText  #Note, overriding the human text from this library to omit the stopcode ('+')
                barcode39Std = code39.Standard39(
                    barcodeValue,
                    barHeight=(self.yPaperSize * .10),
                    barWidth=((self.xPaperSize * 0.28) /
                              (len(barcodeValue) * 13 + 35)),
                    humanReadable=True,
                    quiet=False,
                    checksum=0)
                #^^^Note width is dynamic, but I don't know the significe of *13+35 beyond making it work.
                return barcode39Std
            else:
                return ''

        elements = []  # a list to dump the flowables into for pdf generation
        for labelFieldsDict in labelDataInput:

            def dfl(key):  # dict lookup helper function
                value = labelFieldsDict.get(
                    key, '')  # return empty string if no result from lookup.
                return str(value)

        #Building list of flowable elements below

            if (len(dfl('catalogNumber')) > 0) | (self.settings.dummyCatNumber
                                                  != False):
                row0 = Table([[
                    Para('collectionName', 'collectionNameSTY'),
                    createBarCodes()
                ]],
                             colWidths=(self.xPaperSize * .67,
                                        self.xPaperSize * .29),
                             rowHeights=None,
                             style=[
                                 ('VALIGN', (0, 0), (0, -1), 'TOP'),
                                 ('ALIGN', (0, 0), (0, 0), 'LEFT'),
                                 ('ALIGN', (1, 0), (1, 0), 'RIGHT'),
                             ])
            else:
                row0 = Para('collectionName', 'collectionNameSTY')

            row1 = Table([[Para('labelProject', 'labelProjectSTY')],
                          [verifiedByPara('verifiedBy', 'verifiedBySTY')]],
                         colWidths=self.xPaperSize * .98,
                         rowHeights=None,
                         style=[('BOTTOMPADDING', (0, 0), (-1, -1), 2)])
            #bookmark
            #ScientificName Row Dynamic Formatting

            scientificNameElement = sciName('scientificName',
                                            'scientificNameAuthorship',
                                            'sciNameSTY')
            try:  #Test if Scienftific Name can Share a row with Event Date.
                scientificNameElement.wrap(
                    1400, 1400
                )  #Test wrap the string in a large environment to get it's desired ideal width.
                sciNameParaWidth = scientificNameElement.getActualLineWidths0(
                )[0]
                sciHeight = scientificNameElement.height

            except (AttributeError, IndexError) as e:
                sciNameParaWidth = 0
                sciHeight = 0

            if sciNameParaWidth > self.xPaperSize * .96:  #If the string is so large as to not fit, even alone then shrink font and split lines into two rows.
                row2 = Table(
                    [
                        [Para('eventDate', 'dateSTY')],
                        [
                            Spacer(width=self.xPaperSize * .98,
                                   height=sciHeight)
                        ],  #Add spacer between rows for formatting.
                        [
                            sciName('scientificName',
                                    'scientificNameAuthorship',
                                    'sciNameSTYSmall')
                        ]
                    ],
                    colWidths=self.xPaperSize * .98,
                    rowHeights=None,
                    style=tableSty)

            elif sciNameParaWidth > self.xPaperSize * -1:  #If the string is too big to share row with event date, split lines into rows.
                row2 = Table(
                    [
                        [Para('eventDate', 'dateSTY')],
                        [
                            Spacer(width=self.xPaperSize * .98,
                                   height=sciHeight)
                        ],  #Add spacer between rows for formatting.
                        [
                            sciName('scientificName',
                                    'scientificNameAuthorship', 'sciNameSTY')
                        ]
                    ],
                    colWidths=self.xPaperSize * .98,
                    rowHeights=None,
                    style=tableSty)
            else:
                row2 = Table([[
                    sciName('scientificName', 'scientificNameAuthorship',
                            'sciNameSTY'),
                    Para('eventDate', 'dateSTY')
                ]],
                             colWidths=(self.xPaperSize * .80,
                                        self.xPaperSize * .18),
                             rowHeights=None,
                             style=tableSty)

            row3 = Table([[Para('locality', 'default')]],
                         rowHeights=None,
                         style=tableSty)

            #Associated Taxa Dynamic Formatting
            if dfl(
                    'associatedTaxa'
            ) == '':  #If associated taxa is not used, give up the y space.
                associatedTaxaHeight = 0
                associatedTaxaStyle = 'defaultSTYSmall'  #This entire block is not functioning the way it was planned to.
            else:
                associatedTaxaHeight = .15 * self.yPaperSize  #Otherwise, devote some space, then test it's useage.
                associatedTaxaElement = Para(
                    'associatedTaxa', 'default',
                    'Associated taxa: ')  #Test build for height
                try:
                    associatedTaxaParaHeight = associatedTaxaElement.wrap(
                        self.xPaperSize * .98, 1
                    )[1]  #Test wrap the string in a large environment to get necessary height.
                except (AttributeError, IndexError) as e:
                    print('error ', e)
                    associatedTaxaParaHeight = 0

                if associatedTaxaParaHeight > associatedTaxaHeight:  #If the string is too large, reduce the font size.
                    associatedTaxaStyle = 'defaultSTYSmall'
                else:
                    associatedTaxaStyle = 'default'  #otherwise, use the normal height
            row4 = Table([[
                Para('associatedTaxa', associatedTaxaStyle,
                     'Associated taxa: ')
            ]],
                         rowHeights=None,
                         style=tableSty)
            #Note, associatedTaxa only reduces size if it is too large. At some extream point we'll need to consider trunication.

            if dfl('individualCount') != '':
                row5 = Table([[
                    Para('habitat', 'default', 'Habitat: '),
                    Para('individualCount', 'rightSTY', 'Approx. ≥ ',
                         ' on site.')
                ]],
                             colWidths=(self.xPaperSize * .68,
                                        self.xPaperSize * .30),
                             rowHeights=None,
                             style=[('VALIGN', (1, 0), (1, 0), 'CENTER'),
                                    ('ALIGN', (0, 0), (0, 0), 'LEFT'),
                                    ('ALIGN', (1, 0), (1, 0), 'RIGHT'),
                                    ('LEFTPADDING', (0, 0), (-1, -1), 0),
                                    ('RIGHTPADDING', (0, 0), (-1, -1), 0),
                                    ('TOPPADDING', (0, 0), (-1, -1), 0),
                                    ('BOTTOMPADDING', (0, 0), (-1, -1), 0)])
            else:
                row5 = Table([[Para('habitat', 'default', 'Habitat: ')]],
                             style=tableSty)

            if dfl(
                    'establishmentMeans'
            ) == 'cultivated':  #If establishmentMeans status is not 'cultivated' (based on cultivated status in mobile app) then forfit the space in case Substrate field is long.
                row6 = Table([[
                    Para('substrate', 'default', 'Substrate: '),
                    cultivationStatusChecker('establishmentMeans', 'rightSTY')
                ]],
                             colWidths=(self.xPaperSize * .68,
                                        self.xPaperSize * .30),
                             rowHeights=None,
                             style=tableSty)

            else:
                row6 = Table([[Para('substrate', 'default', 'Substrate: ')]],
                             style=tableSty)

            row7 = [
                collectedByPara('recordedBy', 'associatedCollectors',
                                'default', 'Collected by: ')
            ]

            row6_5 = Table(
                [[Para('locationRemarks', 'default', 'Location Remarks: ')]],
                style=tableSty)
            #Note locationRemarks is in testing, may not stay!

            row6_7 = Table(
                [[Para('occurrenceRemarks', 'default', 'Occurence Remarks: ')]
                 ],
                style=tableSty)

            if dfl('identifiedBy') != '':
                row7_5 = Table(
                    [[Para('identifiedBy', 'default', 'Determined by: ')]],
                    style=tableSty)
            # TODO: Add all tableList (row) objects to a loop which checks for content and appends else returns None
            # ...  Then Clean tableList for None objects

            tableList = [[row0], [row1], [row2], [row3], [row4], [row5],
                         [row6], [row6_5], [row6_7], [row7]]

            #Testing if GPS String can fit on one row with the field number. If not, split them into two rows.
            gpsStrElement = gpsCoordStringer('decimalLatitude',
                                             'decimalLongitude',
                                             'coordinateUncertaintyInMeters',
                                             'minimumElevationInMeters',
                                             'rightSTYSmall')
            try:
                gpsStrElement.wrap(self.xPaperSize * .98,
                                   self.yPaperSize * .98)
                try:
                    gpsParaWidth = gpsStrElement.getActualLineWidths0()[0]
                except IndexError:
                    gpsParaWidth = 0
            except AttributeError:
                gpsParaWidth = 0

            if gpsParaWidth > self.xPaperSize * .65:
                row8 = Table([[
                    Para('otherCatalogNumbers', 'default', 'Field Number: ')
                ]],
                             style=tableSty)
                row9 = Table([[gpsStrElement]], style=tableSty)
                tableList.append([row8])

                if dfl('identifiedBy') != '':
                    tableList.append([row7_5])

                tableList.append([row9])

            else:
                row8 = Table([[
                    Para('otherCatalogNumbers', 'default', 'Field Number: '),
                    gpsStrElement
                ]],
                             colWidths=(self.xPaperSize * .33,
                                        self.xPaperSize * .65),
                             rowHeights=None,
                             style=tableSty)
                tableList.append([row8])

                if dfl('identifiedBy') != '':
                    tableList.append([row7_5])

            # append the determined by field

            docTableStyle = [  #Cell alignment and padding settings (not text align within cells)
                ('VALIGN', (0, 3), (0, -1),
                 'BOTTOM'),  #Rows 4-end align to bottom
                ('ALIGN', (0, 0), (-1, -1),
                 'CENTER'),  #All rows align to center
                ('LEFTPADDING', (0, 0), (-1, -1),
                 0),  #ALL Rows padding on left to none
                ('RIGHTPADDING', (0, 0), (-1, -1),
                 0),  #ALL Rows padding on right to none
                ('TOPPADDING', (0, 0), (-1, -1),
                 3),  #ALL Rows padding on top to none
                ('BOTTOMPADDING', (0, 0), (-1, -1),
                 0),  #ALL Rows padding on Bottom to none
                ('BOTTOMPADDING', (0, 0), (0, 0),
                 3),  #ALL Rows padding on Bottom to none
                ('TOPPADDING', (0, 1), (0, 1), 6),  #Row 2 top padding to 6
                ('TOPPADDING', (0, 2), (0, 2), 6),  #Row 3 top padding to 6
                ('BOTTOMPADDING', (0, 2), (0, 2),
                 6),  #Row 3 bottom padding to 6
                #('NOSPLIT', (0,0),(-1,-1)),          #Makes Error if it won't fit. We should raise this error to user!
            ]

            docTable = Table(
                tableList,
                style=docTableStyle)  #build the table to test it's height

            wid, hei = docTable.wrap(
                0, 0)  #Determines how much space is used by the table
            spaceRemaining = (self.yPaperSize - hei - 10
                              )  #Determine how much is left on the page
            spaceFiller = [
                Spacer(width=0, height=(spaceRemaining / 3))
            ]  #assign half the remaining space to a filler (to distrib into two places.
            tableList.insert(
                4, spaceFiller
            )  #build from bottom up because it is less confusing for the index values.
            tableList.insert(3, spaceFiller)
            tableList.insert(2, spaceFiller)

            docTable = Table(tableList,
                             style=docTableStyle)  #build the final table

            #Add the flowables to the elements list.
            elements.append(docTable)
            elements.append(PageBreak())

        #Build the base document's parameters.

        if returnBytes:  # if we only want to make a preview save it to a stream
            byteStream = io.BytesIO()
            labelFileName = byteStream

        elif defaultFileName:
            labelFileName = defaultFileName
            #labelFileName, _ = QFileDialog.getSaveFileName(None, 'Save Label PDF', defaultFileName, 'PDF(*.pdf)')
        else:
            labelFileName, _ = QFileDialog.getSaveFileName(
                None, 'Save Label PDF', os.getenv('HOME'), 'PDF(*.pdf)')

        if not labelFileName:  # If the user canceled the dialog
            return
        # TODO fill in title and author based on select form_view or settings info
        doc = BaseDocTemplate(labelFileName,
                              pagesize=self.customPageSize,
                              pageTemplates=[],
                              showBoundary=0,
                              leftMargin=self.xMargin,
                              rightMargin=self.xMargin,
                              topMargin=self.yMargin,
                              bottomMargin=self.yMargin,
                              allowSplitting=self.allowSplitting,
                              title=None,
                              author=None,
                              _pageBreakQuick=1,
                              encrypt=None)

        #Function to build the pdf

        def build_pdf(flowables):
            """ actually loads the flowables into the document """

            doc.addPageTemplates([
                PageTemplate(onPage=self.labelSetup,
                             frames=[
                                 platypusFrame(doc.leftMargin,
                                               doc.bottomMargin,
                                               doc.width,
                                               doc.height,
                                               topPadding=0,
                                               bottomPadding=0,
                                               id=None),
                             ]),
            ])
            try:
                doc.build(flowables)
            except LayoutError:
                raise LayoutError

        try:
            build_pdf(elements)
        except LayoutError:
            # if there is a layout error, raise it
            raise LayoutError

        if returnBytes:  # If a preview is being generated just return the bytes
            # calling the byte stream "labelFileName" is a fast and dirty
            # workaround to keep existing code functional
            pdfBytes = labelFileName.getvalue(
            )  # save the stream to a variable
            labelFileName.close()  # close the buffer down
            return pdfBytes  # return the results

        #Open the file after it is built (maybe change/remove this later? Idealy, a preview or something

        def open_file(filename):
            if sys.platform == "win32":
                os.startfile(filename)
            else:
                opener = "open" if sys.platform == "darwin" else "xdg-open"
                subprocess.call([opener, filename])

        open_file(labelFileName)
Esempio n. 27
0
def run(data):
    data = data.split(';')
    if data[0] == 'dosen':
        dosenID = data[1]
        tahunID = data[2]
        email = data[3]
        tipe = data[4]
        
        df = pd.read_excel(f'jadwal_sidang_ta_14.xlsx')
        listPem = ['npm', 'koor', 'tipe', 'tahun']
        df = df.loc[:, listPem]
        df = df.drop_duplicates()
        npms = df.loc[(df["koor"] == dosenID) & (df["tahun"] == int(tahunID)), ['npm']].values.tolist()
        
        checkDir(f'./revisisidang/pengesahan/')
        namaFile = f"revisisidang\\pengesahan\\pengesahan-sidang-{tahunID}-{dosenID}.pdf"
        doc = SimpleDocTemplate(namaFile,
                    pagesize=A4,
                    rightMargin=3*cm,
                    leftMargin=4*cm,
                    topMargin=4*cm,
                    bottomMargin=3*cm)

        contain=[]
        styles=getSampleStyleSheet()
        styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY, fontName='Times', fontSize=12))
        styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER, fontName='Times', fontSize=12))
        styles.add(ParagraphStyle(name='CenterSpacing', alignment=TA_CENTER, fontName='Times', fontSize=12, leading=18))
        
        try:
            for npm in npms:
                npm = npm[0]
                if checkStatusSidang(npm, tahunID, tipe):                
                    makePdf(str(npm), tipe, tahunID, email, contain, styles)
                    contain.append(PageBreak())
            else:
                pass
        except Exception as e:
            print(str(e))
        
        doc.build(contain)
        time.sleep(2)
        sendEmail(email, f'pengesahan-sidang-{tahunID}-{dosenID}.pdf', dosenID)
        print("udh cuy")
        
    elif data[0] == 'mahasiswa':
        npm = data[1]
        tahunID = data[2]
        email = data[3]
        kategori = data[4]
        
        checkDir(f'./revisisidang/pengesahan/')
        namaFile = f"revisisidang\\pengesahan\\pengesahan-sidang-{tahunID}-{npm}.pdf"
        doc = SimpleDocTemplate(namaFile,
                            pagesize=A4,
                            rightMargin=3*cm,
                            leftMargin=4*cm,
                            topMargin=4*cm,
                            bottomMargin=3*cm)

        contain=[]
        styles=getSampleStyleSheet()
        styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY, fontName='Times', fontSize=12))
        styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER, fontName='Times', fontSize=12))
        styles.add(ParagraphStyle(name='CenterSpacing', alignment=TA_CENTER, fontName='Times', fontSize=12, leading=18))
        
        makePdf(npm, kategori, tahunID, email, contain, styles)
        
        doc.build(contain)
        time.sleep(2)
        sendEmail(email, f'pengesahan-sidang-{tahunID}-{npm}.pdf', npm)
        print("udh coy")
Esempio n. 28
0
        def procesoPpal(Story):
            """ Creación del informe. """

            I = Image("manifiestos/manifest/static/manifest/logo-horizontal.jpg", width=136, height=42)
            Comprobante = Paragraph("Comprobantes # " + data['manifest']['id'], estilo['Comprobante'])

            t = Table(
                data = [
                    [Comprobante]
                ],
                style=[
                    ('VALIGN',(0,0),(0,0),'CENTER'),
                    ('BOTTOMPADDING', (0, 0),(0, 0), 25),
                ], 
                colWidths=[550], hAlign='LEFT',
            )

            Story.append(t)

            # Datos del formato

            datoformato1 = Paragraph('''<b>Codigo:</b> OPE_FOR_002''', estilo['datosFormato'])
            datoformato2 = Paragraph('''<b>Version:</b> 03''', estilo['datosFormato'])
            datoformato3 = Paragraph('''<b>Fecha de vigencia:</b> 02/01/2017''', estilo['datosFormato'])

            t = Table(
                data = [
                    [I, datoformato1],
                    ['', datoformato2],
                    ['', datoformato3],
                ],
                style=[
                    ('VALIGN',(0,0),(0,0),'CENTER'),
                    ('GRID',(0,0),(1,2),0.5,colors.gray),
                    ('SPAN', (0, 0),(0, 2)),
                    ('BOX', (0,0), (1,2), 0.5, colors.black),
                ], 
                colWidths=[144, 200], 
                hAlign='LEFT',
            )

            Story.append(t)

            ecoCapital = Paragraph('ECOCAPITAL | NIT 900.487.187-3 | Carrera 19A No 61-11', estilo['datosFormato'])
            planned_date = Paragraph('''<b>FECHA FRECUENCIA: </b>''' + data['manifest']['planned_date'], estilo['datosFormato'])
            date = Paragraph('''<b>Fecha de Recoleccion: </b>''' + data['manifest']['date'] + 
                ''' | <b>Código</b> ''' + data['manifest']['client']['code_eco'], estilo['datosFormato'])
            client = Paragraph(data['manifest']['client']['name'], estilo['client'])
            geoInformacion = Paragraph(data['manifest']['client']['geoinformation']['address'] + 
                ' | ' + '''<b>NIT o CC </b>''' + data['manifest']['client']['id'], estilo['datosFormato'])
            transmDatos = Paragraph('''Transmisión de datos / <b>Inicio: </b>''' + data['manifest']['start_time'] + 
                ''' - <b>Final: </b>''' + data['manifest']['end_time'], estilo['datosFormato'])
            recoge = Paragraph('''<b>Recoge: </b>''' + data['manifest']['fleet']['driver']['name'] + 
                ''' | <b>CC</b> ''' + data['manifest']['fleet']['driver']['id'], estilo['datosFormato'])
            placa = Paragraph('''<b>Placa: </b>''' +  data['manifest']['fleet']['license_plate'] + " " +
                '''<b>Ruta: </b> ''' + data['manifest']['fleet']['route'], estilo['datosFormato'])

            t = Table(
                data = [
                    [ecoCapital],
                    [planned_date],
                    [date],
                    [client],
                    [geoInformacion],
                    [transmDatos],
                    [recoge],
                    [placa],
                ],
                style=[
                    ('VALIGN',(0,0),(-1,-1),'CENTER'),
                    ('TOPPADDING', (0, 0),(-1, -1), 10),
                ], 
                colWidths=[550], 
                hAlign='LEFT',
            )

            Story.append(t)

            produc1 = Paragraph(data['manifest']['production'][0]['units'] + '''<b> Producción </b> ''' + 
                data['manifest']['production'][0]['tag'], estilo['datosRecogida'])
            cantidadProduc1 = Paragraph(data['manifest']['production'][0]['total_value'], estilo['Normal'])
            produc2 = Paragraph(data['manifest']['production'][1]['units'] + '''<b> Producción </b> ''' + 
                data['manifest']['production'][1]['tag'], estilo['datosRecogida'])
            cantidadProduc2 = Paragraph(data['manifest']['production'][1]['total_value'], estilo['Normal'])
            produc3 = Paragraph(data['manifest']['production'][2]['units'] + '''<b> Producción </b> ''' + 
                data['manifest']['production'][2]['tag'], estilo['datosRecogida'])
            cantidadProduc3 = Paragraph(data['manifest']['production'][2]['total_value'], estilo['Normal'])
            produc4 = Paragraph(data['manifest']['production'][3]['units'] + '''<b> Producción </b> ''' + 
                data['manifest']['production'][3]['tag'], estilo['datosRecogida'])
            cantidadProduc4 = Paragraph(data['manifest']['production'][3]['total_value'], estilo['Normal'])

            termoRecambio = Paragraph("# " + data['manifest']['items'][0]['tag'] + " Recambio", estilo['datosRecogida'])
            cantidadTermRecambio = Paragraph(data['manifest']['items'][0]['exchanged'], estilo['Normal'])
            termoRecogido = Paragraph("# " + data['manifest']['items'][0]['tag'] + " Recogidos", estilo['datosRecogida'])
            cantidadTermRecogido = Paragraph(data['manifest']['items'][0]['picked_up'], estilo['Normal'])
            termoAsig = Paragraph("# " + data['manifest']['items'][0]['tag'] + " Asignados", estilo['datosRecogida'])
            cantidadTermAsig = Paragraph(data['manifest']['items'][0]['delivered'], estilo['Normal'])

            estRecambio = Paragraph("# " + data['manifest']['items'][1]['tag'] + " Recambio", estilo['datosRecogida'])
            cantidadEstRecambio = Paragraph(data['manifest']['items'][1]['exchanged'], estilo['Normal'])
            estRecogido = Paragraph("# " + data['manifest']['items'][1]['tag'] + " Recogidos", estilo['datosRecogida'])
            cantidadEstRecogido = Paragraph(data['manifest']['items'][1]['picked_up'], estilo['Normal'])
            estAsig = Paragraph("# " + data['manifest']['items'][1]['tag'] + " Asignados", estilo['datosRecogida'])
            cantidadestAsig = Paragraph(data['manifest']['items'][1]['delivered'], estilo['Normal'])

            textoNovedad = Paragraph("Novedad", estilo['datosRecogida'])
            tipoNovedad = Paragraph(data['manifest']['novelties'][0]['comment'], estilo['Normal'])
            textObs = Paragraph("Observaciones: ", estilo['datosRecogida'])

            t = Table(
                data = [
                    [[produc1], [cantidadProduc1]],
                    [[produc2], [cantidadProduc2]],
                    [[produc3], [cantidadProduc3]],
                    [[produc4], [cantidadProduc4]],
                    [[termoRecambio], [cantidadTermRecambio]],
                    [[termoRecogido], [cantidadTermRecogido]],
                    [[termoAsig], [cantidadTermAsig]],
                    [[estRecambio], [cantidadEstRecambio]],
                    [[estRecogido], [cantidadEstRecogido]],
                    [[estAsig], [cantidadestAsig]],
                    [[textoNovedad], [tipoNovedad]],
                    [[textObs]],
                ],
                style=[
                    ('VALIGN',(0,0),(-1,-2),'CENTER'),
                    ('TOPPADDING', (0, 0),(-1, -1), 10),
                ], 
                colWidths=[250, 250], 
            )

            Story.append(t)
            Story.append(PageBreak())

            textEvidencia = Paragraph(data['manifest']['novelties'][0]['evidence_type'] + " Novedad", estilo['Normal'])
            I = Image(data['manifest']['novelties'][0]['file'], width=170, height=150)
            textFirma1 = Paragraph("Firma quien entrega", estilo['Normal'])
            signaClient = Image(data['manifest']['signatures'][1]['signature_file'], width=170, height=150)
            textFirma2 = Paragraph("Firma quien recoge", estilo['Normal'])
            signaEmployee = Image(data['manifest']['signatures'][3]['signature_file'], width=170, height=150)
            finalText = Paragraph("El presente manifiesto no se constituye como acta de tratamiento y/o disposición final, por tanto su validez únicamente corresponde a la del manifiesto de recolección y transporte de residuos de riesgo biológico", estilo['Normal'])

            t = Table(
                data = [
                    [textEvidencia],
                    [I],
                    [textFirma1],
                    [signaClient],
                    [textFirma2],
                    [signaEmployee],
                    [finalText],
                ],
                style=[
                    ('VALIGN',(0,0),(0,0),'CENTER'),
                    ('TOPPADDING', (0, 0),(0, 0), 10),
                ], 
                colWidths=[500], 
            )

            Story.append(t)

            return Story
Esempio n. 29
0
    def __transactions(self):
        self.l -= 20
        self.c.setFont('Courier', 14)
        self.c.drawString(30, self.l, 'Movimientos')

        header = ['Fecha', 'Tipo', 'Cuenta', 'Monto', 'Description']
        data = [header]

        for tra in self.transactions:
            tipo = self.__translate_type(tra.t_type)
            data.append([tra.date, tipo.upper(), tra.account,
                '$%.2f' % tra.amount, tra.description])

        registros = 24
        filas = len(data) / float(registros)
        coheficiente = math.ceil(len(data) / filas)
        look = 0
        datas = list()
        datas_new = list()

        while look < len(data):
            second = int(look+coheficiente)
            datas.append(data[look:second])
            look = int(look+coheficiente)

        datas_new.append(datas[0])

        for dd in datas[1:][::-1]:
            datas_new.append([header] + dd)

        data1 = datas_new[0]
        self.l -= len(data1) * 19
        t = Table(data1)
        t.setStyle(TableStyle([('INNERGRID', (0,0), (-1,-1), 0.25, black),
            ('BOX', (0,0), (-1,-1), 0.25, black),
            ('FONTNAME', (0,0), (-1,0), 'Courier-Bold'),
            ('BACKGROUND', (0,0), (-1,0), HexColor('#efeded')),
            ('BACKGROUND', (0,0), (0,-1), HexColor('#efeded')),
            ('FONTSIZE', (0,0), (-1,0), 12),
            ('FONTSIZE', (0,1), (-1,-1), 8),
            ('FONTNAME', (0,1), (-1,-1), 'Courier')]))
        t.wrapOn(self.c, 30, self.l)
        t.drawOn(self.c, 30, self.l)

        for dd in datas_new[1:][::-1]:
            p = PageBreak()
            p.drawOn(self.c, 0, 1000)
            self.c.showPage()
            self.l = 800 - (len(dd) * 19)

            t2 = Table(dd)
            t2.setStyle(TableStyle([('INNERGRID', (0,0), (-1,-1), 0.25, black),
                ('BOX', (0,0), (-1,-1), 0.25, black),
                ('FONTNAME', (0,0), (-1,0), 'Courier-Bold'),
                ('BACKGROUND', (0,0), (-1,0), HexColor('#efeded')),
                ('BACKGROUND', (0,0), (0,-1), HexColor('#efeded')),
                ('FONTSIZE', (0,0), (-1,0), 12),
                ('FONTSIZE', (0,1), (-1,-1), 8),
                ('FONTNAME', (0,1), (-1,-1), 'Courier')]))
            t2.wrapOn(self.c, 30, self.l)
            t2.drawOn(self.c, 30, self.l)
Esempio n. 30
0
    def draw(self,canvas,doc):
        
        self.createTables()
        
        ##########
        def firstPage(canvas, doc):
            canvas.saveState()
            cumHeight = self.drawHeaderOnCanvas(canvas, doc)

            ### Unique to Page 1
            pPage1 = Paragraph("Only Applicable Limits Shown:", TableOptions.styleN)
            w, h = pPage1.wrap(doc.width, doc.topMargin)
            pPage1.drawOn(canvas, doc.leftMargin - TableOptions.marginXOffset, TableOptions.pageHeight - cumHeight - 30)

            self.drawFooterOnCanvas(canvas, doc)
            canvas.restoreState()

        ##########
        def mySecondPage(canvas, doc):

            canvas.saveState()
            cumHeight = self.drawHeaderOnCanvas(canvas, doc)

            ### Unique to Page 2
            pPage2 = Paragraph("All Calculations Shown:", TableOptions.styleN)
            w, h = pPage2.wrap(doc.width, doc.topMargin)
            pPage2.drawOn(canvas, doc.leftMargin - TableOptions.marginXOffset, TableOptions.pageHeight - cumHeight - 30)

            self.drawFooterOnCanvas(canvas, doc)
            canvas.restoreState()

        templateFrame = Frame(0.5 * inch, 1.0 * inch, 7.5 * inch, 8.5 * inch, id='templateFrame')
        pageTemplate1 = PageTemplate(id='pageTemplate1', frames=[templateFrame], onPage=firstPage)
        pageTemplate2 = PageTemplate(id='pageTemplate2', frames=[templateFrame], onPage=mySecondPage)

        Story = []
        
        tableheaderStyle = TableOptions.styleH
        tableheaderStyle.fontSize = 10
        for i in range(len(self.applicableTables)):
            
            table = self.applicableTables[i]
            
            ### Create Grouping Header Paragraph
            grouping = self.categoryOrder[i]
            formalGrouping = limitReportPDF.categoryFormalNames[grouping]
            categoryParagraph = Paragraph(formalGrouping, tableheaderStyle)
            
            Story.append(categoryParagraph)
            Story.append(table)
            Story.append(TableOptions.vspace)

        Story.append(NextPageTemplate('pageTemplate2'))
        Story.append(PageBreak())
        
        for i in range(len(self.nonApplicableTables)):
            table = self.nonApplicableTables[i]
            
            ### Create Grouping Header Paragraph
            grouping = self.categoryOrder[i]
            formalGrouping = limitReportPDF.categoryFormalNames[grouping]
            categoryParagraph = Paragraph(formalGrouping, tableheaderStyle)
            
            Story.append(categoryParagraph)
            Story.append(table)
            Story.append(TableOptions.vspace)
            
        Story.append(PageBreak())
        
        doc.addPageTemplates([pageTemplate1, pageTemplate2])
        doc.build(Story)

        return canvas
Esempio n. 31
0
    Report.append(Paragraph(ptext, styles["Center"]))
    Report.append(Spacer(1, 30))
    ptext = '<font size=16>Case: <b>%s</b></font>' % case
    Report.append(Paragraph(ptext, styles["Center"]))
    Report.append(Spacer(1, 50))

    # Create return address
    ptext = '<font size=12><b>%s</b></font>' % full_name
    Report.append(Paragraph(ptext, styles["Center"]))
    Report.append(Spacer(1, 20))

    for part in address_parts:
        ptext = '<font size=12>%s</font>' % part.strip()
        Report.append(Paragraph(ptext, styles["Center"]))

    Report.append(PageBreak())
    success = True
    if data:
        if "system" in data:
            try:
                ptext = '<img src="data/img/system.png" valign="-15" /><font size=16 name="Times-Roman">' \
                        '<b>  System Analysis</b></font>'
                Report.append(Paragraph(ptext, styles["Left"]))
                Report.append(Spacer(1, 40))

                system_string = ""
                system = data["system"][1]
                tmp = system["path"].split(";")
                path = list_to_string(tmp)

                system_string += "<b>Computer Name: </b> " + str(
Esempio n. 32
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)
Esempio n. 33
0
    def __init__(self, id):
        """Constructor de la clase que genera una factura .
                             Excepciones:
                                -dbapi2.DatabaseError
                        """
        idFactura = id
        factura = []

        factura.append(list(['', '', 'VentasDia', '', '']))
        try:
            ###Conectamos con la base de datos
            baseDatos = dbapi2.connect("BaseDeDatos.dat")
            cursor = baseDatos.cursor()
            detalles = cursor.execute(
                "select nombreCliente,direccion,telefono,correo from facturasClientes where idFactura='"
                + idFactura + "'")

            for cliente in detalles:
                factura.append([
                    'Nombre Cliente: ', cliente[0], '', 'Nº Factura: ',
                    idFactura
                ])
                factura.append(['Direccion: ', cliente[1], '', '', ''])
                factura.append(['Telefono: ', cliente[2], '', '', ''])
                factura.append(['Correo: ', cliente[3], '', '', ''])

        except (dbapi2.DatabaseError):
            print("ERROR BD")
        finally:
            print("Cerramos conexion BD")
            cursor.close()
            baseDatos.close()

        factura.append(list(['', '', '', '', '']))
        factura.append(
            ['CODIGO', 'PRODUCTO', 'CANTIDAD', 'PRECIO/UNI', 'PRECIO'])

        try:
            ###Conectamos con la base de datos
            baseDatos = dbapi2.connect("BaseDeDatos.dat")
            cursor = baseDatos.cursor()

            listaProductos = []
            total = 0
            productos = cursor.execute(
                "select id,nombre,precioUnidad from productos")
            for producto in productos:
                listaProductos.append([producto[0], producto[1], producto[2]])

            detalesFactura = cursor.execute(
                "select idProducto,cantidad from facturasInfo where idFactura='"
                + idFactura + "'")
            for pro in detalesFactura:
                for prod in listaProductos:
                    precio2 = 0
                    if (prod[0] == pro[0]):
                        precio = int(pro[1]) * float(prod[2])
                        precio2 = precio
                        factura.append(
                            [prod[0], prod[1], pro[1], prod[2], precio])
                total = total + precio2
            factura.append(['', '', '', 'PRECIO TOTAL:', str(total) + " €"])
        except (dbapi2.DatabaseError):
            print("ERROR BD")
        finally:
            print("Cerramos conexion BD")
            cursor.close()
            baseDatos.close()

        print(factura)

        doc = SimpleDocTemplate("factura.pdf", pagesize=A4)

        guion = []

        taboa = Table(factura, colWidths=90, rowHeights=30)
        taboa.setStyle(
            TableStyle([('TEXTCOLOR', (0, 0), (-1, -1), colors.darkgreen),
                        ('TEXTCOLOR', (0, 1), (-1, -1), colors.black),
                        ('ALIGN', (2, 5), (-1, -1), 'RIGHT'),
                        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                        ('BOX', (0, 1), (-1, 4), 1, colors.black),
                        ('BOX', (0, 6), (-1, -2), 1, colors.black),
                        ('INNERGRID', (0, 6), (-1, -2), 0.5, colors.grey)]))

        guion.append(taboa)
        guion.append(PageBreak())

        doc.build(guion)
elems.append(P)
elems.append(S1)
P = Paragraph("Table Of Contents", style=style_header)
elems.append(P)
elems.append(S0)
P = Paragraph('Accuracy', style=style_text, bulletText='-')
elems.append(P)
P = Paragraph('Precision', style=style_text, bulletText='-')
elems.append(P)
P = Paragraph('Sensitivity', style=style_text, bulletText='-')
elems.append(P)
P = Paragraph('Specificity', style=style_text, bulletText='-')
elems.append(P)
P = Paragraph('Appendix', style=style_text, bulletText='-')
elems.append(P)
elems.append(PageBreak())

############
##  accuracy
############
P = Paragraph("I. ACCURACY", style=style_header)
elems.append(P)
elems.append(S1)
P = Paragraph(
    "In this section we are assessing the analytical accuracy of Guardant360 CDx (G360 CDx). To quantify accuracy for G360, we compare results obtained"
    "to an external orthognal validator conducted by MD Anderson Cancer Center, where we treat the latter as the 'ground truth', and thus allowing us to"
    "quantify and compare the analytical accuracy across the entire pane and the reportable range. For the purpose of this study three sample collections were"
    "made. Aliquots from these samples were taken and tested once by Guardant360 CDx and another by LBP70 (MD Anderson). Accuracy in this context was quantified"
    "as Positive Percent Agreement (PPA) and Negative Percent Agreement (NPA), between the two methods. PPA here is defined as the proportion of variants detected"
    "by G360 CDx, in comparison to the total number of variants in the samples (presented by LBP70). Similarly NPA is defined as the proportion of the variants "
    "not detected by G360 CDx in comparison to the total number of variants not detected by LBP70. We quantify and compare PPA and NPA over all variants between the"
Esempio n. 35
0
    def __get_tags_statistics(self):
        monto_categorias = dict()
        for tra in self.transactions:
            if len(tra.tags) > 0:
                for tag in tra.tags:
                    if tag in monto_categorias.keys():
                        monto_categorias[tag] += tra.amount
                    else:
                        monto_categorias[tag] = tra.amount

        labels = [lab.encode('utf-8') for lab in monto_categorias.keys()]
        data = monto_categorias.values()

        p = PageBreak()
        p.drawOn(self.c, 0, 1000)
        self.c.showPage()
        self.l = 600

        self.c.setFont('Courier', 14)
        self.c.drawString(30, 800, 'Categorias')

        drawing = Drawing(200, 200)

        pie = Pie()
        pie.x = 30
        pie.y = self.l - 130
        pie.height = 300
        pie.width = 300
        pie.data = data
        pie.labels = labels
        pie.simpleLabels = 1
        pie.slices.strokeWidth = 1
        pie.slices.strokeColor = black
        pie.slices.label_visible = 0

        legend = Legend()
        legend.x = 400
        legend.y = self.l
        legend.dx              = 8
        legend.dy              = 8
        legend.fontName        = 'Helvetica'
        legend.fontSize        = 7
        legend.boxAnchor       = 'w'
        legend.columnMaximum   = 10
        legend.strokeWidth     = 1
        legend.strokeColor     = black
        legend.deltax          = 75
        legend.deltay          = 10
        legend.autoXPadding    = 5
        legend.yGap            = 0
        legend.dxTextSpace     = 5
        legend.alignment       = 'right'
        legend.dividerLines    = 1|2|4
        legend.dividerOffsY    = 4.5
        legend.subCols.rpad    = 30
        n = len(pie.data)
        self.__setItems(n,pie.slices,
            'fillColor',self.pdf_chart_colors)

        legend.colorNamePairs = [(pie.slices[i].fillColor, 
            (pie.labels[i][0:20],'$%0.2f' % pie.data[i])) for i in xrange(n)]

        drawing.add(pie)
        drawing.add(legend)
        x, y = 0, 10

        renderPDF.draw(drawing, self.c, x, y, showBoundary=False)