Example #1
0
def types_grid(title, data):
    line = []
    header = []
    title_par = ''
    LineLeng = 20
    print title
    for i in title:
        if i != '|':
            title_par += i
        else:
            header.append(
                Preformatted(title_par,
                             styles['stileLeyenda'],
                             maxLineLength=LineLeng))
            title_par = ''
    header.append(
        Preformatted(title_par, styles['stileLeyenda'],
                     maxLineLength=LineLeng))
    line.append(header)
    for linea in data:
        new_line = []
        for cell in sorted(linea):
            # if cell != None:
            new_line.append(
                Preformatted(str(linea[cell]),
                             styles['stileVal'],
                             maxLineLength=LineLeng))  # Valores
            # else:
            # new_line.append(Preformatted(str(''),styles['stileVal'],maxLineLength=LineLeng)) # Valores
        line.append(new_line)
    return line
Example #2
0
    def __init__(self, text, style, caption):
        figures.Figure.__init__(self, 0, 0, caption)
        self.text = text
        self.style = style
        self.para = Paragraph(text, style)

        styleText = self.getStyleText(style)
        self.pre = Preformatted(styleText, self.descrStyle)
Example #3
0
    def produce(self, module):

        str_competence = ' \n'.join([
            '- {0} ({1})'.format(c.nom, c.code)
            for c in module.competence_set.all()
        ])

        str_sous_competence = ''
        for c in module.competence_set.all():
            for sc in c.souscompetence_set.all():
                str_sous_competence += '- {0} (voir {1})\n'.format(
                    sc.nom, c.code)

        str_res = ' \n'.join([
            '- {0}'.format(c.nom) for c in module.ressource_set.all()
        ])  # for future use

        str_objectif = ' \n'.join(
            ['- {0}'.format(c.nom) for c in module.objectif_set.all()])

        self.story.append(Paragraph(module.__str__(), style_bold))
        self.story.append(Spacer(0, 0.5 * cm))

        data = [
            ['Domaine', module.processus.domaine.__str__()],
            ['Processus', module.processus.__str__()],
            ['Situation emblématique', module.situation],
            ['Compétences visées', str_competence],
            ['Plus-value sur le CFC ASE', str_sous_competence],
            ['Objectifs', str_objectif], ['Didactique', module.didactique],
            ['Evaluation', module.evaluation],
            ['Type', '{0}, obligatoire'.format(module.type)],
            ['Semestre', 'Sem. {0}'.format(module.semestre)],
            ['Présentiel', '{0} heures'.format(module.total_presentiel)],
            ['Travail personnel', '{0} heures'.format(module.travail_perso)],
            ['Responsable',
             module.processus.domaine.responsable.descr_pdf()]
        ]

        formated_data = []
        for foo in data:
            formated_data.append([
                Preformatted(foo[0], style_normal, maxLineLength=15),
                Preformatted(foo[1], style_normal, maxLineLength=85),
            ])

        t = Table(data=formated_data, colWidths=[4 * cm, 13 * cm])
        t.hAlign = TA_LEFT
        t.setStyle(tblstyle=TableStyle([
            ('SIZE', (0, 0), (-1, -1), 7),
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ('LEFTPADDING', (0, 0), (-1, -1), 0),
        ]))
        self.story.append(t)
        self.build(self.story)
Example #4
0
def resize_para(str, max_size=10.0, min_size=2.0, max_width=(1.25*inch),
                font_name='Helvetica', alignment=TA_CENTER):
    """Produce a paragraph, reducing font size until it fits in the max width"""
    size = max_size
    while size > min_size:
        # HACK: Use a preformatted object so that minWidth() fomes up with
        # non-wrapped width. This just feels so dirty, dirty, but it works
        style = ParagraphStyle(name='Size %s' % size,
                               alignment=alignment, fontName=font_name,
                               fontSize=size, leading=size+0.25)
        para = Preformatted(str, style)
        if para.minWidth() <= max_width:
            para = Paragraph(str, style)
            break
        size -= 0.125
    return para
def go():
    #create the basic page and frames
    doc = BaseDocTemplate("phello.pdf",
                          leftMargin=10,
                          rightMargin=0,
                          topMargin=0,
                          bottomMargin=0)
    doc.pagesize = landscape(A4)

    frameCount = 2
    frameWidth = doc.height / frameCount
    frameHeight = doc.width - .05 * inch
    frames = []
    #construct a frame for each column
    for frame in range(frameCount):
        leftMargin = doc.leftMargin + frame * frameWidth
        column = Frame(leftMargin, doc.bottomMargin, frameWidth, frameHeight)
        print leftMargin, doc.bottomMargin, frameWidth, frameHeight

        frames.append(column)
    template = PageTemplate(frames=frames)
    doc.addPageTemplates(template)

    #	doc = SimpleDocTemplate("phello.pdf", id='TwoColumns')
    #	doc.pagesize = landscape(A4) ## TODO: make configurable

    Story = []
    style = styles["Normal"]
    style.fontName = 'Courier'
    style.fontSize = 6
    for monkey in monkeys:
        p = Preformatted(get_ttview(monkey[0], monkey[1], 15), style)
        Story.append(KeepTogether(p))
        Story.append(Spacer(1, 0.05 * inch))
    doc.build(Story)
Example #6
0
    def _doPrintingPdf(self):
        if self.printFile:
            pdf_file_name = self.printFile
        elif self.printDir:
            pdf_file_name = self._getNextSpoolFile(extension='pdf')
        else:
            pdf_file_name = tempfile.mktemp(".pdf")
        # print("Printing to: %s" % (pdf_file_name))

        # ## FONT # ##
        from reportlab.pdfbase import pdfmetrics
        from reportlab.pdfbase.ttfonts import TTFont
        pdfmetrics.registerFont(
            TTFont('Epson1', self._getFontPath('fonts/epson1.ttf')))
        pdfmetrics.registerFontFamily('Epson1', normal='Epson1')
        # ## FONT # ##

        styles = getSampleStyleSheet()
        code = styles["Code"]
        pre = code.clone('Pre', leftIndent=0, fontName='Epson1')
        normal = styles["Normal"]
        styles.add(pre)

        doc = SimpleDocTemplate(pdf_file_name)
        story = [Preformatted(open(self.source_file_name).read(), pre)]
        doc.build(story)
        # win32api.ShellExecute (0, "print", pdf_file_name, None, ".", 0)
        return pdf_file_name
Example #7
0
    def __init__(self, text, style, caption):
        figures.Figure.__init__(self, 0, 0, caption)
        self.text = text
        self.style = style
        self.para = Paragraph(text, style)

        styleText = self.getStyleText(style)
        self.pre = Preformatted(styleText, self.descrStyle)
Example #8
0
def build_flowables(stylesheet):
    text = """   
foo
    
                        bar
    spam
"""

    return [Preformatted(text, stylesheet['default'])]
Example #9
0
def Grid(group, grupo):
    leyenda = []
    name = []
    line = []
    dato = []
    obj = []
    columns = len(group[group.keys()[0]]['components'])
    LebelLeng = LineLengLebel // int(columns)
    for component in group[group.keys()[0]]['components']:
        if 'showdatagrid' in component[component.keys()[0]]['properties']:
            if component[component.keys()
                         [0]]['properties']['showdatagrid'] == True:
                leyenda.append(
                    Preformatted(
                        component[component.keys()[0]]['properties']['label'],
                        styles['stileLeyenda'],
                        maxLineLength=LebelLeng))  # Etiquetas de las columnas
                obj.append(
                    (component[component.keys()[0]]['properties']['name'],
                     component[component.keys()[0]]['type']))
    if len(obj) != 0:
        line.append(leyenda)
        if grupo in valor:  # Load columns Val
            for i in range(0, len(valor[grupo])):
                for x in obj:
                    if x[0] in valor[grupo][i]:
                        if x[1] == 'date':
                            dato.append(
                                Preformatted(str(
                                    formatDate(valor[grupo][i][x[0]])),
                                             styles['stileValGrid'],
                                             maxLineLength=LebelLeng))
                        elif x[1] == 'combo':
                            dato.append(
                                Preformatted(str(
                                    valor[grupo][i][x[0]]['text']),
                                             styles['stileValGrid'],
                                             maxLineLength=LebelLeng))
                        elif x[1] == 'numeric':
                            if valor[grupo][i][x[0]] is None:
                                dato.append(
                                    Preformatted(str(''),
                                                 styles['stileValGrid'],
                                                 maxLineLength=LebelLeng))
                            else:
                                dato.append(
                                    Preformatted(str(valor[grupo][i][x[0]]),
                                                 styles['stileValGrid'],
                                                 maxLineLength=LebelLeng))
                        else:
                            dato.append(
                                Preformatted(str(valor[grupo][i][x[0]]),
                                             styles['stileValGrid'],
                                             maxLineLength=LebelLeng))
                    else:
                        dato.append('')
                line.append(dato)
                dato = []
    return line
Example #10
0
def preformatted_paragraph():
    doc = SimpleDocTemplate("preformatted_paragraph.pdf",
                            pagesize=letter
                            )
    styles = getSampleStyleSheet()

    flowables = []

    text = "<para align=center>Hello, I'm a Paragraph</para>"
    para = Paragraph(text, style=styles["Normal"])
    flowables.append(para)

    text = "<para align=center>Hello, I'm a Preformatted Paragraph</para>"
    para = Preformatted(text, style=styles["Code"])
    flowables.append(para)

    doc.build(flowables)
Example #11
0
def pdfgen(relevant_extracts, sector, keywords):
    today = datetime.datetime.today()
    today.replace(second=0, microsecond=0)

    outputdir = join('..', 'output')
    if not exists(outputdir):
        mkdir(outputdir)
    chdir(outputdir)

    doc = SimpleDocTemplate('%s_%s.pdf' %
                            (sector, today.strftime("%Y-%m-%d_%H.%M")))
    template = PageTemplate(
        'normal', [Frame(2.5 * cm, 2.5 * cm, 15 * cm, 25 * cm, id='F1')])
    doc.addPageTemplates(template)

    Story = [Spacer(1, 0.5 * inch)]
    styleSheet = getSampleStyleSheet()
    style = styleSheet['BodyText']
    title = Paragraph(
        '<para align=center><b>%s Industry Earnings Call Transcripts Report</b></para>'
        % sector, style)
    Story.append(title)
    subtitle = Paragraph(
        '<para align=center>Keywords: %s</para>' % ", ".join(keywords), style)
    Story.append(subtitle)
    Story.append(Spacer(1, 0.5 * inch))

    for extract in relevant_extracts:
        Story.append(Paragraph("From %s" % extract["title"], h1))
        Story.append(
            Paragraph(
                "Published on %s at %s" % (extract["date"], extract["time"]),
                h1))
        text = Preformatted(extract["bodyContent"].encode('utf8'),
                            style,
                            maxLineLength=100)
        Story.append(text)
        Story.append(Spacer(1, 0.2 * inch))

    doc.build(Story)
Example #12
0
def paint_pdf(phile):
    """Generate a PDF."""
    buf = io.BytesIO()

    # Setup the document with paper size and margins
    doc = SimpleDocTemplate(
        buf,
        rightMargin=settings.SCRIP_SAFE_RIGHT_MARGIN * inch,
        leftMargin=settings.SCRIP_SAFE_LEFT_MARGIN * inch,
        topMargin=settings.SCRIP_SAFE_TOP_MARGIN * inch,
        bottomMargin=settings.SCRIP_SAFE_BOTTOM_MARGIN * inch,
        pagesize=portrait(letter),
    )

    # Styling
    styles = getSampleStyleSheet()
    styles.add(
        ParagraphStyle(
            name='CodeSmall',
            parent=styles['Code'],
            fontSize=settings.SCRIP_SAFE_FONT_SIZE,
            leading=settings.SCRIPT_SAFE_LEADING,
        ))

    lines = []
    # line break at Page n of n
    reg = re.compile('(Page) (\d+) (of) (\d+)')
    for line in phile.readlines():
        if reg.search(line):
            lines.append(PageBreak())
        lines.append(Preformatted(
            line,
            styles['CodeSmall'],
        ))
    doc.build(lines)

    # Write the PDF to a file
    with open('{0}.pdf'.format(phile.name), 'wb') as fd:
        fd.write(buf.getvalue())
Example #13
0
def pdf(path, start_time, end_time):

    # 读取文件 以及背景图 生成的gantt图以及生成的table
    gantt_width, gantt_height = Image.open(GANTT_BG).size
    table_width, table_height = Image.open(TABLE_BG).size

    # 设置pdf画布的大小   默认宽是1920   超过1920的  即俩个图最大的宽度 + 外边框(左右图边距均为160)
    bigger_width = max([gantt_width, table_width])
    bigger_width = bigger_width if bigger_width > DEFAULT_WIDTH else DEFAULT_WIDTH
    gantt_height = ceil((bigger_width / gantt_width) * gantt_height)
    table_height = ceil((bigger_width / table_width) * table_height)

    page_width = bigger_width + 4 * PAGE_MARGIN

    title_image = Image.open(TITLE_BG)
    title_width, title_height = title_image.size
    title_width = page_width
    resize_precent = title_width / 1920
    title_height = ceil(resize_precent * title_height)
    # print(title_height)
    page_height = title_height + (80 + gantt_height + 80 +
                                  200) + (80 + table_height + 80 + 10 + 200)

    c = canvas.Canvas(path, pagesize=(page_width, page_height))
    c.setFillColorRGB(PAGE_BG_COLOR[0], PAGE_BG_COLOR[1], PAGE_BG_COLOR[2])
    # 给画布添加背景色
    c.rect(0, 0, width=page_width, height=page_height, stroke=0, fill=1)

    # 从左下角的原点坐标开始画起

    # 设置table区域  背景色为白色
    c.setFillColorRGB(1, 1, 1)
    c.rect(80,
           80,
           width=bigger_width + 2 * 80,
           height=table_height + 80 + 10 + 200,
           stroke=0,
           fill=1)
    # 画出table的图片
    c.drawImage(TABLE_BG,
                160,
                160,
                width=bigger_width,
                height=table_height,
                mask=None)
    # 设置分割符号
    c.setFillColorRGB(PAGE_BG_COLOR[0], PAGE_BG_COLOR[1], PAGE_BG_COLOR[2])
    c.rect(150,
           160 + table_height,
           width=bigger_width + 20,
           height=10,
           stroke=0,
           fill=1)

    # 设置table 标题
    # 设置字体以及字体大小
    c.setFont('hei', 80)
    c.drawString(150, 160 + table_height + 10 + 60, '项目周报详情')
    c.setFont('hei', 30)
    c.drawString(bigger_width + 20 + 80 + 75 - 505,
                 table_height + 80 + 10 + 200 + 80 - 130,
                 f'周报日期:{start_time} ~ {end_time}')

    # 设置gantt图

    # 设置gantt区域  背景色为白色
    c.setFillColorRGB(1, 1, 1)
    c.rect(80,
           80 + table_height + 80 + 10 + 200 + 80,
           width=bigger_width + 2 * 80,
           height=gantt_height + 80 + 200,
           stroke=0,
           fill=1)

    # 画出gantt图的图片
    c.drawImage(GANTT_BG,
                160,
                80 + table_height + 80 + 10 + 200 + 80 + 80,
                width=bigger_width,
                height=gantt_height,
                mask=None)
    # 设置分割符号
    c.setFillColorRGB(PAGE_BG_COLOR[0], PAGE_BG_COLOR[1], PAGE_BG_COLOR[2])
    c.rect(150,
           80 + table_height + 80 + 10 + 200 + 80 + 80 + gantt_height,
           width=bigger_width + 20,
           height=10,
           stroke=0,
           fill=1)
    # gantt图图片
    c.setFont('hei', 80)
    c.drawString(
        150, 80 + table_height + 80 + 10 + 200 + 80 + gantt_height + 80 + 80,
        '项目进度图')

    # 设置title
    c.drawImage(TITLE_BG,
                0,
                80 + table_height + 80 + 10 + 200 + 80 + gantt_height + 80 +
                200,
                width=title_width,
                height=title_height)

    # 绘制时间

    # 获取默认样式的字典对象
    styleSheet = getSampleStyleSheet()
    # 获取文本的样式
    style = styleSheet['BodyText']
    # 设置字体
    style.fontName = 'hei'  # 字体
    # 设置字体大小
    style.fontSize = ceil(resize_precent * 60)  # 字体大小
    # 设置行间距
    style.leading = ceil(resize_precent * 70)
    # 设置字体颜色
    style.textColor = PAGE_BG_COLOR
    # 官方文档提示 中文要有该参数
    style.wordWrap = 'CJK'
    # 文本格式化
    text = f'''
    {start_time}
    /
    {end_time}
    '''
    p = Preformatted(text, style, newLineChars='')
    # 指定文本区域大小
    p.wrapOn(c, 321, 224)
    # 绘画在画布上
    time_position_x = ceil(1400 / 1920 * page_width)
    time_position_y = ceil(129 / 482 * title_height) + (
        80 + gantt_height + 80 + 200) + (80 + table_height + 80 + 10 + 200)
    p.drawOn(c, time_position_x, time_position_y)

    c.showPage()
    c.save()
Example #14
0
class ParaBox(figures.Figure):
    """Illustrates paragraph examples, with style attributes on the left"""
    descrStyle = ParagraphStyle('description',
                                fontName='Courier',
                                fontSize=8,
                                leading=9.6)

    def __init__(self, text, style, caption):
        figures.Figure.__init__(self, 0, 0, caption)
        self.text = text
        self.style = style
        self.para = Paragraph(text, style)

        styleText = self.getStyleText(style)
        self.pre = Preformatted(styleText, self.descrStyle)

    def wrap(self, availWidth, availHeight):
        """Left 30% is for attributes, right 50% for sample,
        10% gutter each side."""
        self.x0 = availWidth * 0.05  #left of box
        self.x1 = availWidth * 0.1  #left of descriptive text
        self.x2 = availWidth * 0.5  #left of para itself
        self.x3 = availWidth * 0.9  #right of para itself
        self.x4 = availWidth * 0.95  #right of box
        self.width = self.x4 - self.x0
        self.dx = 0.5 * (availWidth - self.width)

        paw, self.pah = self.para.wrap(self.x3 - self.x2, availHeight)
        self.pah = self.pah + self.style.spaceBefore + self.style.spaceAfter
        prw, self.prh = self.pre.wrap(self.x2 - self.x1, availHeight)
        self.figureHeight = max(self.prh, self.pah) * 10.0 / 9.0
        return figures.Figure.wrap(self, availWidth, availHeight)

    def getStyleText(self, style):
        """Converts style to preformatted block of text"""
        lines = []
        for (key, value) in style.__dict__.items():
            lines.append('%s = %s' % (key, value))
        lines.sort()
        return string.join(lines, '\n')

    def drawFigure(self):

        #now we fill in the bounding box and before/after boxes
        self.canv.saveState()
        self.canv.setFillGray(0.95)
        self.canv.setDash(1, 3)
        self.canv.rect(self.x2 - self.x0,
                       self.figureHeight * 0.95 - self.pah,
                       self.x3 - self.x2,
                       self.para.height,
                       fill=1,
                       stroke=1)

        self.canv.setFillGray(0.90)
        self.canv.rect(
            self.x2 - self.x0,  #spaceBefore
            self.figureHeight * 0.95 - self.pah + self.para.height,
            self.x3 - self.x2,
            self.style.spaceBefore,
            fill=1,
            stroke=1)

        self.canv.rect(
            self.x2 - self.x0,  #spaceBefore
            self.figureHeight * 0.95 - self.pah - self.style.spaceAfter,
            self.x3 - self.x2,
            self.style.spaceAfter,
            fill=1,
            stroke=1)

        self.canv.restoreState()
        #self.canv.setFillColor(colors.yellow)
        self.para.drawOn(self.canv, self.x2 - self.x0,
                         self.figureHeight * 0.95 - self.pah)
        self.pre.drawOn(self.canv, self.x1 - self.x0,
                        self.figureHeight * 0.95 - self.prh)

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

  _____       _   _
 |  __ \     | | | |
 | |__) |   _| |_| |__   ___  _ __
 |  ___/ | | | __| '_ \ / _ \| '_ \
 | |   | |_| | |_| | | | (_) | | | |
 |_|    \__, |\__|_| |_|\___/|_| |_|
         __/ |
        |___/
    """,
            getSampleStyleSheet()["Code"]))
    doc.build(story, onFirstPage=number_page, onLaterPages=number_page)
Example #16
0
    def save_mesh(self, save_mesh_path, report=True):
        """
        Save the final mesh and may produce a report of the processing.
        :param save_mesh_path: Path to the desired location of the final mesh.
        :parma report: If True, also produce a report stating the processing parameters and the final mesh
        characteristics located in the same directory as the final mesh.
        """
        if save_mesh_path == "":
            save_mesh_path = os.path.splitext(self.mesh_path)[0] + "_QCTMA.cdb"
        if save_mesh_path.lower().endswith(".cdb"):
            write_cdb_mat(self.mesh_path, save_mesh_path, self.matid,
                          self.e_pool, self.density_pool)
        else:
            warnings.warn(
                "WARNING: Extension of the desired save path of the mesh not recognized. Unable to save the Mesh."
            )

        if report:
            doc_name = "%s_qctma_report.pdf" % os.path.basename(
                os.path.splitext(save_mesh_path)[0])
            doc_path = os.path.join(os.path.split(save_mesh_path)[0], doc_name)
            temp_img_path1 = os.path.join(
                os.path.split(save_mesh_path)[0], "temp_img1.png")
            temp_img_path2 = os.path.join(
                os.path.split(save_mesh_path)[0], "temp_img2.png")
            doc = SimpleDocTemplate(doc_path,
                                    pagesize=letter,
                                    rightMargin=72,
                                    leftMargin=72,
                                    topMargin=72,
                                    bottomMargin=18)
            content = []
            styles = getSampleStyleSheet()

            # gl2density function
            ptext = '<font size="16">%s</font>' % "Gray Level to Density function"
            content.append(Paragraph(ptext, styles["Normal"]))
            content.append(Spacer(1, 12))

            ptexts = [
                '%s' % line
                for line in inspect.getsource(self.gl2density).split('\n')
            ]
            for ptext in ptexts:
                content.append(Preformatted(ptext, styles["Normal"]))
            content.append(Spacer(1, 12))

            plt.figure(figsize=(5.31, 3))
            gl = np.linspace(np.min(self.image_mat), np.max(self.image_mat),
                             100)
            rho = self.gl2density(gl)
            plt.plot(gl, rho, '-')
            plt.xlabel('Gray Level')
            plt.ylabel('Density')
            plt.tight_layout()
            plt.savefig(temp_img_path1)
            im = Image(temp_img_path1)
            content.append(im)
            del im
            content.append(Spacer(1, 12))

            # density2E function
            ptext = '<font size="16">%s</font>' % "Density to Young's modulus function"
            content.append(Paragraph(ptext, styles["Normal"]))
            content.append(Spacer(1, 12))

            ptexts = [
                '%s' % line
                for line in inspect.getsource(self.density2E).split('\n')
            ]
            for ptext in ptexts:
                content.append(Preformatted(ptext, styles["Normal"]))
            content.append(Spacer(1, 12))

            plt.figure(figsize=(5.31, 3))
            rho = np.linspace(np.min(self.e_mat), np.max(self.e_mat), 100)
            e = self.density2E(rho)
            plt.plot(rho, e, '-')
            plt.xlabel('Density')
            plt.ylabel("Young's modulus")
            plt.tight_layout()
            plt.savefig(temp_img_path2)
            im = Image(temp_img_path2)
            content.append(im)
            del im
            content.append(Spacer(1, 12))

            doc.build(content)
            os.remove(temp_img_path1)
            os.remove(temp_img_path2)
Example #17
0
 def formating(self, el1='', length=40):
     el1 = '' if el1 == '' else el1.__str__()
     return Preformatted(el1, style_normal, maxLineLength=length)
Example #18
0
def content_longitude(
    c, 
    content_title=CONTENT_TITLE_CONTENT,
    content_description=CONTENT_DESCRIPTION_CONTENT,
    content_echart = 'map.jpg',
    content_page=CONTENT_PAGE_PAGE,
    content_page_subtitle = CONTENT_FOOTER_MODEL_CONTENT,
    content_page_watermarking = CONTENT_FOOTER_WATERMARKING_CONTENT,
):
    '''
    生成pdf内容--纵向文本  经度方向
    :param c  reportlab canvas 对象  object 
    :param content_title   文本标题
    :param content_description  文本描述 
    :param content_echart   插入图表的图片路径
    :param content_page     页脚  -- 页码
    :param content_page_subtitle  页脚  -- 副标题 一般与封面的中文名称保持一致
    :param content_page_watermarking  页脚 -- 水印 一般与封面的公司水印保持一致
    '''
    # c = canvas.Canvas("hello.pdf",pagesize=PDF_PAGESIZE)
    # **************  设置背景  **************
    # 设置图片的背景
    c.drawImage(CONTENT_BG,0,0,width=PDF_PAGESIZE[0],height=PDF_PAGESIZE[1],mask=None)
    # **************  设置标题  ********************
    # 设置标题字体
    c.setFont(CONTENT_TITLE_FONT,CONTENT_TITLE_FONTSIZE)
    # 填充颜色
    c.setFillColorRGB(CONTENT_TITLE_COLOR[0], CONTENT_TITLE_COLOR[1], CONTENT_TITLE_COLOR[2])
    # 设置透明度
    c.setFillAlpha(CONTENT_TITLE_OPACITY)  
    # 标题
    c.drawString(CONTENT_TITLE_POSITION[0],CONTENT_TITLE_POSITION[1],content_title)

    # **************  插入图表  ********************
    c.drawImage(
        content_echart,
        CONTENT_CHARTS_POSITION_LONGITUDE[0],
        CONTENT_CHARTS_POSITION_LONGITUDE[1],
        width=CONTENT_CHARTS_SIZE_LONGITUDE[0],
        height=CONTENT_CHARTS_SIZE_LONGITUDE[1],
        mask=None
    )
    # **************  图表说明背景  ********************
    # 填充颜色
    c.setFillColorRGB(CONTENT_DESCRIPTION_BG_COLOR[0],CONTENT_DESCRIPTION_BG_COLOR[1],CONTENT_DESCRIPTION_BG_COLOR[2])
    # 设置透明度
    c.setFillAlpha(CONTENT_DESCRIPTION_BG_OPACITY)
    # 画矩形框
    c.rect(
        CONTENT_DESCRIPTION_BG_POSITION_LONGITUDE[0],
        CONTENT_DESCRIPTION_BG_POSITION_LONGITUDE[1], 
        width = CONTENT_DESCRIPTION_BG_SIZE_LONGITUDE[0], 
        height=CONTENT_DESCRIPTION_BG_SIZE_LONGITUDE[1], 
        stroke=0, 
        fill=1
    )
    # **************  图表说明描述  *******************
    # 获取默认样式的字典对象
    styleSheet = getSampleStyleSheet()
    # 获取文本的样式
    style = styleSheet['BodyText']
    # 设置字体
    style.fontName = CONTENT_DESCRIPTION_FONT   # 字体
    # 设置字体大小
    style.fontSize = CONTENT_DESCRIPTION_FONTSIZE  # 字体大小
    # 设置行间距
    style.leading = CONTENT_DESCRIPTION_ROWSPACING_LONGITUDE
    # 设置字体颜色
    style.textColor = CONTENT_DESCRIPTION_COLOR 
    # 官方文档提示 中文要有该参数
    style.wordWrap = 'CJK'    
    # 文本格式化
    p =Preformatted(content_description,style,maxLineLength=CONTENT_DESCRIPTION_MAXLENGTH_LONGITUDE, newLineChars='')
    # 左下角为(0,0) 原点  所以纵向文本写入画布时会有问题 为了右上角对齐 
    # 纵坐标会根据文本的行数 而发生变动  变动的的纵坐标可以根据计算得出  
    # 文本域距下的像素 + 文本域空余的像素(文本域指定大小 - 根据文本行数计算而得的像素) =  写入文本的坐标位置
    # 行数间隔的像素 = 每行字的像素 + 行与行之间的空格的像素    
    t_px = len(p.lines)  * CONTENT_DESCRIPTION_ROWSPACING_LONGITUDE
    t_px = CONTENT_DESCRIPTION_POSITION_LONGITUDE[1] + 960 - t_px  if t_px <= 960 else CONTENT_DESCRIPTION_POSITION_LONGITUDE[1] 
    # 指定文本区域大小
    p.wrapOn(c,CONTENT_DESCRIPTION_SIZE_LONGITUDE[0], CONTENT_DESCRIPTION_SIZE_LONGITUDE[1])
    # 绘画在画布上
    p.drawOn(c, CONTENT_DESCRIPTION_POSITION_LONGITUDE[0], t_px)
    # **************  页脚---页码  *******************
    # 设置标题字体
    c.setFont(CONTENT_PAGE_FONT,CONTENT_PAGE_FONTSIZE)
    # 填充颜色
    c.setFillColorRGB(CONTENT_PAGE_COLOR[0], CONTENT_PAGE_COLOR[1], CONTENT_PAGE_COLOR[2])
    # 设置透明度
    c.setFillAlpha(CONTENT_PAGE_OPACITY)  
    # 标题
    c.drawString(CONTENT_PAGE_POSITION[0],CONTENT_PAGE_POSITION[1],str(content_page).zfill(2))
    # **************  页脚---模块  ******************* 
    # 设置标题字体
    c.setFont(CONTENT_FOOTER_MODEL_FONT,CONTENT_FOOTER_MODEL_FONTSIZE)
    # 填充颜色
    c.setFillColorRGB(CONTENT_FOOTER_MODEL_COLOR[0], CONTENT_FOOTER_MODEL_COLOR[1], CONTENT_FOOTER_MODEL_COLOR[2])
    # 设置透明度
    c.setFillAlpha(CONTENT_FOOTER_MODEL_OPACITY)  
    # 标题
    c.drawString(CONTENT_FOOTER_MODEL_POSITION[0],CONTENT_FOOTER_MODEL_POSITION[1],content_page_subtitle)
    # **************  页脚---水印  *******************
    # 设置标题字体
    c.setFont(CONTENT_FOOTER_WATERMARKING_FONT,CONTENT_FOOTER_WATERMARKING_FONTSIZE)
    # 填充颜色
    c.setFillColorRGB(CONTENT_FOOTER_WATERMARKING_COLOR[0], CONTENT_FOOTER_WATERMARKING_COLOR[1], CONTENT_FOOTER_WATERMARKING_COLOR[2])
    # 设置透明度
    c.setFillAlpha(CONTENT_FOOTER_WATERMARKING_OPACITY)  
    # 标题  前一个的位置+前一个的长度(字体个数*单字的像素点)+二者的间隔
    c.drawString( 
        (CONTENT_FOOTER_MODEL_POSITION[0] + len(content_page_subtitle)*CONTENT_FOOTER_WATERMARKING_FONTSIZE+CONTENT_FOOTER_WATERMARKING_INTERVAL),
        CONTENT_FOOTER_WATERMARKING_POSITION[1],
        content_page_watermarking
    )
    return c 
Example #19
0
    def generate_pdf(self):

        doc = SimpleDocTemplate(self.file_name,
                                rightMargin=72,
                                leftMargin=72,
                                topMargin=60,
                                bottomMargin=60,
                                pagesize=landscape(self.pagesize))

        styles = getSampleStyleSheet()
        style_tabl_title = ParagraphStyle('tabletitle',
                                          parent=styles["BodyText"],
                                          fontSize=8,
                                          textColor=colors.white)
        style_tabl = ParagraphStyle('tablebody',
                                    parent=styles["BodyText"],
                                    fontSize=7,
                                    textColor=colors.black)
        title_style = ParagraphStyle('title',
                                     parent=styles['Normal'],
                                     fontSize=16,
                                     leading=8,
                                     alignment=TA_LEFT)

        # Elements
        elements = []
        elements.append(
            Paragraph("Illumina NGS TST170 Panel 43 of 170", title_style))
        elements.append(Spacer(1, 20))
        elements.append(
            Preformatted(
                f"Date sample sent: {self.sample_dict.get('date_sample_sent')}               "
                f"          Date sample received: {self.sample_dict.get('date_sample_received')}",
                styles['Normal']))
        elements.append(Spacer(1, 10))

        # Headers
        tabl_headers = [
            Paragraph('Gene num', style_tabl_title),
            Paragraph('Gene name', style_tabl_title),
            Paragraph('Scope of test', style_tabl_title),
            Paragraph('Test result', style_tabl_title),
            Paragraph('Test report', style_tabl_title),
            Paragraph('Test status', style_tabl_title),
            Paragraph('Comments', style_tabl_title)
        ]

        # Gene level data
        table_data = []
        for k, v in self.sample_dict.get('genes').items():
            line_table = []
            line_table.append(Paragraph(v.get('gene'), style_tabl))
            line_table.append(Paragraph(k, style_tabl))
            line_table.append(
                Paragraph(v.get('test_scope').split(":")[1], style_tabl))
            line_table.append(Paragraph(v.get('test_results'), style_tabl))
            line_table.append(Paragraph(v.get('test_report'), style_tabl))
            test_status = v.get('test_status')
            line_table.append(Paragraph(test_status, style_tabl))
            line_table.append(Paragraph(v.get('comments'), style_tabl))
            table_data.append(line_table)

        table_data.insert(0, tabl_headers)

        table = Table(table_data, self.col_widths_dict.get(self.status))
        table.setStyle(
            TableStyle([('BACKGROUND', (0, 0), (-1, 0), colors.grey),
                        ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                        ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                        ('ROWBACKGROUNDS', (0, 1), (-1, -1),
                         [colors.lightgrey, colors.white])]))
        elements.append(table)
        elements.append(Spacer(1, 10))

        # Checker data added to report
        # For sequenced samples
        num_fails = 0
        if self.status == "s":
            sig_table_data = [["", "", "Date"],
                              [
                                  "Checker 1",
                                  self.sample_dict.get('reported_by_1'),
                                  self.sample_dict.get('date_reported_1')
                              ],
                              [
                                  "Checker 2",
                                  self.sample_dict.get('reported_by_2'),
                                  self.sample_dict.get('date_reported_2')
                              ],
                              [
                                  "Authorised",
                                  self.sample_dict.get('authorised_by'),
                                  self.sample_dict.get('date_authorised')
                              ]]
            # Count number of failed genes
            num_fails += len([
                count[-2].text for count in table_data if count[-2].text == "3"
            ])
            elements.append(
                Paragraph(f"Number of failed genes: {num_fails}",
                          styles['Normal']))
            elements.append(Spacer(1, 10))

        # For failed or withdrawn samples
        elif self.status == "f" or self.status == "w":
            sig_table_data = [["", "", "Date"],
                              [
                                  "Authorised",
                                  self.sample_dict.get('authorised_by'),
                                  self.sample_dict.get('date_authorised')
                              ]]

        else:
            raise Exception(
                "Could not determine if report is for QC fail, withdrawn or sequenced sample"
            )

        sig_table = Table(sig_table_data,
                          colWidths=[2.5 * cm, 1.5 * cm, 2.5 * cm],
                          hAlign='LEFT')
        sig_table.setStyle(
            TableStyle([('BACKGROUND', (0, 0), (-1, 0), colors.grey),
                        ('TEXTCOLOR', (0, 0), (-1, 0), colors.white),
                        ('FONTSIZE', (0, 0), (-1, -1), 8),
                        ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                        ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                        ('ROWBACKGROUNDS', (0, 1), (-1, -1), [colors.white])]))

        elements.append(sig_table)
        doc.build(elements,
                  onFirstPage=self._headers,
                  onLaterPages=self._headers,
                  canvasmaker=BespokeCanvasTemplate)
        file_name = op.basename(self.file_name)
        return f"PDF report {file_name} generated"
Example #20
0
def onPage(canvas, doc, da=None, a=None):
    width, height = canvas._doctemplate.pagesize
    canvas.saveState()
    fattura = doc.fatture[doc.fattura_corrente]
    if da is None: da = fattura.emessa_da
    if a is None: a = fattura.emessa_a
    fatturazione = FATTURE_PER_TIPO[fattura.tipo]

    stondata_style = ParagraphStyle("IntestazioneStondata",
                                    fontName='Helvetica',
                                    fontSize=8,
                                    leading=10,
                                    borderRadius=5,
                                    borderWidth=1,
                                    borderColor=colors.silver,
                                    borderPadding=5)
    a_style = ParagraphStyle("Titolo della fattura",
                             fontName='Helvetica',
                             fontSize=8,
                             leading=10)
    tipo = fattura.tipo

    # set PDF properties ***************
    canvas.setFont('Helvetica', 8)
    canvas.setAuthor(settings.LICENSE_OWNER)
    canvas.setCreator('TaM v.%s' % settings.TAM_VERSION)
    canvas._doc.info.producer = ('TaM invoices')
    canvas.setSubject(u"%s" % fattura.nome_fattura())
    if tipo == '3':
        nome = 'Ricevuta servizio TAXI'
    else:
        nome = 'Fattura'  # Fatture consorzio e conducente si chiamano semplicemente FATTURA
    descrittoreFattura = u"%s %s" % (nome, fattura.descrittore())
    canvas.setTitle(descrittoreFattura)

    # Header ***************
    y = height - doc.topMargin
    x = doc.leftMargin
    if test:
        canvas.setLineWidth(1)
        p = canvas.beginPath()
        p.moveTo(0, y)
        p.lineTo(width, y)
        canvas.drawPath(p)
    if fatturazione.mittente == "consorzio":
        logo_height = 2.5 * cm
        y -= logo_height
        canvas.drawImage(logoImage_path,
                         x=x,
                         y=y,
                         width=7 * cm,
                         height=logo_height)
    descrittore = Paragraph(
        '<font size="14"><b>%s</b></font> del %s' %
        (descrittoreFattura, localize(fattura.data)), a_style)
    descrittore.wrapOn(canvas, width / 2, y)
    descrittore.drawOn(canvas, x=x, y=y - descrittore.height)
    y -= descrittore.height + 10

    if fatturazione.mittente == "conducente":  # nelle fatture conducente metto il mittente a sinistra
        fattura_da = Paragraph(da.strip().replace('\n', '<br/>'), a_style)
        fattura_da.wrapOn(canvas, 6.5 * cm, 10 * cm)
        fattura_da.drawOn(canvas, x, y - fattura_da.height)
        y -= fattura_da.height
        y -= 0.2 * cm  # spacer tra mittente e destinatario

    if fattura.note:
        note = Preformatted(fattura.note, a_style)
        note.wrapOn(canvas, width / 2, 10 * cm)
        y = y - note.height - 8
        note.drawOn(canvas, 1 * cm, y=y)

    note_fisse = fattura.note_fisse()
    if note_fisse:  # le vecchie ricevute hanno l'indicazione di servizio emodializzato
        y = y - 10
        testata_fissa = Paragraph("<font size='6'>%s</font>" % note_fisse,
                                  a_style)
        testata_fissa.wrapOn(canvas, width / 2, 2 * cm)
        y = y - testata_fissa.height
        testata_fissa.drawOn(canvas, x, y)

    left_y = y - 8  # spacer finale

    if test:
        p = canvas.beginPath()
        p.moveTo(0, y)
        p.lineTo(width / 2, y)
        canvas.drawPath(p)

    # faccio la seconda colonna (destra) dell'header
    y = height - doc.topMargin
    x = width - 8 * cm

    if not fatturazione.mittente == "conducente":  # nelle fatture conducente ho messo già il conducente a sinistra
        fattura_da = Paragraph(da.strip().replace('\n', '<br/>'), a_style)
        fattura_da.wrapOn(canvas, 6.5 * cm, 10 * cm)
        fattura_da.drawOn(canvas, x, y - fattura_da.height)
        y -= fattura_da.height
        y -= 0.1 * cm  # spacer tra mittente e destinatario

    fattura_a = Paragraph(a.replace('\n', '<br/>'), stondata_style)
    fattura_a.wrapOn(canvas, 6.5 * cm, 10 * cm)
    fattura_a.drawOn(canvas, x,
                     y - fattura_a.height - fattura_a.style.borderPadding)

    y -= fattura_a.height + fattura_a.style.borderPadding * 2  # spazio finale
    right_y = y
    lower_y = min(left_y, right_y)

    y = lower_y

    if test:
        p = canvas.beginPath()
        p.moveTo(width / 2, y)
        p.lineTo(width, y)
        canvas.drawPath(p)

    note_finali_lines = []
    for footer_row in fattura.footer():
        note_finali_lines.append(footer_row)

    note_finali = Paragraph("<br/>".join(note_finali_lines), normalStyle)
    note_finali.wrap(width - doc.rightMargin - doc.leftMargin, 5 * cm)
    note_finali.drawOn(canvas, doc.leftMargin, doc.bottomMargin)

    # linea sotto l'intestazione
    canvas.setLineWidth(1)
    p = canvas.beginPath()
    p.moveTo(doc.leftMargin, y)
    p.lineTo(width - doc.rightMargin, y)
    canvas.drawPath(p)

    doc.pageTemplate.frames = [
        Frame(doc.leftMargin,
              doc.bottomMargin + note_finali.height,
              width - (doc.leftMargin + doc.rightMargin),
              y - doc.bottomMargin - note_finali.height,
              showBoundary=test),  # x,y, width, height
    ]

    canvas.setLineWidth(0.3)
    p = canvas.beginPath()
    p.moveTo(doc.leftMargin, doc.bottomMargin)
    p.lineTo(width - doc.rightMargin, doc.bottomMargin)
    canvas.drawPath(p)

    canvas.restoreState()
def buatPdf(chat_id):
    width, height = A4
    namafile    = "media%s.pdf"%(abs(chat_id))
    pdfmetrics.registerFont(TTFont('Candara','arial_0.ttf'))
    pdfmetrics.registerFont(TTFont('CandaraBold','arialbd_0.ttf'))
    pdfmetrics.registerFont(TTFont('CandaraItalic','ariali_0.ttf'))

    doc = SimpleDocTemplate(namafile, rightMargin=.5 * cm, leftMargin=.5 * cm,topMargin=.5 * cm, bottomMargin=1.5 * cm)
    story = []        
    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER))
    styles.add(ParagraphStyle(name='Right', alignment=TA_RIGHT))
    styles.add(ParagraphStyle(name='Left', alignment=TA_LEFT))
    styles.add(ParagraphStyle(name='Line_Data', fontName='Candara',alignment=TA_LEFT, fontSize=10, leading=10))
    # styles.add(ParagraphStyle(name='Line_Data_Angka', fontName='Candara',alignment=TA_RIGHT, fontSize=8, leading=7))
    # styles.add(ParagraphStyle(name='Line_Data_Small', fontName='Candara',alignment=TA_LEFT, fontSize=7, leading=8))
    styles.add(ParagraphStyle(name='Line_Data_Large', fontName='CandaraBold',alignment=TA_LEFT, fontSize=11, leading=12))
    # styles.add(ParagraphStyle(name='Line_Data_Largest', fontName='Candara',alignment=TA_LEFT, fontSize=15, leading=15))
    styles.add(ParagraphStyle(name='Line_Label', fontName='Candara', fontSize=11, leading=13, alignment=TA_LEFT, wordWrap = True))
    # styles.add(ParagraphStyle(name='Line_Label_Center', fontName='Candara', fontSize=10, alignment=TA_CENTER))
    styles.add(ParagraphStyle(name='judul', fontName='CandaraBold', fontSize=16, alignment=TA_CENTER,leading = 20))
    styles.add(ParagraphStyle(name='username', fontName='CandaraBold', fontSize=11, alignment=TA_LEFT,leading = 7))
    styles.add(ParagraphStyle(name='reply', fontName='CandaraItalic', fontSize=10, alignment=TA_LEFT,leading = 10))    

    data1 = [
        [Paragraph('Export media', styles["Line_Data_Large"]),
         Paragraph('', styles["Line_Data_Large"]),
         Paragraph('', styles["Line_Data_Large"])
        ],
        [Paragraph('', styles["Line_Data_Large"]),
         Paragraph('', styles["Line_Data_Large"]),         
         Paragraph('', styles["Line_Data_Large"])]]

    t1 = Table(data1, colWidths=('70%','10%','20%'))
    t1.setStyle(TableStyle([
        ('INNERGRID', (0, 0), (0, 1), 0.25, colors.black),    
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),    
    ]))
    story.append(t1)
    story.append(Spacer(0.1 * cm, .5 * cm))
    
    sql = "SELECT nomor,waktu, media_tipe, media_keyword,thumb_id, image_size  FROM media WHERE chat_id = '%s'"%chat_id
    barR, jumR = eksekusi(sql)
    
    for i in range(jumR):        
        nomor       = barR[i][0]
        waktu       = barR[i][1]
        # waktu       = datetime.strptime(waktu,"%Y-%m-%d %H:%M:%S")
        m_tipe      = barR[i][2]
        m_keyword   = barR[i][3]
        m_id        = barR[i][4]
        
        try:
          width,height = (int(b) for b in barR[i][5].split("x"))
        except Exception as a:          
          width,height = [0,0]
        

        if width > 200:
          aspect  = height / float(width)
          width   = 100
          height  = (width * aspect)
        else:
          pass
        

        mc = str(m_id)

        if width ==0 and height == 0:            
            pict = Paragraph("preview tidak tersedia", styles["Line_Label"])
        else:
            pict = Image("gambar/%s"%mc,width = width,height = height)
        # waktu = Paragraph(waktu, styles["Line_Label"])
        # tipe = Paragraph(m_tipe, styles["Line_Label"])
        keyword = Paragraph(m_keyword, styles["Line_Label"])
        caption = "%s\n%s\n%s "%(m_tipe, m_keyword,waktu)
        caption = Preformatted(caption, styles["Line_Label"],maxLineLength = 96)
          
        dataLISTwidth = ('25%','10%',None,'1%')
        
        data1 = [
          [caption,pict,'',''],          
        ]
        t1 = Table(data1, colWidths=dataLISTwidth)
        t1.setStyle(TableStyle([
          # ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
          # ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
          ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),     
          # ('SPAN',(1,0),(2,0)),   
          # ('SPAN',(1,1),(2,1)),   
        ]))
        t1.hAlign = 'LEFT'
        story.append(t1)        
        story.append(Spacer(0.1 * cm, 1 * cm))       

    doc.build(story,canvasmaker = PageNumCanvas)


# buatPdf(-1001286308688)
Example #22
0
 def formating(self, text):
     return Preformatted(text, style_normal, maxLineLength=25)
 def code(txt, story=story, styleSheet=styleSheet):
     story.append(Preformatted(txt, styleSheet['Code']))
Example #24
0
class ParaBox(figures.Figure):
    """Illustrates paragraph examples, with style attributes on the left"""
    descrStyle = ParagraphStyle('description',
                                fontName='Courier',
                                fontSize=8,
                                leading=9.6)

    def __init__(self, text, style, caption):
        figures.Figure.__init__(self, 0, 0, caption)
        self.text = text
        self.style = style
        self.para = Paragraph(text, style)

        styleText = self.getStyleText(style)
        self.pre = Preformatted(styleText, self.descrStyle)

    def wrap(self, availWidth, availHeight):
        """Left 30% is for attributes, right 50% for sample,
        10% gutter each side."""
        self.x0 = availWidth * 0.05  #left of box
        self.x1 = availWidth * 0.1   #left of descriptive text
        self.x2 = availWidth * 0.5   #left of para itself
        self.x3 = availWidth * 0.9   #right of para itself
        self.x4 = availWidth * 0.95  #right of box
        self.width = self.x4 - self.x0
        self.dx = 0.5 * (availWidth - self.width)

        paw, self.pah = self.para.wrap(self.x3 - self.x2, availHeight)
        self.pah = self.pah + self.style.spaceBefore + self.style.spaceAfter
        prw, self.prh = self.pre.wrap(self.x2 - self.x1, availHeight)
        self.figureHeight = max(self.prh, self.pah) * 10.0/9.0
        return figures.Figure.wrap(self, availWidth, availHeight)

    def getStyleText(self, style):
        """Converts style to preformatted block of text"""
        lines = []
        for (key, value) in style.__dict__.items():
            lines.append('%s = %s' % (key, value))
        lines.sort()
        return string.join(lines, '\n')

    def drawFigure(self):

        #now we fill in the bounding box and before/after boxes
        self.canv.saveState()
        self.canv.setFillGray(0.95)
        self.canv.setDash(1,3)
        self.canv.rect(self.x2 - self.x0,
                       self.figureHeight * 0.95 - self.pah,
                       self.x3-self.x2, self.para.height,
                       fill=1,stroke=1)

        self.canv.setFillGray(0.90)
        self.canv.rect(self.x2 - self.x0, #spaceBefore
                       self.figureHeight * 0.95 - self.pah + self.para.height,
                       self.x3-self.x2, self.style.spaceBefore,
                       fill=1,stroke=1)

        self.canv.rect(self.x2 - self.x0, #spaceBefore
                       self.figureHeight * 0.95 - self.pah - self.style.spaceAfter,
                       self.x3-self.x2, self.style.spaceAfter,
                       fill=1,stroke=1)

        self.canv.restoreState()
        #self.canv.setFillColor(colors.yellow)
        self.para.drawOn(self.canv, self.x2 - self.x0,
                         self.figureHeight * 0.95 - self.pah)
        self.pre.drawOn(self.canv, self.x1 - self.x0,
                         self.figureHeight * 0.95 - self.prh)


    def getStyleText(self, style):
        """Converts style to preformatted block of text"""
        lines = []
        for (key, value) in style.__dict__.items():
            if key not in ('name','parent'):
                lines.append('%s = %s' % (key, value))
        return string.join(lines, '\n')
Example #25
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)
Example #26
0
def content_latitude(
    c,
    content_title=CONTENT_TITLE_CONTENT,
    content_description=CONTENT_DESCRIPTION_CONTENT,
    content_echart = 'lines.jpg',
    content_page=CONTENT_PAGE_PAGE,
    content_page_subtitle = CONTENT_FOOTER_MODEL_CONTENT,
    content_page_watermarking = CONTENT_FOOTER_WATERMARKING_CONTENT,
):
    '''
    生成pdf内容--横向文本  纬度方向
    :param c  reportlab canvas 对象  object 
    :param content_title   文本标题
    :param content_echart  插入图表的图片路径
    :param content_page     页脚  -- 页码
    :param content_page_subtitle  页脚  -- 副标题 一般与封面的中文名称保持一致
    :param content_page_watermarking  页脚 -- 水印 一般与封面的公司水印保持一致
    '''
    # **************  设置背景  **************
    # 设置图片的背景
    c.drawImage(CONTENT_BG,0,0,width=PDF_PAGESIZE[0],height=PDF_PAGESIZE[1],mask=None)
    # **************  设置标题  ********************
    # 设置标题字体
    c.setFont(CONTENT_TITLE_FONT,CONTENT_TITLE_FONTSIZE)
    # 填充颜色
    c.setFillColorRGB(CONTENT_TITLE_COLOR[0], CONTENT_TITLE_COLOR[1], CONTENT_TITLE_COLOR[2])
    # 设置透明度
    c.setFillAlpha(CONTENT_TITLE_OPACITY)  
    # 标题
    c.drawString(CONTENT_TITLE_POSITION[0],CONTENT_TITLE_POSITION[1],content_title)

    # **************  插入图表  ********************
    c.drawImage(
        content_echart,
        CONTENT_CHARTS_POSITION_LATITUDE[0],
        CONTENT_CHARTS_POSITION_LATITUDE[1],
        width=CONTENT_CHARTS_SIZE_LATITUDE[0],
        height=CONTENT_CHARTS_SIZE_LATITUDE[1],
        mask=None)
    # **************  图表说明背景  ********************
    # 填充颜色
    c.setFillColorRGB(CONTENT_DESCRIPTION_BG_COLOR[0],CONTENT_DESCRIPTION_BG_COLOR[1],CONTENT_DESCRIPTION_BG_COLOR[2])
    # 设置透明度
    c.setFillAlpha(CONTENT_DESCRIPTION_BG_OPACITY)
    # 画矩形框
    c.rect(
        CONTENT_DESCRIPTION_BG_POSITION_LATITUDE[0],
        CONTENT_DESCRIPTION_BG_POSITION_LATITUDE[1], 
        width = CONTENT_DESCRIPTION_BG_SIZE_LATITUDE[0], 
        height=CONTENT_DESCRIPTION_BG_SIZE_LATITUDE[1], 
        stroke=0, 
        fill=1
    )
    # **************  图表说明描述  *******************
    # 获取默认样式的字典对象
    styleSheet = getSampleStyleSheet()
    # 获取文本的样式
    style = styleSheet['BodyText']
    # 设置字体
    style.fontName = CONTENT_DESCRIPTION_FONT   # 字体
    # 设置字体大小
    style.fontSize = CONTENT_DESCRIPTION_FONTSIZE  # 字体大小
    # 设置行间距
    style.leading = CONTENT_DESCRIPTION_ROWSPACING_LATITUDE
    # 设置字体颜色
    style.textColor = CONTENT_DESCRIPTION_COLOR 
    # 官方文档提示 中文要有该参数
    style.wordWrap = 'CJK'    
    # 文本格式化
    p =Preformatted(content_description,style,maxLineLength=CONTENT_DESCRIPTION_MAXLENGTH_LATITUDE, newLineChars='')
    # 指定文本区域大小
    p.wrapOn(c,CONTENT_DESCRIPTION_SIZE_LATITUDE[0], CONTENT_DESCRIPTION_SIZE_LATITUDE[1])
    # 绘画在画布上
    p.drawOn(c, CONTENT_DESCRIPTION_POSITION_LATITUDE[0], CONTENT_DESCRIPTION_POSITION_LATITUDE[1])
    # **************  页脚---页码  *******************
    # 设置标题字体
    c.setFont(CONTENT_PAGE_FONT,CONTENT_PAGE_FONTSIZE)
    # 填充颜色
    c.setFillColorRGB(CONTENT_PAGE_COLOR[0], CONTENT_PAGE_COLOR[1], CONTENT_PAGE_COLOR[2])
    # 设置透明度
    c.setFillAlpha(CONTENT_PAGE_OPACITY)  
    # 标题
    c.drawString(CONTENT_PAGE_POSITION[0],CONTENT_PAGE_POSITION[1],str(content_page).zfill(2))
    # **************  页脚---模块  ******************* 
    # 设置标题字体
    c.setFont(CONTENT_FOOTER_MODEL_FONT,CONTENT_FOOTER_MODEL_FONTSIZE)
    # 填充颜色
    c.setFillColorRGB(CONTENT_FOOTER_MODEL_COLOR[0], CONTENT_FOOTER_MODEL_COLOR[1], CONTENT_FOOTER_MODEL_COLOR[2])
    # 设置透明度
    c.setFillAlpha(CONTENT_FOOTER_MODEL_OPACITY)  
    # 标题
    c.drawString(CONTENT_FOOTER_MODEL_POSITION[0],CONTENT_FOOTER_MODEL_POSITION[1],content_page_subtitle)
    # **************  页脚---水印  *******************
    # 设置标题字体
    c.setFont(CONTENT_FOOTER_WATERMARKING_FONT,CONTENT_FOOTER_WATERMARKING_FONTSIZE)
    # 填充颜色
    c.setFillColorRGB(CONTENT_FOOTER_WATERMARKING_COLOR[0], CONTENT_FOOTER_WATERMARKING_COLOR[1], CONTENT_FOOTER_WATERMARKING_COLOR[2])
    # 设置透明度
    c.setFillAlpha(CONTENT_FOOTER_WATERMARKING_OPACITY)  
    # 标题  前一个的位置+前一个的长度(字体个数*单字的像素点)+二者的间隔
    c.drawString( 
        (CONTENT_FOOTER_MODEL_POSITION[0] + len(content_page_subtitle)*CONTENT_FOOTER_WATERMARKING_FONTSIZE+CONTENT_FOOTER_WATERMARKING_INTERVAL),
        CONTENT_FOOTER_WATERMARKING_POSITION[1],
        content_page_watermarking
    )
    return c 
Example #27
0
def Group(group, grupo):
    leyenda = []
    line = []
    dato = []
    if 'columns' in group[group.keys()[0]]['properties']:
        columns = group[group.keys()[0]]['properties'][
            'columns']  # Cantidad de columnas de cada grupo
    else:
        columns = '1'
    LineLeng = LineLengLebel // int(
        columns)  # cantidad de caracteres por fila Titulos
    LineLeng2 = LineLengVal // int(
        columns)  # cantidad de caracteres por fila Valores
    for component in group[group.keys()
                           [0]]['components']:  # Recorro Componentes
        types = component[component.keys()[0]]['type']
        if 'label' in component[component.keys()[0]]['properties']:
            if types == 'grid':
                leyenda = component[component.keys()
                                    [0]]['properties']['header']
            else:
                leyenda.append(
                    Preformatted(
                        component[component.keys()[0]]['properties']['label'],
                        styles['stileLeyenda'],
                        maxLineLength=LineLeng))  # Etiquetas de las columnas
        else:
            leyenda.append(
                Preformatted(
                    '', styles['stileLeyenda'],
                    maxLineLength=LineLeng))  # Etiquetas de las columnas
        try:
            if types == 'combo':
                if 'multiselect' in component[component.keys()
                                              [0]]['properties']:
                    if component[component.keys()
                                 [0]]['properties']['multiselect']:
                        texto = toolbox.multiSelection_to_text(
                            valor[grupo][component[component.keys()[0]]
                                         ['properties']['name']])
                    else:
                        texto = str(
                            valor[grupo][component[component.keys()[0]]
                                         ['properties']['name']]['text'])
                else:
                    texto = str(valor[grupo][component[component.keys()[0]]
                                             ['properties']['name']]['text'])
            elif types == 'date':
                texto = str(
                    formatDate(valor[grupo][component[component.keys()[0]]
                                            ['properties']['name']]))
            elif types == 'label':
                texto = str('')
            # elif  types == 'password':
            # texto = '**********'
            elif types == 'grid':
                return types_grid(
                    leyenda, valor[grupo][component[component.keys()[0]]
                                          ['properties']['name']])
            else:
                texto = str(valor[grupo][component[component.keys()[0]]
                                         ['properties']['name']])
        except Exception, e:
            texto = '____________________'
        dato.append(
            Preformatted(texto, styles['stileVal'],
                         maxLineLength=LineLeng2))  # Valores
        if columns == str(len(leyenda)):  # Carga las Lineas.
            line.append(leyenda)
            leyenda = []
            line.append(dato)
            dato = []
Example #28
0
File: pdf.py Project: dariosky/tam
def onPage(canvas, doc, da=None, a=None):
    width, height = canvas._doctemplate.pagesize
    canvas.saveState()
    fattura = doc.fatture[doc.fattura_corrente]
    if da is None: da = fattura.emessa_da
    if a is None: a = fattura.emessa_a
    fatturazione = FATTURE_PER_TIPO[fattura.tipo]

    stondata_style = ParagraphStyle("IntestazioneStondata", fontName='Helvetica', fontSize=8,
                                    leading=10,
                                    borderRadius=5, borderWidth=1, borderColor=colors.silver,
                                    borderPadding=5)
    a_style = ParagraphStyle("Titolo della fattura", fontName='Helvetica', fontSize=8, leading=10)
    tipo = fattura.tipo

    # set PDF properties ***************
    canvas.setFont('Helvetica', 8)
    canvas.setAuthor(settings.LICENSE_OWNER)
    canvas.setCreator('TaM v.%s' % settings.TAM_VERSION)
    canvas._doc.info.producer = ('TaM invoices')
    canvas.setSubject(u"%s" % fattura.nome_fattura())
    nome = fattura.custom_name
    descrittoreFattura = u"%s %s" % (nome, fattura.descrittore())
    canvas.setTitle(descrittoreFattura)

    # Header ***************
    y = height - doc.topMargin
    x = doc.leftMargin
    if test:
        canvas.setLineWidth(1)
        p = canvas.beginPath()
        p.moveTo(0, y)
        p.lineTo(width, y)
        canvas.drawPath(p)
    if fatturazione.mittente == "consorzio":
        logo_height = 2.5 * cm
        y -= logo_height
        canvas.drawImage(logoImage_path, x=x, y=y, width=7 * cm, height=logo_height)
    descrittore = Paragraph(
        '<font size="14"><b>%s</b></font> del %s' % (descrittoreFattura, localize(fattura.data)),
        a_style)
    descrittore.wrapOn(canvas, width / 2, y)
    descrittore.drawOn(canvas, x=x, y=y - descrittore.height)
    y -= descrittore.height + 10

    if fatturazione.mittente == "conducente":  # nelle fatture conducente metto il mittente a sinistra
        fattura_da = Paragraph(da.strip().replace('\n', '<br/>'), a_style)
        fattura_da.wrapOn(canvas, 6.5 * cm, 10 * cm)
        fattura_da.drawOn(canvas, x, y - fattura_da.height)
        y -= fattura_da.height
        y -= 0.2 * cm  # spacer tra mittente e destinatario

    if fattura.note:
        note = Preformatted(fattura.note, a_style)
        note.wrapOn(canvas, width / 2, 10 * cm)
        y = y - note.height - 8
        note.drawOn(canvas, 1 * cm, y=y)

    note_fisse = fattura.note_fisse()
    if note_fisse:  # le vecchie ricevute hanno l'indicazione di servizio emodializzato
        y = y - 10
        testata_fissa = Paragraph("<font size='6'>%s</font>" % note_fisse, a_style)
        testata_fissa.wrapOn(canvas, width / 2, 2 * cm)
        y = y - testata_fissa.height
        testata_fissa.drawOn(canvas, x, y)

    left_y = y - 8  # spacer finale

    if test:
        p = canvas.beginPath()
        p.moveTo(0, y)
        p.lineTo(width / 2, y)
        canvas.drawPath(p)

    # faccio la seconda colonna (destra) dell'header
    y = height - doc.topMargin
    x = width - 8 * cm

    if not fatturazione.mittente == "conducente":  # nelle fatture conducente ho messo già il conducente a sinistra
        fattura_da = Paragraph(da.strip().replace('\n', '<br/>'), a_style)
        fattura_da.wrapOn(canvas, 6.5 * cm, 10 * cm)
        fattura_da.drawOn(canvas, x, y - fattura_da.height)
        y -= fattura_da.height
        y -= 0.1 * cm  # spacer tra mittente e destinatario

    fattura_a = Paragraph(a.replace('\n', '<br/>'), stondata_style)
    fattura_a.wrapOn(canvas, 6.5 * cm, 10 * cm)
    fattura_a.drawOn(canvas, x, y - fattura_a.height - fattura_a.style.borderPadding)

    y -= fattura_a.height + fattura_a.style.borderPadding * 2  # spazio finale
    right_y = y
    lower_y = min(left_y, right_y)

    y = lower_y

    if test:
        p = canvas.beginPath()
        p.moveTo(width / 2, y)
        p.lineTo(width, y)
        canvas.drawPath(p)

    note_finali_lines = []
    for footer_row in fattura.footer():
        note_finali_lines.append(footer_row)

    note_finali = Paragraph("<br/>".join(note_finali_lines), normalStyle)
    note_finali.wrap(width - doc.rightMargin - doc.leftMargin, 5 * cm)
    note_finali.drawOn(canvas, doc.leftMargin, doc.bottomMargin)

    # linea sotto l'intestazione
    canvas.setLineWidth(1)
    p = canvas.beginPath()
    p.moveTo(doc.leftMargin, y)
    p.lineTo(width - doc.rightMargin, y)
    canvas.drawPath(p)

    doc.pageTemplate.frames = [
        Frame(doc.leftMargin, doc.bottomMargin + note_finali.height,
              width - (doc.leftMargin + doc.rightMargin),
              y - doc.bottomMargin - note_finali.height,
              showBoundary=test),  # x,y, width, height
    ]

    canvas.setLineWidth(0.3)
    p = canvas.beginPath()
    p.moveTo(doc.leftMargin, doc.bottomMargin)
    p.lineTo(width - doc.rightMargin, doc.bottomMargin)
    canvas.drawPath(p)

    canvas.restoreState()
Example #29
0
def build(spec, data):
    reload(sys)
    sys.setdefaultencoding("utf-8")
    init()
    global form
    form = spec
    global valor
    valor = data
    story = []
    head = []
    header = form['header']['name']  # Title Form
    for group in form['payload']:  # Load Group
        # si el grupo tiene propiedad showby y no tiene 'data' no se imprime el mismo.
        if 'showby' in group[group.keys()[0]]['properties']:
            showby = group[group.keys()[0]]['properties']['showby']
            if showby == None:
                group_showby = True
            elif showby == 'true':
                group_showby = True
            elif showby == '':
                group_showby = True
            elif showby == False:
                group_showby = False
            elif showby == True:
                group_showby = True
            elif len(showby) != 0:
                if group.keys()[0] in valor:  # si el grupo tiene datos
                    if len(valor[group.keys()[0]]) == 0:
                        group_showby = False
                    else:
                        group_showby = True
                else:
                    group_showby = False
            else:
                group_showby = True
        else:
            group_showby = True

        # check 'notshowgroupinpdf'
        if 'notshowgroupinpdf' in group[group.keys()[0]]['properties']:
            if group[group.keys()
                     [0]]['properties']['notshowgroupinpdf'] == True:
                group_showby = False

        if group_showby:
            head = []
            if 'label' in group[group.keys()[0]]['properties']:
                head.append(
                    [
                        Preformatted(
                            group[group.keys()[0]]['properties']['label'],
                            styles['stileheader2'],
                            maxLineLength=500)
                    ]
                )  # Titulo del Grupo / meto el titulo dentro de la tabla para obtener la misma tabulacion de los detalles
            else:
                head.append(
                    [
                        Preformatted('',
                                     styles['stileheader2'],
                                     maxLineLength=150)
                    ]
                )  # Titulo del Grupo / meto el titulo dentro de la tabla para obtener la misma tabulacion de los detalles
            table = Table(head, colWidths='100%')
            table.hAlign = TA_LEFT
            story.append(table)
            story.append(Spacer(1, 3))
            #story.append(separador)
            story.append(Spacer(1, 5))
            table = Table([''])

            grupo = group[group.keys()[0]]['properties'][
                'name']  # nombre del Grupo
            if 'usedatagrid' in group[group.keys()[0]]['properties']:
                datagrid = group[group.keys()[0]]['properties']['usedatagrid']
            else:
                datagrid = False

            if 'components' in group[group.keys()[0]] and datagrid == True:
                data_Grid = Grid(group, grupo)
                if len(data_Grid) != 0:
                    table = Table(data_Grid, colWidths='100%')
            elif 'components' in group[group.keys()[0]] and datagrid == False:
                table = Table(Group(group, grupo), colWidths='100%')
            else:
                table = Table([''])

            table.hAlign = TA_LEFT
            story.append(table)
            story.append(Spacer(1, 15))

    doc = docTemplate(files)
    doc.build(story)  # save pdf

    with open(files, "rb") as image_file:  # Transforma PDF en binario base64
        encoded_string = base64.b64encode(image_file.read())
    os.remove(files)  # remove  file

    return encoded_string
def getExamples():
    """Returns all the example flowable objects"""
    styleSheet = getSampleStyleSheet()

    story = []

    #make a style with indents and spacing
    sty = ParagraphStyle('obvious', None)
    sty.leftIndent = 18
    sty.rightIndent = 18
    sty.firstLineIndent = 18
    sty.spaceBefore = 6
    sty.spaceAfter = 6
    story.append(
        Paragraph(
            """Now for some demo stuff - we need some on this page,
        even before we explain the concepts fully""", styleSheet['BodyText']))
    p = Paragraph(
        """
        Platypus is all about fitting objects into frames on the page.  You
        are looking at a fairly simple Platypus paragraph in Debug mode.
        It has some gridlines drawn around it to show the left and right indents,
        and the space before and after, all of which are attributes set in
        the style sheet.  To be specific, this paragraph has left and
        right indents of 18 points, a first line indent of 36 points,
        and 6 points of space before and after itself.  A paragraph
        object fills the width of the enclosing frame, as you would expect.""",
        sty)

    p.debug = 1  #show me the borders
    story.append(p)

    story.append(
        Paragraph(
            """Same but with justification 1.5 extra leading and green text.""",
            styleSheet['BodyText']))
    p = Paragraph(
        """
        <para align=justify leading="+1.5" fg=green><font color=red>Platypus</font> is all about fitting objects into frames on the page.  You
        are looking at a fairly simple Platypus paragraph in Debug mode.
        It has some gridlines drawn around it to show the left and right indents,
        and the space before and after, all of which are attributes set in
        the style sheet.  To be specific, this paragraph has left and
        right indents of 18 points, a first line indent of 36 points,
        and 6 points of space before and after itself.  A paragraph
        object fills the width of the enclosing frame, as you would expect.</para>""",
        sty)

    p.debug = 1  #show me the borders
    story.append(p)

    story.append(
        platypus.XBox(4 * inch, 0.75 * inch,
                      'This is a box with a fixed size'))

    story.append(
        Paragraph(
            """
        All of this is being drawn within a text frame which was defined
        on the page.  This frame is in 'debug' mode so you can see the border,
        and also see the margins which it reserves.  A frame does not have
        to have margins, but they have been set to 6 points each to create
        a little space around the contents.
        """, styleSheet['BodyText']))

    story.append(FrameBreak())

    #######################################################################
    #     Examples Page 2
    #######################################################################

    story.append(
        Paragraph(
            """
        Here's the base class for Flowable...
        """, styleSheet['Italic']))

    code = '''class Flowable:
        """Abstract base class for things to be drawn.  Key concepts:
    1. It knows its size
    2. It draws in its own coordinate system (this requires the
        base API to provide a translate() function.
        """
    def __init__(self):
        self.width = 0
        self.height = 0
        self.wrapped = 0

    def drawOn(self, canvas, x, y):
        "Tell it to draw itself on the canvas.  Do not override"
        self.canv = canvas
        self.canv.saveState()
        self.canv.translate(x, y)

        self.draw()   #this is the bit you overload

        self.canv.restoreState()
        del self.canv

    def wrap(self, availWidth, availHeight):
        """This will be called by the enclosing frame before objects
        are asked their size, drawn or whatever.  It returns the
        size actually used."""
        return (self.width, self.height)
    '''

    story.append(Preformatted(code, styleSheet['Code'], dedent=4))
    story.append(FrameBreak())
    #######################################################################
    #     Examples Page 3
    #######################################################################

    story.append(
        Paragraph("Here are some examples of the remaining objects above.",
                  styleSheet['Italic']))

    story.append(
        Paragraph("This is a bullet point",
                  styleSheet['Bullet'],
                  bulletText='O'))
    story.append(
        Paragraph("Another bullet point", styleSheet['Bullet'],
                  bulletText='O'))

    story.append(
        Paragraph(
            """Here is a Table, which takes all kinds of formatting options...""",
            styleSheet['Italic']))
    story.append(platypus.Spacer(0, 12))

    g = platypus.Table(
        (('', 'North', 'South', 'East', 'West'),
         ('Quarter 1', 100, 200, 300, 400), ('Quarter 2', 100, 200, 300, 400),
         ('Total', 200, 400, 600, 800)), (72, 36, 36, 36, 36),
        (24, 16, 16, 18))
    style = platypus.TableStyle([
        ('ALIGN', (1, 1), (-1, -1), 'RIGHT'),
        ('ALIGN', (0, 0), (-1, 0), 'CENTRE'),
        ('GRID', (0, 0), (-1, -1), 0.25, colors.black),
        ('LINEBELOW', (0, 0), (-1, 0), 2, colors.black),
        ('LINEBELOW', (1, -1), (-1, -1), 2, (0.5, 0.5, 0.5)),
        ('TEXTCOLOR', (0, 1), (0, -1), colors.black),
        ('BACKGROUND', (0, 0), (-1, 0), (0, 0.7, 0.7))
    ])
    g.setStyle(style)
    story.append(g)
    story.append(FrameBreak())

    #######################################################################
    #     Examples Page 4 - custom fonts
    #######################################################################
    # custom font with LettError-Robot font
    import reportlab.rl_config
    reportlab.rl_config.warnOnMissingFontGlyphs = 0

    from reportlab.pdfbase import pdfmetrics
    fontDir = os.path.join(_RL_DIR, 'fonts')
    face = pdfmetrics.EmbeddedType1Face(
        os.path.join(fontDir, 'DarkGardenMK.afm'),
        os.path.join(fontDir, 'DarkGardenMK.pfb'))
    faceName = face.name  # should be 'DarkGardenMK'
    pdfmetrics.registerTypeFace(face)
    font = pdfmetrics.Font(faceName, faceName, 'WinAnsiEncoding')
    pdfmetrics.registerFont(font)

    # put it inside a paragraph.
    story.append(
        Paragraph(
            """This is an ordinary paragraph, which happens to contain
        text in an embedded font:
        <font name="DarkGardenMK">DarkGardenMK</font>.
        Now for the real challenge...""", styleSheet['Normal']))

    styRobot = ParagraphStyle('Robot', styleSheet['Normal'])
    styRobot.fontSize = 16
    styRobot.leading = 20
    styRobot.fontName = 'DarkGardenMK'

    story.append(
        Paragraph("This whole paragraph is 16-point DarkGardenMK.", styRobot))
    story.append(FrameBreak())

    if _GIF:
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from a string filename.",
                styleSheet['Italic']))
        story.append(platypus.Image(_GIF))
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from a utf8 filename.",
                styleSheet['Italic']))
        #story.append(platypus.Image(fileName2FSEnc(_GIF)))
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from a string file url.",
                styleSheet['Italic']))
        story.append(platypus.Image(getFurl(_GIF)))
        story.append(
            Paragraph("Here is an Image flowable obtained from an open file.",
                      styleSheet['Italic']))
        story.append(platypus.Image(open_for_read(_GIF, 'b')))
        story.append(FrameBreak())
        try:
            img = platypus.Image(
                'http://www.reportlab.com/rsrc/encryption.gif')
            story.append(
                Paragraph(
                    "Here is an Image flowable obtained from a string http url.",
                    styleSheet['Italic']))
            story.append(img)
        except:
            story.append(
                Paragraph(
                    "The image could not be obtained from a string http url.",
                    styleSheet['Italic']))
        story.append(FrameBreak())

    if _JPG:
        img = platypus.Image(_JPG)
        story.append(
            Paragraph(
                "Here is an JPEG Image flowable obtained from a filename.",
                styleSheet['Italic']))
        story.append(img)
        story.append(
            Paragraph(
                "Here is an JPEG Image flowable obtained from an open file.",
                styleSheet['Italic']))
        img = platypus.Image(open_for_read(_JPG, 'b'))
        story.append(img)
        story.append(FrameBreak())

    return story
Example #31
0
def buatPdf(chat_id):
    width, height = A4
    pdfmetrics.registerFont(TTFont('Candara','arial_0.ttf'))
    pdfmetrics.registerFont(TTFont('CandaraBold','arialbd_0.ttf'))
    pdfmetrics.registerFont(TTFont('CandaraItalic','ariali_0.ttf'))

    sql = "SELECT nomor,waktu, judul, author,chat_title  FROM rekam WHERE chat_id = '%s' AND done = 0"%chat_id
    bar, jum = eksekusi(sql)
    
    nomor       = bar[0][0]
    waktu       = bar[0][1]
    judul       = bar[0][2]
    if judul == '0':
      judul = '(untitled)'
    author      = bar[0][3]
    if author == None:
      author = "all member"
    else:
      author = "@%s"%author
    chat_title  = bar[0][4]
    tanggalexp  = datetime.strptime(waktu,"%Y-%m-%d")
    waktu       = tanggalexp.strftime("%d %b %Y")
    namafile    = "%s%s.pdf"%(abs(chat_id), nomor)

    header = {
      'chat_id' : chat_id, 
      'chat_title' : chat_title, 
      'no'      : nomor,
      'judul'   : judul,
      'author'  : author,
      'waktu'   : waktu,
      }

    doc = SimpleDocTemplate(namafile, rightMargin=.5 * cm, leftMargin=.5 * cm,topMargin=.5 * cm, bottomMargin=1.5 * cm)
    story = []        
    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER))
    styles.add(ParagraphStyle(name='Right', alignment=TA_RIGHT))
    styles.add(ParagraphStyle(name='Left', alignment=TA_LEFT))
    styles.add(ParagraphStyle(name='Line_Data', fontName='Candara',alignment=TA_LEFT, fontSize=10, leading=10))
    # styles.add(ParagraphStyle(name='Line_Data_Angka', fontName='Candara',alignment=TA_RIGHT, fontSize=8, leading=7))
    # styles.add(ParagraphStyle(name='Line_Data_Small', fontName='Candara',alignment=TA_LEFT, fontSize=7, leading=8))
    styles.add(ParagraphStyle(name='Line_Data_Large', fontName='CandaraBold',alignment=TA_LEFT, fontSize=11, leading=12))
    # styles.add(ParagraphStyle(name='Line_Data_Largest', fontName='Candara',alignment=TA_LEFT, fontSize=15, leading=15))
    styles.add(ParagraphStyle(name='Line_Label', fontName='Candara', fontSize=11, leading=13, alignment=TA_LEFT, wordWrap = True))
    # styles.add(ParagraphStyle(name='Line_Label_Center', fontName='Candara', fontSize=10, alignment=TA_CENTER))
    styles.add(ParagraphStyle(name='judul', fontName='CandaraBold', fontSize=16, alignment=TA_CENTER,leading = 20))
    styles.add(ParagraphStyle(name='username', fontName='CandaraBold', fontSize=11, alignment=TA_LEFT,leading = 7))
    styles.add(ParagraphStyle(name='reply', fontName='CandaraItalic', fontSize=10, alignment=TA_LEFT,leading = 10))    

    data1 = [
        [Paragraph(header['chat_title'], styles["Line_Data_Large"]),
         Paragraph('Tanggal', styles["Line_Data_Large"]),
         Paragraph(header['waktu'], styles["Line_Data_Large"])
        ],
        [Paragraph('kulgram ke %s'%header['no'], styles["Line_Data_Large"]),
         Paragraph('Author', styles["Line_Data_Large"]),         
         Paragraph('%s'%header['author'], styles["Line_Data_Large"])]]

    t1 = Table(data1, colWidths=('70%','10%','20%'))
    t1.setStyle(TableStyle([
        ('INNERGRID', (0, 0), (0, 1), 0.25, colors.black),    
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),    
    ]))
    story.append(t1)
    story.append(Spacer(0.1 * cm, .5 * cm))
    story.append(Paragraph("<b>%s</b>"%header['judul'], styles["judul"]))
    story.append(Spacer(0.1 * cm, .8 * cm))
    sql_rangkum = "SELECT waktu, nama, message_chat, message_media, message_id, reply_to,username,forward_username, forward_name,image_size FROM rekam_log WHERE nomor = '%s' AND chat_id = '%s'"%(bar[0][0],chat_id)
    barR,jumR = eksekusi(sql_rangkum)
    # jumR = 93
    for i in range(jumR):

        waktu         = str(barR[i][0])        
        username      = str(barR[i][6])
        nama          = barR[i][1]
        try:
          tanggalexp    = datetime.strptime(waktu,"%Y-%m-%d %H:%M:%S")        
          waktu         = tanggalexp.strftime("%H:%M:%S")
        except:
          tanggalexp = parse(waktu).strftime("%Y-%m-%d %H:%M:%S")
          waktu         = parse(waktu).strftime("%H:%M:%S")
        
        dataLISTwidth = ('8%','8%','84%')
        reply_to      = barR[i][5]
        forward_username = barR[i][7]
        try:
          width,height = (int(b) for b in barR[i][9].split("x"))
        except Exception as a:          
          width,height = [0,0]
        

        if width > 400:
          aspect  = height / float(width)
          width   = 200
          height  = (width * aspect)
        else:
          pass
        

        if reply_to == '0':
          pass
        else:
          baca_reply = "SELECT waktu, nama, message_chat FROM rekam_log WHERE nomor = '%s' AND chat_id = '%s' AND message_id = '%s'"%(bar[0][0],chat_id,reply_to)
          barReply,jumReply = eksekusi(baca_reply)

          if jumReply == 0:
            pass
          else:

            try:
              message_chat = barReply[0][2].decode('utf-8')
            except Exception as e:
              message_chat = barReply[0][2]

            try:
              waktureply = datetime.strptime(barReply[0][0],"%Y-%m-%d %H:%M:%S").strftime("%H:%M:%S")
            except:
              waktureply = parse(barReply[0][0]).strftime("%H:%M:%S")
            data1 = [[
              Paragraph('', styles["Line_Label"]),
              Paragraph('<font size = 8 color = grey>%s</font>'%waktureply, styles["reply"]),
              Paragraph('%s <font color= grey>%s</font>'%((barReply[0][1]),str(message_chat).replace("\\n","<br/>")), styles["reply"]),
            ]]
            dataLISTwidth = ('8%','8%','84%')
            t1 = Table(data1, colWidths=dataLISTwidth)            
            t1.hAlign = 'LEFT'
            t1.setStyle(TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP')]))
            story.append(t1)   

        if forward_username is None:
          try:
            data1 = [[
                Paragraph('<img src = "gambar/%s" width = 32 height = 32 valign = "top"></img>'%username, styles["Line_Data"]),
                Paragraph('<font size = 8 color = grey>%s</font>'%waktu, styles["Line_Data"]),
                Paragraph(html.escape(nama), styles["username"]),
                ]]
          except:
            data1 = [[
                Paragraph('', styles["Line_Data"]),
                Paragraph('<font size = 8 color = grey>%s</font>'%waktu, styles["Line_Data"]),
                Paragraph(html.escape(nama), styles["username"]),
                ]]
        else:
          try:
            data1 = [[
                Paragraph('<img src = "gambar/%s" width = 32 height = 32 valign = "top"></img>'%username, styles["Line_Data"]),
                Paragraph('<font size = 8 color = grey>%s</font>'%waktu, styles["Line_Data"]),
                Paragraph("Forwarded from %s"%html.escape(forward_username), styles["username"]),
                ]]
          except:
            data1 = [[
                Paragraph('', styles["Line_Data"]),
                Paragraph('<font size = 8 color = grey>%s</font>'%waktu, styles["Line_Data"]),
                Paragraph("Forwarded from %s"%html.escape(forward_username), styles["username"]),
                ]]
        t1 = Table(data1, colWidths=dataLISTwidth)            
        t1.hAlign = 'LEFT'
        t1.setStyle(TableStyle([
            # ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            # ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ]))
        story.append(t1)
        
        try:          
          reshaped_text = reshaper.reshape(emoji.demojize(barR[i][2]))
          message_chat = get_display(reshaped_text)
        except:
          message_chat = barR[i][2]
        
        mc = str(barR[i][3])        
        if mc=='':
          pict = Paragraph('', styles["Line_Data"])
        else:
          pict = Image("gambar/%s"%mc,width = width,height = height)
          
        caption2 = ""
        if message_chat == None:
          caption = Paragraph('', styles["Line_Data"])
        else:          
          if (len(message_chat.splitlines())) > 59:
            lines     = len(''.join(message_chat.splitlines()[:60]))
            caption0  = (message_chat[:lines]+"...(Teks dipotong ke baris berikutnya)")
            caption   = ("(sambungan)..."+message_chat[lines:])
            data0     = [
              [Paragraph('', styles["Line_Label"]),pict,Paragraph('', styles["Line_Label"]),],
              [Paragraph('', styles["Line_Label"]),caption0,Paragraph('', styles["Line_Data"])]
            ]
            t0 = Table(data0, colWidths=dataLISTwidth)
            t0.setStyle(TableStyle([
              # ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
              # ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
              # ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),     
              ('SPAN',(1,0),(2,0)),   
              ('SPAN',(1,1),(2,1)),   
            ]))
            t0.hAlign = 'LEFT'
            story.append(t0)            
          else:
            caption = Preformatted(message_chat, styles["Line_Label"],maxLineLength = 96)

        dataLISTwidth = ('8%','8%','84%')
        data1 = [
          [Paragraph('', styles["Line_Label"]),pict,Paragraph('', styles["Line_Label"]),],
          [Paragraph('', styles["Line_Label"]),caption,Paragraph('', styles["Line_Data"])]
        ]
        t1 = Table(data1, colWidths=dataLISTwidth)
        t1.setStyle(TableStyle([
          # ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
          # ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
          # ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),     
          ('SPAN',(1,0),(2,0)),   
          ('SPAN',(1,1),(2,1)),   
        ]))
        t1.hAlign = 'LEFT'
        story.append(t1)        
        story.append(Spacer(0.1 * cm, 1 * cm))       

    doc.build(story,canvasmaker = PageNumCanvas)
Example #32
0
 def getFlowable(self):
     return Preformatted(self.rawtext, getStyles()[self.style])
Example #33
0
def get_base64_pdf_content(renglones):
	reload(sys)
	sys.setdefaultencoding("utf-8")
	story = []
	line = []
	row = []
	renglon = []

	story.append(Spacer(1, 5))
	#story.append(separador)
	story.append(Spacer(1, 10))
	line = []
	for linea in renglones:
	  if len(linea) !=0:
	  	print linea  	
		if renglon != '' and renglon != str(linea['2']):
			if line != []:
				table = Table(line)    
				table.rowheights = 1
				table.hAlign = TA_LEFT
				story.append(table)
				line = []

			renglon = str(linea['2']) 
			title = []
			line.append([])
			title.append(Preformatted('Renglon', styles['stileLeyenda'], maxLineLength=7))
			title.append(Preformatted('Cantidad', styles['stileLeyenda'], maxLineLength=8))
			title.append(Preformatted('Unidad de Medida', styles['stileLeyenda'], maxLineLength=16))
			title.append(Preformatted('Codigo SIByS', styles['stileLeyenda'], maxLineLength=20))
			title.append(Preformatted('Descripcion', styles['stileLeyenda']))
			line.append(title)
			title = []
			title.append(Preformatted(str(linea['2']), styles['stileVal'], maxLineLength=7))
			title.append(Preformatted(str(linea['3']), styles['stileVal'], maxLineLength=16))
			title.append(Preformatted(str(linea['4']), styles['stileVal'], maxLineLength=16))
			title.append(Preformatted(str(linea['5']), styles['stileVal'], maxLineLength=20))
			title.append(Preformatted(str(linea['6']), styles['stileVal'], maxLineLength=30))  
			line.append(title)
			title = []
			row = []
			row.append(Preformatted('Razon Social', styles['stileLeyenda'], maxLineLength=15))        
			row.append(Preformatted('CUIT', styles['stileLeyenda'], maxLineLength=11))
			row.append(Preformatted('Tipo de Oferta', styles['stileLeyenda'], maxLineLength=14))
			row.append(Preformatted('Cantidad Ofertada', styles['stileLeyenda'], maxLineLength=17))
			row.append(Preformatted('Importe Unitario', styles['stileLeyenda'], maxLineLength=18))
			row.append(Preformatted('IVA', styles['stileLeyenda'], maxLineLength=4))
			row.append(Preformatted('Importe Total', styles['stileLeyenda'], maxLineLength=13))
			row.append(Preformatted('Descuentos', styles['stileLeyenda'], maxLineLength=10))
			line.append(row)
		row = []
		row.append(Preformatted(str(linea['1']), styles['stileVal'], maxLineLength=25))
		row.append(Preformatted(str(linea['0']), styles['stileVal'], maxLineLength=12))
		row.append(Preformatted(str(linea['7']), styles['stileVal'], maxLineLength=14))
		row.append(Preformatted(str(linea['8']), styles['stileVal'], maxLineLength=16))
		row.append(Preformatted(str(linea['9']), styles['stileVal'], maxLineLength=16))
		row.append(Preformatted(str(linea['10']), styles['stileVal'], maxLineLength=16))
		row.append(Preformatted(str(linea['11']), styles['stileVal'], maxLineLength=16))
		row.append(Preformatted(str(linea['12']), styles['stileVal'], maxLineLength=16))
		line.append(row)
		row = []


	table = Table(line)
	table.rowheights = 1
	table.hAlign = TA_LEFT
	story.append(table)

	# CONSTRUIMOS EL PDF
	#==================
	doc = docTemplate()  # Nombre del archivo ... 
	doc.build(story)
	with open(files, "rb") as image_file:  # Transforma PDF en binario base64
	   encoded_string = base64.b64encode(image_file.read())
	os.remove(files)  # Elimina PDF fisico.
	return encoded_string