Ejemplo n.º 1
0
def flow_and_dividends_block(df: pd.DataFrame, block_position: BlockPosition):
    """Формирует блок pdf-файла с информацией движении средств и дивидендах.

    В левой части располагается табличка движения средств, а в правой - таблица дивидендов.
    """
    left_block_header = platypus.Paragraph("Last Month Change and Inflow", BLOCK_HEADER_STYLE)
    left_table = make_pdf_flow(df)
    left_frame = platypus.Frame(
        block_position.x,
        block_position.y,
        block_position.width * LEFT_PART_OF_BLOCK,
        block_position.height,
        leftPadding=0,
        bottomPadding=0,
        rightPadding=0,
        topPadding=6,
        showBoundary=0,
    )
    left_frame.addFromList([left_block_header, left_table], block_position.canvas)
    right_block_header = platypus.Paragraph("Portfolio Dividends", BLOCK_HEADER_STYLE)
    right_table = make_pdf_dividends(df)
    right_frame = platypus.Frame(
        block_position.x + block_position.width * LEFT_PART_OF_BLOCK,
        block_position.y,
        block_position.width * (1 - LEFT_PART_OF_BLOCK),
        block_position.height,
        leftPadding=0,
        bottomPadding=0,
        rightPadding=0,
        topPadding=6,
        showBoundary=0,
    )
    right_frame.addFromList([right_block_header, right_table], block_position.canvas)
Ejemplo n.º 2
0
def story_title(survey, info=dict()):
    story = [
        platypus.Paragraph(str(line), stylesheet['Title'])
        for line in survey.title.split('\n')
    ]
    story += [
        platypus.FrameBreak(),
    ]

    keys = list(survey.info.keys())
    if keys:
        keys.sort()
        table = [[
            platypus.Paragraph(str(key), stylesheet['Normal']),
            platypus.Paragraph(str(survey.info[key]), stylesheet['Normal'])
        ] for key in keys]
        story += [
            platypus.Table(table, colWidths=(50 * mm, None)),
        ]
    if info:
        story += [platypus.Spacer(0, 10 * mm)]
        keys = list(info.keys())
        keys.sort()
        table = [[
            platypus.Paragraph(str(key), stylesheet['Normal']),
            platypus.Paragraph(str(info[key]), stylesheet['Normal'])
        ] for key in keys]
        story += [
            platypus.Table(table, colWidths=(50 * mm, None)),
        ]

    story += [platypus.NextPageTemplate('Normal'), platypus.PageBreak()]
    return story
Ejemplo n.º 3
0
 def _flowable(self, n):
     tags = {
         'name': lambda node: self.__name(node),
         'para': lambda node: platypus.Paragraph(self._textual(node), self.styles.para_style_get(node), **(utils.attr_get(node, [], {'bulletText': 'str'}))),
         'xpre': lambda node: platypus.XPreformatted(self._textual(node), self.styles.para_style_get(node), **(utils.attr_get(node, [], {'bulletText': 'str', 'dedent': 'int', 'frags': 'int'}))),
         'pre': lambda node: platypus.Preformatted(self._textual(node), self.styles.para_style_get(node), **(utils.attr_get(node, [], {'bulletText': 'str', 'dedent': 'int'}))),
         'illustration': lambda node: self._illustration(node),
         'blockTable': lambda node: self._table(node),
         'title': lambda node: platypus.Paragraph(self._textual(node), reportlab.lib.styles.getSampleStyleSheet()['Title'], **(utils.attr_get(node, [], {'bulletText': 'str'}))),
         'h1': lambda node: platypus.Paragraph(self._textual(node), reportlab.lib.styles.getSampleStyleSheet()['Heading1'], **(utils.attr_get(node, [], {'bulletText': 'str'}))),
         'h2': lambda node: platypus.Paragraph(self._textual(node), reportlab.lib.styles.getSampleStyleSheet()['Heading2'], **(utils.attr_get(node, [], {'bulletText': 'str'}))),
         'h3': lambda node: platypus.Paragraph(self._textual(node), reportlab.lib.styles.getSampleStyleSheet()['Heading3'], **(utils.attr_get(node, [], {'bulletText': 'str'}))),
         'image': lambda node: platypus.Image(node.getAttribute('file'), mask=(250, 255, 250, 255, 250, 255), **(utils.attr_get(node, ['width', 'height', 'preserveAspectRatio', 'anchor']))),
         'spacer': lambda node: platypus.Spacer(
             width=utils.unit_get(node.getAttribute('width') if node.hasAttribute('width') else '1cm'),
             height=utils.unit_get(node.getAttribute('length'))),
         'barCode': lambda node: code39.Extended39(self._textual(node)),
         'pageBreak': lambda node: platypus.PageBreak(),     # FIXME: it is not in RML std
         'nextPage': lambda node: platypus.PageBreak(),
         'condPageBreak': lambda node: platypus.CondPageBreak(**(utils.attr_get(node, ['height']))),
         'setNextTemplate': lambda node: platypus.NextPageTemplate(str(node.getAttribute('name'))),
         'nextFrame': lambda node: platypus.CondPageBreak(1000),  # TODO: change the 1000 !
         'ul': lambda node: self._list(node),
         'keepInFrame': lambda node: self.__keep_in_frame(node),
     }
     retvalue = tags.get(n.localName)
     if retvalue:
         return retvalue(n)
     else:
         sys.stderr.write('Warning: flowable not yet implemented: %s !\n' % (n.localName,))
Ejemplo n.º 4
0
    def _create(self):
        """
        Does the final creation of the Platypus Table object.
        Including a correct numeration for the Table of Tables list.

        Typically this Method will be called by the _PreBuild-Method of
        the Story class.

        :return: story with all final objects for pdf rendering
        :rtype: list of platypus objects ready for rendering.
        """
        self._style = [('BACKGROUND', (0, 0), (1, 0), colors.lightgrey),
                       ('GRID', (0, 0), (-1, -1), 1.0, colors.black)]

        data = [build_table_header(['Testcase', 'Description'])]

        for testcase in self._testcases:
            data.append([plat.Paragraph(html_str(testcase.name), NORMAL_STYLE),
                         plat.Paragraph(html_str(testcase.description), NORMAL_STYLE)])

        story = []

        table = plat.Table(data, style=self._style)

        story.append(table)
        self.append_caption(story)

        return story
Ejemplo n.º 5
0
def build_table_row(row_items, col_filter=None, style=NORMAL_SPLIT):
    """
    Create one row with given item, format to fit into column

    internal: creates platypus.Paragraph for each str entry using given style
    that allows to get word wrap active in the cells

    :param row_items: list of items to format in columns of a row
    :type row_items:  list[item, ...]
    :param col_filter: opt filter list to leave out columns (see `filter_cols()`)
    :type  col_filter: list[True, False, ...]
    :param style: opt style setting, default: NORMAL_STYLE
    :type  style: platypus.ParagraphStyle

    :return: ReportLab table row
    :rtype:  list[Paragraph]
    """
    row = []
    for item in filter_cols(row_items, col_filter):
        if type(item) in (int, float, complex) or isinstance(
                item, six.integer_types):
            row.append(plat.Paragraph(str(item), style))
        elif type(item) is str:
            row.append(plat.Paragraph(item, style))
        else:
            row.append(item)
    return row
Ejemplo n.º 6
0
 def make_paragraph(self,
                    txt,
                    style=None,
                    attributes="",
                    keep_with_next=False):
     if attributes:
         xmltxt = '<para %s>%s</para>' % (attributes, txt)
     else:
         xmltxt = '<para>%s</para>' % txt
     if not style: style = self.styleSheet['Normal']
     try:
         if PASS_REPORTLAB_UNICODE:
             return platypus.Paragraph(unicode(xmltxt), style)
         else:
             return platypus.Paragraph(
                 unicode(xmltxt).encode('iso-8859-1', 'replace'), style)
     except UnicodeDecodeError:
         try:
             #print 'WORK AROUND UNICODE ERROR WITH ',txt[:20]
             # This seems to be the standard on windows.
             platypus.Paragraph(xmltxt, style)
         except:
             print 'Trouble with ', xmltxt
             raise
     except:
         # Try escaping text...
         print 'TROUBLE WITH', txt[:20], 'TRYING IT ESCAPED...'
         return self.make_paragraph(xml.sax.saxutils.escape(txt), style,
                                    attributes, keep_with_next)
Ejemplo n.º 7
0
 def _flowable(self, node):
     if node.localName == 'para':
         style = self.styles.para_style_get(node)
         return platypus.Paragraph(self._textual(node), style, **(utils.attr_get(node, [], {'bulletText': 'str'})))
     elif node.localName == 'name':
         self.styles.names[
             node.getAttribute('id')] = node.getAttribute('value')
         return None
     elif node.localName == 'xpre':
         style = self.styles.para_style_get(node)
         return platypus.XPreformatted(self._textual(node), style, **(utils.attr_get(node, [], {'bulletText': 'str', 'dedent': 'int', 'frags': 'int'})))
     elif node.localName == 'pre':
         style = self.styles.para_style_get(node)
         return platypus.Preformatted(self._textual(node), style, **(utils.attr_get(node, [], {'bulletText': 'str', 'dedent': 'int'})))
     elif node.localName == 'illustration':
         return self._illustration(node)
     elif node.localName == 'blockTable':
         return self._table(node)
     elif node.localName == 'title':
         styles = reportlab.lib.styles.getSampleStyleSheet()
         style = styles['Title']
         return platypus.Paragraph(self._textual(node), style, **(utils.attr_get(node, [], {'bulletText': 'str'})))
     elif node.localName == 'h1':
         styles = reportlab.lib.styles.getSampleStyleSheet()
         style = styles['Heading1']
         return platypus.Paragraph(self._textual(node), style, **(utils.attr_get(node, [], {'bulletText': 'str'})))
     elif node.localName == 'h2':
         styles = reportlab.lib.styles.getSampleStyleSheet()
         style = styles['Heading2']
         return platypus.Paragraph(self._textual(node), style, **(utils.attr_get(node, [], {'bulletText': 'str'})))
     elif node.localName == 'h3':
         styles = reportlab.lib.styles.getSampleStyleSheet()
         style = styles['Heading3']
         return platypus.Paragraph(self._textual(node), style, **(utils.attr_get(node, [], {'bulletText': 'str'})))
     elif node.localName == 'image':
         return platypus.Image(node.getAttribute('file'), mask=(250, 255, 250, 255, 250, 255), **(utils.attr_get(node, ['width', 'height', 'preserveAspectRatio', 'anchor'])))
     elif node.localName == 'spacer':
         if node.hasAttribute('width'):
             width = utils.unit_get(node.getAttribute('width'))
         else:
             width = utils.unit_get('1cm')
         length = utils.unit_get(node.getAttribute('length'))
         return platypus.Spacer(width=width, height=length)
     elif node.localName == 'barCode':
         return code39.Extended39(self._textual(node))
     elif node.localName == 'pageBreak':
         return platypus.PageBreak()
     elif node.localName == 'condPageBreak':
         return platypus.CondPageBreak(**(utils.attr_get(node, ['height'])))
     elif node.localName == 'setNextTemplate':
         return platypus.NextPageTemplate(str(node.getAttribute('name')))
     elif node.localName == 'nextFrame':
         return platypus.CondPageBreak(1000)  # TODO: change the 1000 !
     elif node.localName == 'ul':
         return self._list(node)
     else:
         sys.stderr.write(
             'Warning: flowable not yet implemented: %s !\n' % (node.localName,))
         return None
Ejemplo n.º 8
0
def _build_report():
    stylesheet = getSampleStyleSheet()
    builder = [
        platypus.Paragraph("Report document", stylesheet["Heading1"]),
        platypus.Paragraph(to_paragraph(HEADER), stylesheet["Normal"]),
    ]

    for scan_prefix, scan_info in results.items():
        excel_filename = f"{scan_prefix}.xlsx"
        workbook = openpyxl.load_workbook(excel_filename)
        df = pd.read_excel(excel_filename, engine="openpyxl")
        df = df[list(table_fields)]

        for attr, col_info in table_fields.items():
            precision = col_info.get("precision")
            if precision is not None:
                col = getattr(df, attr)
                setattr(df, attr, [f"%.{precision}f" % item for item in col])

        style = platypus.TableStyle([
            ("FACE", (0, 0), (-1, 0), "Times-Bold"),
            ("ALIGN", (0, 0), (-1, 0), "CENTER"),
            ("GRID", (0, 0), (-1, -1), 0.25, colors.black),
            ("ALIGN", (1, 0), (-1, -1), "RIGHT"),
        ])

        header = [
            col_info.get("label", attr)
            for attr, col_info in table_fields.items()
        ]
        table = platypus.Table([header] + np.array(df).tolist(), repeatRows=1)
        table.setStyle(style)
        plot = platypus.Image(f"{scan_prefix}.png")
        plot.drawWidth = 8.0 * units.inch
        plot.drawHeight = 6.67 * units.inch
        builder.extend([
            platypus.Paragraph(scan_info["title"], stylesheet["Heading1"]),
            platypus.Paragraph(
                f"Data generated: {workbook.properties.created}",
                stylesheet["Normal"],
            ),
            platypus.Paragraph(to_paragraph(scan_info["info"]),
                               stylesheet["Normal"]),
            platypus.Paragraph("Scan Information", stylesheet["Heading2"]),
            platypus.Paragraph(to_paragraph(SCAN_INFO), stylesheet["Normal"]),
            platypus.PageBreakIfNotEmpty(),
            plot,
            platypus.Paragraph("Plot / Table Information",
                               stylesheet["Heading2"]),
            platypus.Paragraph(to_paragraph(PLOT_INFO), stylesheet["Normal"]),
            platypus.Paragraph(f"{scan_info['title']}: Scan Data Table",
                               stylesheet["Heading2"]),
            table,
            platypus.PageBreakIfNotEmpty(),
        ])

    return builder
Ejemplo n.º 9
0
    def save(self, directory, filetype):
        """Saves the attributes of the Country to a specified file.

        Parameters
        ----------
        directory : str
            Path to save output
        filetype : str
            For output file with country data (json or pdf)

        Raises
        ------
        NotImplementedError
            If unsupported filetype is passed in.
        """

        filename = directory + self.name.replace(' ', '_')
        if filetype == 'json':
            filename += ".json"
            with open(filename, 'w') as f:
                json.dump(vars(self), f, indent=4)
            f.close()
        elif filetype == 'pdf':
            ss = getSampleStyleSheet()
            pdf = platy.SimpleDocTemplate(filename + ".pdf")
            flowables = []
            flowables.append(platy.Paragraph(self.name, ss['Heading1']))
            for k in vars(self):
                if k == 'id' or k == 'name':
                    continue
                if type(vars(self)[k]) is str or type(vars(self)[k]) is int:
                    p = f"{k.replace('_',' ').title()}: {str(vars(self)[k])}"
                    flowables.append(platy.Paragraph(p, ss['BodyText']))
                else:
                    p = f"{k.replace('_',' ').title()}:"
                    flowables.append(platy.Paragraph(p, ss['BodyText']))
                    bullets = []
                    for v in vars(self)[k]:
                        p = v
                        if type(vars(self)[k]) is not list:
                            p += ": "+vars(self)[k][v]
                        b = platy.Paragraph(p, ss['Normal'])
                        bullets.append(platy.ListItem(b, leftIndent=35))
                    table = platy.ListFlowable(bullets, bulletType='bullet')
                    flowables.append(table)
            pdf.build(flowables)
        elif filetype == 'html':
            filename += ".json"
            json_string = json.dumps(vars(self),indent=4)
            f = open(filename, 'w')
            f.write("var data = " + json_string)
            f.close()
        else:
            raise NotImplementedError(
                f"Output file type, {filetype}, not supported")
Ejemplo n.º 10
0
def append_header(doc_els,
                  cfg_dct,
                  table_width,
                  re_style,
                  ti_style,
                  sample_name,
                  genotype=None):
    doc_els.append(plat.Paragraph(cfg_dct["report_title"], ti_style))
    doc_els.append(plat.Paragraph("For research use only", re_style))
    # -- top table
    doc_els.append(top_table(sample_name, table_width, genotype))
Ejemplo n.º 11
0
    def pdf_response_rl(self, question, filename, download=False):
        """
        Use the ReportLab api and the Model Objects provided by the context
        dict in this views pipeline.
        """
        import reportlab.platypus as RL
        import reportlab.lib.styles as SL
        from io import BytesIO

        flo = []
        out = BytesIO()  # create a byte buffer to hold PDF data
        pdf = RL.SimpleDocTemplate(out)
        pdf.showBoundary = 1
        pdf.leftMargin = pdf.rightMargin = pdf.leftMargin / 2
        pdf.topMargin = pdf.bottomMargin = pdf.topMargin / 2

        ss = SL.getSampleStyleSheet()
        h1 = RL.Paragraph("Question:", ss['Heading1'])
        h2 = RL.Paragraph(f"{str(question)}", ss['Heading2'])
        h3 = RL.Paragraph("Choices:", ss['Heading3'])
        hl = RL.HRFlowable(width='100%')

        if question.question_img:
            img = RL.Image(question.question_img.path,
                           width=100,
                           height=75,
                           hAlign="LEFT")
            flo += [img, hl]

        flo += [h1, h2, hl, h3]

        ps = [
            RL.Paragraph(f"{str(c)} [{c.votes} votes]", ss['BodyText'])
            for c in question.choice_set.all()
        ]
        ul = [RL.ListItem(x, value='sparkle') for x in ps]
        lf = RL.ListFlowable(ul, bulletType='bullet')
        flo += [lf]

        flo += [hl]
        try:
            pdf.build(flo)
        except Exception as e:
            message = (f"Unable to generate PDF from <hl><pre>{html}</pre>")
            return HttpResponse(message, status=500)

        out.seek(0)  # reset byte buffer pointer to the start

        if download:
            return FileResponse(out, as_attachment=True, filename=filename)
        return FileResponse(out, filename=filename)
Ejemplo n.º 12
0
    def __preamble(self):
        """Compose the beginning of the report
        """
        date = datetime.today().isoformat(' ')

        owner = 'PyMVPA v. %s' % mvpa2.__version__
        if self.author is not None:
            owner += '   Author: %s' % self.author

        return [
            rplp.Spacer(1, 0.8 * rplu.inch),
            rplp.Paragraph("Generated on " + date, self.style),
            rplp.Paragraph(owner, self.style)
        ] + self.__flowbreak
Ejemplo n.º 13
0
def portfolio_structure_block(portfolio: Portfolio,
                              block_position: BlockPosition):
    """Формирует блок pdf-файла с информацией о структуре портфеля.

    В левой части располагается табличка структуры, а в правой части диаграмма.
    """
    block_header = platypus.Paragraph("Portfolio Structure",
                                      BLOCK_HEADER_STYLE)
    table = make_pdf_table(portfolio)
    frame = platypus.Frame(
        block_position.x,
        block_position.y,
        block_position.width * LEFT_PART_OF_BLOCK,
        block_position.height,
        leftPadding=0,
        bottomPadding=0,
        rightPadding=0,
        topPadding=6,
        showBoundary=0,
    )
    frame.addFromList([block_header, table], block_position.canvas)
    image = make_plot(
        portfolio,
        block_position.width * (1 - LEFT_PART_OF_BLOCK),
        block_position.height,
    )
    image.drawOn(
        block_position.canvas,
        block_position.x + block_position.width * LEFT_PART_OF_BLOCK,
        block_position.y,
    )
Ejemplo n.º 14
0
def portfolio_return_block(df: pd.DataFrame, block_position: BlockPosition):
    """Формирует блок pdf-файла с информацией доходности портфеля и индекса.

    В левой части располагается табличка, а в правой части диаграмма.
    """
    block_header = platypus.Paragraph("Portfolio Return", BLOCK_HEADER_STYLE)
    table = make_pdf_table(df)
    frame = platypus.Frame(
        block_position.x,
        block_position.y,
        block_position.width * LEFT_PART_OF_BLOCK,
        block_position.height,
        leftPadding=0,
        bottomPadding=0,
        rightPadding=0,
        topPadding=6,
        showBoundary=0,
    )
    frame.addFromList([block_header, table], block_position.canvas)
    image = make_plot(df, block_position.width * (1 - LEFT_PART_OF_BLOCK),
                      block_position.height)
    image.drawOn(
        block_position.canvas,
        block_position.x + block_position.width * LEFT_PART_OF_BLOCK,
        block_position.y,
    )
Ejemplo n.º 15
0
  def getdetails(self):

      with con:
    
          cur = con.cursor()
          pid = str(self.ui.lineEdit_3.text())
          cur.execute('SELECT count(*) FROM ptestresults where pid like ? AND (ptestresults.t1 = "P" OR ptestresults.t2 = "P")',['%'+ pid + '%']); 
          result = cur.fetchall()
          for row in result:
            tcount = row[0]
            # print tcount
          cur.execute('SELECT s1,s2,s3,s4,s5,s6,s7,s8,s9,s10 FROM psymptoms where pid like ? ',['%'+ pid + '%']); 
          result1 = cur.fetchall()
          cnt1 = 0
          result2 = str(" ")
          for row in result1:
              if row[0] != 'N': 
                 cnt1 = cnt1+1
                 result2 = result2 + str("___________________ You have Pain in Throat Region while taking the food ________________________") 
              if row[1] != 'N': 
                 cnt1 = cnt1+1
                 result2 = result2 + str("____________________ You have Pain in chest to abdomen Region_________________________") 
              if row[2] != 'N': 
                 cnt1 = cnt1+1
                 result2 = result2 + str("_____________ Your pain is lasting for several hours ______________") 
              if row[3] != 'N': 
                 cnt1 = cnt1+1
                 result2 = result2 + str(" You have difficulty in swallowing food ")
              if row[4] != 'N': 
                 cnt1 = cnt1+1
                 result2 = result2 + str(" You are unable to swallow food")
              if row[5] != 'N': 
                 cnt1 = cnt1+1
                 result2 = result2 + str(" Food is stucking in throat and chest region")
              if row[6] != 'N': 
                 cnt1 = cnt1+1
                 result2 = result2 + str(" You have a feeling of fullness without taking food ")
              if row[7] != 'N': 
                 cnt1 = cnt1+1
                 result2 = result2 + str(" You are suffering from low to high fever ")
              if row[8] != 'N': 
                 cnt1 = cnt1+1
                 result2 = result2 + str(" You are shaking with chills")
              if row[9] != 'N': 
                 cnt1 = cnt1+1
                 result2 = result2 + str(" You are suffering from chroniic cough ")
              # print cnt1
          if (tcount > 0):
	    # print "Consult Specialist immediately as +ve test results are there"
            result2 = result2 + str("Consult Specialist immediately as +ve test results are there")
          if ((tcount == 0) and (cnt1 > 5)):
	    # print "Consult Specialist immediately as above mentioned +ve symptoms are there"
            result2 = result2 + str("Consult Specialist immediately as above mentioned +ve symptoms are there")
          if ((tcount == 0) and (cnt1 <= 5)):
	    # print "Consult Specialist as above mentioned +ve symptoms are there"
            result2 = result2 + str("Consult Specialist as above mentioned +ve symptoms are there")
          items = []
          items.append(platypus.Paragraph(result2,PS('body')))
          doc = SimpleDocTemplate('medrep1.pdf')
          doc.multiBuild(items)
Ejemplo n.º 16
0
 def _create(self):
     """ create the table with leading page break """
     story = [plat.PageBreak()]
     self.levelStyles = [self.tableTS]
     story.append(plat.Paragraph("Table of Tables", self.toc_h1))
     story.append(self)
     return story
Ejemplo n.º 17
0
    def _make_figure_table(image_files):
        # Add the images to a list of lists
        cols = 2
        table = []
        row = []
        for (i, fn) in enumerate(image_files):
            row.append(p.Image(fn, 3.4 * u.inch, 3.0 * u.inch))
            if (i % cols) == (cols - 1):
                table.append(row)
                row = []

        # Determine if there are any images left to print
        if len(row) != 0:
            for i in range(len(row), cols):
                row.append(p.Paragraph('', styles['body_style']))
            table.append(row)

        # Style this into a reportlab table and add to the story
        width = 3.75 * u.inch
        t = p.Table(table, colWidths=[width, width])
        t.setStyle(
            p.TableStyle([
                ('ALIGNMENT', (0, 0), (-1, -1), 'CENTER'),
                ('VALIGN', (0, 0), (-1, -1), 'CENTER'),
                ('TOPPADDING', (0, 0), (-1, -1), 6.0),
                ('BOTTOMPADDING', (0, 0), (-1, -1), 6.0),
            ]))
        return t
Ejemplo n.º 18
0
 def pdformat(self):
     with con:
         items = []
         cur = con.cursor()
         qpaper = str(self.ui.lineEdit.text())
         with open(qpaper) as fp:
             for line in fp:
                 words = line.split()
                 for word in words:
                     cur.execute('SELECT * from kywrds WHERE kywrd like ?',
                                 [word])
                     result = cur.fetchall()
                     if result:
                         for row in result:
                             result1 = row[0]
                             result2 = row[1]
                             result3 = row[2]
                             address = 'Level: ' + str(
                                 result1
                             ) + ' ' + ' ' + ' ' + ' ' + 'Percentage: ' + str(
                                 result3
                             ) + '%' + '    ' + 'Keyword: ' + result2
                             items.append(
                                 platypus.Paragraph(address, PS('body')))
                         doc = SimpleDocTemplate('report1.pdf')
                         doc.multiBuild(items)
Ejemplo n.º 19
0
    def create_intro(self):
        self.elements += [
            pdf.Spacer(0, 0.25 * inch),
            pdf.Paragraph(self.crawler.novel_title or 'N/A',
                          style=self.styles['Title']),
            pdf.Spacer(0, 0.1 * inch),
            pdf.Table(
                [[self.crawler.novel_author or 'N/A']],
                style=pdf.TableStyle([
                    ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                    ('SIZE', (0, 0), (-1, -1), 12),
                ]),
            ),
            pdf.Spacer(0, 0.5 * inch),
        ]

        if self.app.book_cover:
            self.elements += [pdf.Image(self.app.book_cover, height=5 * inch)]
        else:
            self.elements += [pdf.Spacer(0, 5 * inch)]
        # end if

        self.elements += [
            pdf.Spacer(0, 0.5 * inch),
            pdf.Table(
                [['Generated by <Lightnovel Crawler>'],
                 ['https://github.com/dipu-bd/lightnovel-crawler']],
                style=pdf.TableStyle([
                    ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                ]),
            ),
        ]
        self.elements += [pdf.PageBreak()]
Ejemplo n.º 20
0
    def _create(self):
        """
        Does the final creation of the Platypus Heading object.
        Including a correct numeration for the headings.

        Typically this Method will be called by the _PreBuild-Method of
        the Story class.

        :return: story with all final objects for pdf rendering
        :rtype: list of platypus objects ready for rendering.
        """
        story = []

        # if pageBreak:
        #    self._story.append(PageBreak())

        if self.level > 0:
            story.append(plat.Spacer(1, 1.5 * cm))

        # Get Current Section Number
        num = self._build_section_number_string(self.level)

        story.append(
            plat.Paragraph(num + " " + self.heading,
                           self.header[self.level if self.level < 4 else 3]))

        return story
Ejemplo n.º 21
0
 def getList(self, listTextLines):
     bulletParas = []
     for txt in listTextLines:
         bulletParas.append(
             platypus.Paragraph(txt,
                                style=BulletStyle,
                                bulletText=u"\N{BULLET} "))
     return bulletParas
Ejemplo n.º 22
0
 def getData(self, session):
     paras = []
     gen = self.docStream.find_documents(session, cache=self.cache)
     for text in gen:     
         for t in text:
             paras.append(platypus.Paragraph(t, ParagraphStyle, bulletText=None))
             paras.append(NextPageTemplate("noHeader"))
     return paras  
Ejemplo n.º 23
0
 def xml(self, line, style=None):
     """Adding XML string to the report
     """
     if __debug__ and not self in debug.handlers:
         debug("REP", "Adding xml '%s'" % line.strip())
     if style is None:
         style = self.style
     self._story.append(rplp.Paragraph(line, style=style))
Ejemplo n.º 24
0
    def __init__(self,
                 range_min,
                 range_max,
                 values,
                 answers,
                 mean,
                 standard_deviation,
                 count,
                 significant=0):
        platypus.Flowable.__init__(self)

        self.range_min = range_min
        self.range_max = range_max

        self.values = values
        self.mean = mean
        self.standard_deviation = standard_deviation
        self.count = count

        self.box_width = 40
        self.box_height = 60
        self.box_depth = 6

        self.mean_width = 2
        self.mean_height = 6

        self.values_height = 10
        self.values_gap = self.box_depth
        self.bars_height = max(self.values.values()) * self.box_height
        self.skala_height = self.mean_height
        self.marks_height = 10

        if significant:
            stylesheet_name = 'Normal_Highlight'
        else:
            stylesheet_name = 'Normal'

        self.answers_paragraph = \
            platypus.Paragraph(escape(u' - '.join(answers)), stylesheet[stylesheet_name])
        self.count_paragraph = \
            platypus.Paragraph(_(u'Answers: %i') % self.count, stylesheet['Normal'])
        self.mean_paragraph = \
            platypus.Paragraph(_(u'Mean: %.2f') % self.mean, stylesheet['Normal'])
        self.stdd_paragraph = \
            platypus.Paragraph(_(u'Standard Deviation: %.2f') % self.standard_deviation, stylesheet['Normal'])
Ejemplo n.º 25
0
 def header(Elements, txt, style=HeaderStyle):
     s = platypus.Spacer(0.2 * inch, 0.2 * inch)
     Elements.append(s)
     style.alignment = 1
     style.fontName = self.psfont
     style.fontSize = 18
     style.borderWidth = 0
     para = platypus.Paragraph(txt, style)
     Elements.append(para)
Ejemplo n.º 26
0
    def _create(self):
        """ create the table with page break at the end """
        story = [
            plat.Paragraph("Table of Content",
                           ParagraphStyle(name='Heading1', fontSize=0)), self,
            plat.PageBreak()
        ]

        return story
Ejemplo n.º 27
0
 def __init__(self, answer, value, significant=0):
     platypus.Flowable.__init__(self)
     if significant:
         stylesheet_name = 'Right_Highlight'
     else:
         stylesheet_name = 'Right'
     self.answer = platypus.Paragraph(escape(answer),
                                      stylesheet[stylesheet_name])
     self.value = platypus.Paragraph(u'%.2f %%' % (value * 100),
                                     stylesheet[stylesheet_name])
     self.black_box = flowables.Box(value * self.box_width, self.box_height,
                                    self.box_depth, self.box_margin)
     self.black_box.transparent = 0
     self.black_box.fill = 1
     self.black_box.fill_color = (0.6, 0.6, 0.6)
     self.white_box = flowables.Box((1 - value) * self.box_width,
                                    self.box_height, self.box_depth,
                                    self.box_margin)
Ejemplo n.º 28
0
def pdf_maker(trialnumber, ptname, footer):
    '''
    Makes a PDF with a top text, image, and bottom text.
    Inputs:-
    trialnumber: number of trials to plot (indexing from zero)
    ptname: patient name (string) to put in top text
    footer: text string for bottom text
    '''
    from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
    import reportlab.platypus as platypus
    from reportlab.lib.units import cm
    
    fileprefix = 'emg-plot-'
    filesuffix = '.png'
    toptext = '<font size=14><b>EMG for %s</b></font>' % ptname    
    pdf_path = tkFileDialog.asksaveasfilename(initialdir='C:', 
                                            initialfile='EMG report %s.pdf' %ptname)                                    
    doc = platypus.SimpleDocTemplate(pdf_path,
                                     topMargin = cm, bottomMargin = cm,
                                     rightMargin = cm, leftMargin = cm)
    story = []
    
    # Make new, indented text style.
    style = getSampleStyleSheet()['Normal']
    indented = ParagraphStyle(
        'indented',
        parent=style,
        leftIndent=2*cm
        )
    
    for n in range(trialnumber+1):
        story.append(platypus.Paragraph(toptext, indented))
        story.append(platypus.Spacer(1,0.1*cm))
        graph = platypus.Image(str(fileprefix+str(n)+filesuffix))
        graph._restrictSize(19*cm, 24*cm)
        story.append(graph)
        #story.append(platypus.Spacer(1,0.5*cm))
        footer = footer.replace('\n','<br />\n') #Reportlab's Paragraph ignores newlines
        story.append(platypus.Paragraph(footer, indented))
        story.append(platypus.PageBreak())
        
    print('docbuild ran in %s' %pdf_path)
    doc.build(story)
Ejemplo n.º 29
0
    def add_paragraph(self, text, style='Normal'):
        """
        **Add a new Paragraph to the story.**

        taken from platypus.Paragraph documentation:

        The paragraph Text can contain XML-like markup including the tags::

            <b> ... </b> - bold
            <i> ... </i> - italics
            <u> ... </u> - underline
            <strike> ... </strike> - strike through
            <super> ... </super> - superscript
            <sub> ... </sub> - subscript
            <font name=fontfamily/fontname color=colorname size=float>
            <span name=fontfamily/fontname color=colorname backcolor=colorname size=float style=stylename>
            <onDraw name=callable label="a label"/>
            <index [name="callablecanvasattribute"] label="a label"/>
            <link>link text</link>
            attributes of links
            size/fontSize=num
            name/face/fontName=name
            fg/textColor/color=color
            backcolor/backColor/bgcolor=color
            dest/destination/target/href/link=target
            <a>anchor text</a>
            attributes of anchors
            fontSize=num
            fontName=name
            fg/textColor/color=color
            backcolor/backColor/bgcolor=color
            href=href

        **example:**

        .. python::

            doc = pdf.Pdf()

            doc.add_paragraph('''This text is written in one paragraph.
                              New line and additional spaces are ignored,
                              the text will be aligned to fit the page width.
                              The paragraph text can contain XML-like markup including the tags:
                              <b> bold text </b> and <i> italics text </i> can be used
                              inside a paragraph.''', style='Title')

        :param text: text, which must be added to the story.
        :type text: string
        :param style: style, which must be added to the story.
                      Examples of style: 'Title', 'BodyText', 'Italic', 'Heading1', 'Heading4', 'Heading6', ...
                      For more style options go to reportlab.lib.styles.getSampleStyleSheet.
        :type style: string
        :return:
        """
        self._story.append(plat.Paragraph(text, self.styles[style]))
Ejemplo n.º 30
0
    def _create_story(self):

        # Set up an empty list to hold the story
        story = []

        # Import the report styles
        styles = report_styles.get_report_styles()

        # Create a page break
        story = self._make_page_break(story, self.PORTRAIT)

        # Section title
        title_str = '<strong>References</strong>'
        story.append(self._make_title(title_str))
        story.append(p.Spacer(0, 0.1 * u.inch))

        # List of references used
        references = [
            '''
            Cohen, J. 1960. "A coefficient of agreement for
            nominal scales." Educational and Psychological Measurement
            20: 37-46.
            ''',
            '''
            Kennedy, RE, Z Yang and WB Cohen. 2010. "Detecting trends
            in forest disturbance and recovery using yearly Landsat
            time series: 1. Landtrendr -- Temporal segmentation
            algorithms." Remote Sensing of Environment 114(2010):
            2897-2910.
            ''',
            '''
            Ohmann, JL, MJ Gregory and HM Roberts. 2014 (in press). "Scale
            considerations for integrating forest inventory plot data and
            satellite image data for regional forest mapping." Remote
            Sensing of Environment.
            ''',
            '''
            O'Neil, TA, KA Bettinger, M Vander Heyden, BG Marcot, C Barrett,
            TK Mellen, WM Vanderhaegen, DH Johnson, PJ Doran, L Wunder, and
            KM Boula. 2001. "Structural conditions and habitat elements of
            Oregon and Washington. Pages 115-139 in: Johnson, DH and TA
            O'Neil, editors. 2001. "Wildlife-habitat relationships in Oregon
            and Washington." Oregon State University Press, Corvallis, OR.
            ''',
        ]

        # Print all references
        for reference in references:
            para = p.Paragraph(reference, styles['body_style'])
            story.append(para)
            story.append(p.Spacer(0, 0.10 * u.inch))

        # Return this story
        return story