Beispiel #1
0
 def new_title_bar(self, title, color=None):
     """Return an array of Pdf Objects which constitute a Header"""
     # Build a title bar for top of page
     w, t, c = '100%', 2, color or HexColor('#404040')
     title = '<b>{0}</b>'.format(title)
     if 'TitleBar' not in self.stylesheet:
         tb = ParagraphStyle('TitleBar',
                             parent=self.stylesheet['Normal'],
                             fontName='Helvetica-Bold',
                             fontSize=10,
                             leading=10,
                             alignment=TA_CENTER)
         self.stylesheet.add(tb)
     return [
         HRFlowable(width=w,
                    thickness=t,
                    color=c,
                    spaceAfter=2,
                    vAlign='MIDDLE',
                    lineCap='square'),
         self.new_paragraph(title, 'TitleBar'),
         HRFlowable(width=w,
                    thickness=t,
                    color=c,
                    spaceBefore=2,
                    vAlign='MIDDLE',
                    lineCap='square')
     ]
 def new_title_bar(self, title, color=None):
     """Return an array of Pdf Objects which constitute a Header"""
     # Build a title bar for top of page
     w, t, c = "100%", 2, color or HexColor("#404040")
     title = "<b>{0}</b>".format(title)
     if "TitleBar" not in self.stylesheet:
         tb = ParagraphStyle(
             "TitleBar",
             parent=self.stylesheet["Normal"],
             fontName="Helvetica-Bold",
             fontSize=10,
             leading=10,
             alignment=TA_CENTER,
         )
         self.stylesheet.add(tb)
     return [
         HRFlowable(
             width=w,
             thickness=t,
             color=c,
             spaceAfter=2,
             vAlign="MIDDLE",
             lineCap="square",
         ),
         self.new_paragraph(title, "TitleBar"),
         HRFlowable(
             width=w,
             thickness=t,
             color=c,
             spaceBefore=2,
             vAlign="MIDDLE",
             lineCap="square",
         ),
     ]
Beispiel #3
0
    def A4_page_foot(self, canvas, doc):
        canvas.saveState()

        # qrcode
        qrcode = self.codeimg
        qrcode.wrap(3*cm, 3*cm)
        qrcode.drawOn(canvas, doc.width, 1.5*cm)
        # ticket order
        if self.order:
            pr = Paragraph(_('ORDER: %s') % self.order, self.styleL)
            pr.wrap(doc.width, 1*cm)
            pr.drawOn(canvas, doc.leftMargin, 1.5*cm)
        # line
        hr = HRFlowable(width="100%", thickness=0.25, hAlign='CENTER',
                        color=colors.black, vAlign='BOTTOM', dash=None,
                        spaceAfter=5)
        hr.wrap(doc.width, 1*cm)
        hr.drawOn(canvas, doc.leftMargin, 1.5*cm)
        # ticket window code
        pr = Paragraph(self.wcode, self.styleL)
        pr.wrap(doc.width, 1*cm)
        pr.drawOn(canvas, doc.leftMargin, 1.0*cm)
        # code
        pr = Paragraph(self.code, self.styleL)
        pr.wrap(doc.width, 1*cm)
        pr.drawOn(canvas, doc.width, 1.0*cm)

        canvas.restoreState()
Beispiel #4
0
def title_bar(pdf, title):
    # Build a title bar for top of page
#    w, t, c = '100%', 2, HexColor('#404040')
    w, t, c = '100%', 1.5, HexColor('#597b7c')
    title = '<b>{0}</b>'.format(title)    
    return [HRFlowable(width=w, thickness=t, color=c, spaceAfter=5, vAlign='MIDDLE', lineCap='square'),
            pdf.new_paragraph(title, 'TitleBar'),
            HRFlowable(width=w, thickness=t, color=c, spaceBefore=5, vAlign='MIDDLE', lineCap='square')]
Beispiel #5
0
 def draw(self):
     HRFlowable.draw(self)
     canv = self.canv
     canv.saveState()
     canv.setFont(*self.font)
     canv.setFillColor(self.color)
     # Move up by the font height plus half the linewidth, back down by 1
     canv.drawString(0, -1 * (self.font[1] + (self.lineWidth // 2) - 1),
                     self.sig_title)
     canv.restoreState()
Beispiel #6
0
 def pagina_mejoras(self):
     self.titulo = 'Observaciones y mejoras'
     self.elements.append(
         Paragraph('Observaciones y mejoras', self.stylesheet['titulo']))
     self.elements.append(
         Paragraph(
             '<para align="center"><i>Espacio para anotar lo que pienses que no funciona bien o que se puede mejorar.</i></para>',
             self.stylesheet['Normal']))
     self.elements.append(HRFlowable())
     self.elements.append(Spacer(10, 36))
     for x in range(18):
         self.elements.append(HRFlowable())
         self.elements.append(Spacer(10, 24))
     self.elements.pop()
Beispiel #7
0
def previous_doc_refferal_result(value, fwb):
    try:
        value = json.loads(value)
    except:
        return fwb

    if not value:
        return fwb
    pdfmetrics.registerFont(TTFont('PTAstraSerifBold', os.path.join(FONTS_FOLDER, 'PTAstraSerif-Bold.ttf')))
    styleSheet = getSampleStyleSheet()
    style = styleSheet["Normal"]
    style.fontName = "FreeSans"
    style.fontSize = 8
    style.alignment = TA_JUSTIFY
    style.spaceAfter = 0.1 * mm

    styleLeftIndent = deepcopy(style)
    styleLeftIndent.leftIndent = 12 * mm

    styleBold = deepcopy(style)
    styleBold.fontName = 'FreeSansBold'
    space_symbol = '&nbsp;'
    for data in value:
        fwb.append(Paragraph(f"{data.get('date', '')} {5 * space_symbol} {data.get('researchTitle', '')} {5 * space_symbol} {data.get('docConfirm', '')}", styleBold))
        fwb.append(Paragraph(f"{text_to_bold(data.get('value', ''))}", styleLeftIndent))
        fwb.append(HRFlowable(width=180 * mm, spaceAfter=0 * mm, spaceBefore=0.1 * mm, color=colors.black))
        fwb.append(Spacer(1, 2 * mm))

    return fwb
Beispiel #8
0
 def generate(self):
     content = [
         self._header_table(),
         Spacer(0, inch * 0.1),
         HRFlowable(width='100%', color=black),
         HRFlowable(width='100%', color=black),
         Spacer(0, inch * 0.1),
         self._entry_table(),
         Spacer(0, inch * 0.1),
         HRFlowable(width='100%', color=black),
         Spacer(0, inch * 0.1),
         self._total_table(),
     ]
     self._doc.build(content,
                     onFirstPage=self._draw_page,
                     onLaterPages=self._draw_page)
Beispiel #9
0
 def start(self, c):
     c.addPara()
     c.addStory(
         HRFlowable(color=self.attr.color,
                    thickness=self.attr.size,
                    width=self.attr.get('width', "100%") or "100%",
                    spaceBefore=c.frag.spaceBefore,
                    spaceAfter=c.frag.spaceAfter))
Beispiel #10
0
    def _addHeader(self):
        """ Header elements for receipt """

        h1 = Paragraph("<b>{}</b>".format(self.rentalInfo['propertyName']),
                       self.style['receiptTop'])
        h2 = Paragraph("Rental Reciept for {}".format(self.month.capitalize()),
                       self.style['receiptContent'])
        hr = HRFlowable(width="100%")
        return [h1, h2, Spacer(1, 4), hr, Spacer(1, 10)]
def _make_line():
    return HRFlowable(width="80%",
                      thickness=1,
                      lineCap='round',
                      spaceBefore=1,
                      spaceAfter=2,
                      hAlign='CENTER',
                      vAlign='BOTTOM',
                      dash=None)
Beispiel #12
0
def addSubtitle(text):  # Subsection Title
    doc.append(Spacer(1, 10))
    doc.append(HRFlowable(width='100%', color=colors.ReportLabFidBlue))
    doc.append(Spacer(1, 10))
    doc.append(
        Paragraph(
            text,
            ParagraphStyle(name='subtitle',
                           fontSize=15,
                           fontName='Times-Roman')))
    doc.append(Spacer(1, 15))
Beispiel #13
0
    def _addFooter(self, image_fd):
        """ Footer elements for receipt """

        footer = self._makeParagraph(
            "For all questions contact {} at {}".format(
                self.rentalInfo['landlord'], self.rentalInfo['phone']),
            'receiptContent')
        im = Image(image_fd, 1 * inch, 0.45 * inch)
        im.hAlign = 'LEFT'
        hr = HRFlowable(width="100%")
        return [im, Spacer(1, 4), hr, Spacer(1, 8), footer]
    def _get_elements(self):
        elements = []
        table_style_data = [('TEXTCOLOR', (0, 0), (-1, -1), colors.black),
                            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                            ('LINEBELOW', (0, 0), (-1, -1), 1, colors.black),
                            ('BOX', (0, 0), (-1, -1), 1, colors.black),
                            ('BOX', (0, 0), (0, -1), 1, colors.black),
                            ('BACKGROUND', (0, 0), (1, 0), colors.lightblue)]

        table_style = TableStyle(table_style_data)
        table_style.spaceAfter = 25

        heading_style = TableStyle(table_style_data)
        heading_style.spaceAfter = 25
        heading_style.add('SPAN', (0, 0), (1, 0))
        heading_style.add('ALIGN', (0, 0), (1, 0), 'CENTER')

        localised_date_str = self._get_localised_date(self.response['submitted_at'])

        heading_data = self.style.get_heading_data(self.survey['title'], self.response['collection']['instrument_id'],
                                                   self.response['metadata']['ru_ref'], localised_date_str)

        heading = Table(heading_data, style=heading_style, colWidths='*')

        elements.append(heading)

        for question_group in filter(lambda x: 'title' in x, self.survey['question_groups']):

            section_heading = True

            for question in filter(lambda x: 'text' in x, question_group['questions']):
                if question['question_id'] in self.response['data']:
                    try:
                        answer = str(self.response['data'][question['question_id']])
                    except KeyError:
                        answer = ''

                    # Output the section header if we haven't already
                    # Checking here so that whole sections are suppressed
                    # if they have no answers.
                    if section_heading:
                        elements.append(HRFlowable(width="100%"))
                        elements.append(Paragraph(question_group['title'], self.style.style_sh))
                        section_heading = False

                    # Question not output if answer is empty
                    text = question.get("text")
                    if not text[0].isdigit():
                        text = " ".join((question.get("number", ""), text))
                    elements.append(Paragraph(text, self.style.style_n))
                    elements.append(Paragraph(answer, self.style.style_answer))

        return elements
Beispiel #15
0
 def start(self, c):
     c.addPara()
     # patch by Glutanimate to set HR color and height
     line_color = c.cssAttr.get('background') or c.cssAttr.get(
         'color') or self.attr.color
     thickness = c.cssAttr.get('height') or self.attr.size
     c.addStory(
         HRFlowable(color=line_color,
                    thickness=self.attr.size,
                    width=self.attr.get('width', "100%") or "100%",
                    spaceBefore=c.frag.spaceBefore,
                    spaceAfter=c.frag.spaceAfter))
Beispiel #16
0
 def title_bar(self, title):
     # Build a title bar for top of page
     w, t, c = "100%", 2, HexColor("#404040")
     title = "<b>{0}</b>".format(title)
     return [
         HRFlowable(
             width=w,
             thickness=t,
             color=c,
             spaceAfter=2,
             vAlign="MIDDLE",
             lineCap="square",
         ),
         self.pdf.new_paragraph(title, "TitleBar"),
         HRFlowable(
             width=w,
             thickness=t,
             color=c,
             spaceBefore=2,
             vAlign="MIDDLE",
             lineCap="square",
         ),
     ]
Beispiel #17
0
def param_list(param, width ,font_size=6, col_with_percent=0.618):
    title = param[0]
    value = param[1:]

    col_width = []
    current_len = 0
    for vs in zip(title, *tuple(value)):
        len_col = max([len(v) for v in vs]+[5])*font_size*col_with_percent
        current_len += len_col
        if current_len > width:
            break
        col_width.append(len_col)

    if len(col_width)<len(title):
        title = title[0:len(col_width)]
        value = [v[0:len(col_width)] for v in value]

    title_table = Table([title], colWidths=col_width, hAlign="LEFT")
    title_table.setStyle(TableStyle([
        ('FONTSIZE', (0, 0), (-1, -1), font_size),
        ('FACE', (0, 0), (-1, -1), 'hei'),
        ('TEXTCOLOR', (0, 0), (-1, 0), '#2992f1')
    ]))

    value_table = Table(value, colWidths=col_width, hAlign="LEFT")
    value_table.setStyle(TableStyle([
        ('FONTSIZE', (0, 0), (-1, -1), font_size),
        ('FACE', (0, 0), (-1, -1), 'song')
    ]))

    return [HRFlowable(width="100%", color="#d4dbe2", spaceBefore=1, spaceAfter=4),
            title_table,
            HRFlowable(width="100%", color="#d4dbe2", spaceBefore=2, spaceAfter=4),
            value_table,
            HRFlowable(width="100%", color="#d4dbe2", spaceBefore=2, spaceAfter=2),
            Spacer(6, 20)]
Beispiel #18
0
 def _section_doc_header(self):
     elems = list()
     elems.extend([
         Spacer(0, 2.5 * mm),
         Paragraph("<b>%s</b>" % _("text-001"), styles["doc-header"]),
         Spacer(0, 5.5 * mm),
     ])
     t1 = Table([[
         Paragraph(_("text-002"), styles["main-narrow"]),
     ], [
         Paragraph("VS.", styles["main-narrow"]),
     ], [
         Paragraph(self.data["field-001"], styles["field-value"]),
     ],
                 [
                     HRFlowable(width=66 * mm,
                                thickness=0.2 * mm,
                                lineCap='round',
                                color="black")
                 ]],
                style=extend_table_style(styles["main-table"], [
                    ("LEFTPADDING", (0, 1), (-1, 1), 16.5 * mm),
                    ("VALIGN", (0, 2), (-1, 2), "MIDDLE"),
                ]),
                rowHeights=[5 * mm, 5 * mm, 9.75 * mm, 0.5 * mm])
     t2 = Table(
         [[
             Paragraph(_("text-003"), styles["main-narrow-right"]),
             Paragraph(self.data["field-002"], styles["field-value"]),
         ],
          [
              Paragraph(_("text-004"), styles["main-right"]),
              Paragraph(self.data["field-003"], styles["field-value"]),
          ]],
         style=extend_table_style(styles["main-table"], [
             ("LINEBELOW", (1, 0), (1, -1), 0.2 * mm, "black"),
             ("RIGHTPADDING", (0, 0), (0, -1), 2 * mm),
         ]),
         rowHeights=5 * mm)
     elems.append(
         Table(
             [[t1, t2]],
             style=extend_table_style(styles["main-table"], [
                 ("VALIGN", (0, 0), (-1, -1), "TOP"),
             ]),
         ))
     return elems
Beispiel #19
0
def draw_receipt(response, context):
    doc = SimpleDocTemplate(response, topMargin=5.6*cm, leftMargin=0.5*cm)
    context['doc_type'] = 'Resit'
    doc.context = context
    styles = getSampleStyleSheet()
    P = lambda s: Paragraph(s, styles['Normal'])
    stories = []

    payment = context['payment']
    orderitem_list = payment.order.orderitem_set.all()
    stories.append(draw_order_items(doc, orderitem_list))
    stories.append(P('Bayaran: RM%.2f - Terima Kasih.' % payment.amount))
    stories.append(Spacer(1, 1*cm))
    stories.append(P('Tandatangan petugas'))
    stories.append(Spacer(1, 0.5*cm))
    stories.append(HRFlowable(width='22%', hAlign='LEFT', color=colors.black))
    doc.build(stories, onFirstPage=draw_header, onLaterPages=draw_header, canvasmaker=NumberedCanvas)
Beispiel #20
0
def draw_invoice(response, context):
    order = context['order']
    customer = order.customer

    doc = SimpleDocTemplate(response, topMargin=5.6*cm, leftMargin=0.5*cm)
    context['doc_type'] = 'Invois'
    doc.context = context
    styles = getSampleStyleSheet()
    P = lambda s: Paragraph(s, styles['Normal'])
    stories = []

    stories.append(draw_order_items(doc, order.orderitem_set.all()))
    stories.append(Spacer(1, 1*cm))
    stories.append(P('Tandatangan petugas'))
    stories.append(Spacer(1, 0.5*cm))
    stories.append(HRFlowable(width='22%', hAlign='LEFT', color=colors.black))
    doc.build(stories, onFirstPage=draw_header, onLaterPages=draw_header, canvasmaker=NumberedCanvas)
Beispiel #21
0
def create_proposal_sheets():
    """
    Create the bits of papers for constructing an initial schedule.
    """
    file_path = str(file_directory.parent / 'proposal_sheets.pdf')
    style_sheet = getSampleStyleSheet()['BodyText']
    style_sheet.fontSize = 18
    style_sheet.leading = 22
    document = SimpleDocTemplate(file_path,
                                 pagesize=A4,
                                 rightMargin=30,
                                 leftMargin=30,
                                 topMargin=10,
                                 bottomMargin=30)
    elements = []
    for p in Proposal.query.all():
        scores = tuple(score.score for score in p.scores if score.score != 0)
        table = Table([
            [Paragraph(p.title, style_sheet), p.session_type],
            [
                ', '.join('{} {}'.format(pp.first_name, pp.last_name)
                          for pp in p.presenters),
                ', '.join(str(score.score) for score in p.scores) +
                ' — {:.2f}, {}'.format(mean(scores), median(scores))
                if len(scores) > 0 else ''
            ],
        ],
                      colWidths=(380, 180),
                      spaceAfter=64)
        table.setStyle(TableStyle([
            ('FONTSIZE', (0, 0), (-1, -1), 12),
        ]))
        elements.append(
            HRFlowable(width="100%",
                       thickness=1,
                       lineCap='round',
                       color=colors.darkgrey,
                       spaceBefore=1,
                       spaceAfter=1,
                       hAlign='CENTER',
                       vAlign='BOTTOM',
                       dash=None))
        elements.append(KeepTogether(table))
    document.build(elements)
Beispiel #22
0
 def _page_2(self):
     table_width = 68.75 * mm
     border_outer = 0.25 * mm
     border_inner = 1.05 * mm
     addr_parts = self.data["defendant_address"].split(",")
     ps = extend_style(styles["rc-bw-main"], fontSize=12, leading=12, alignment=TA_CENTER)
     elems = [
         Spacer(0, 0.75 * mm),
         Paragraph("<b>BENCH WARRANT</b>", extend_style(styles["rc-bw-title"], fontSize=14, leading=14)),
         Spacer(0, 18.5 * mm),
         HRFlowable(width="100%", thickness=0.1 * mm, lineCap="butt", color="black"),
         Spacer(0, 1.6 * mm),
         Paragraph("<b>MAGISTRATE COURT</b>", extend_style(ps, fontSize=11, leading=11)),
         Spacer(0, 19 * mm),
         HRFlowable(width="100%", thickness=0.75 * mm, lineCap="butt", color="black"),
         Spacer(0, 1.6 * mm),
         Paragraph("<b>ROCKDALE COUNTY</b>", ps),
         Spacer(0, 6 * mm),
         Paragraph("<b>VS.</b>", ps),
         Spacer(0, 0.75 * mm),
         Paragraph("<b><u>%s</u></b>" % self.data["defendant_name"], ps),
         Spacer(0, 8.25 * mm),
         HRFlowable(width="100%", thickness=0.1 * mm, lineCap="butt", color="black"),
         Spacer(0, 6.6 * mm),
         Paragraph(
             "<b><u>%s<br />%s, %s</u></b>" % (addr_parts[0], addr_parts[1], addr_parts[2]),
             extend_style(ps, fontSize=12, leading=14.5)
         ),
         Spacer(0, 21 * mm),
         HRFlowable(width="100%", thickness=0.1 * mm, lineCap="butt", color="black"),
         Spacer(0, 4 * mm),
         HRFlowable(width="100%", thickness=0.1 * mm, lineCap="butt", color="black"),
         Spacer(0, 4.75 * mm),
         HRFlowable(width="100%", thickness=0.75 * mm, lineCap="butt", color="black"),
         Spacer(0, 1.9 * mm),
         Paragraph("<b>Sheriff take good bond in the sum of</b>", extend_style(ps, fontSize=11, leading=11)),
         Spacer(0, 5.5 * mm),
         Paragraph("<b>${:,.2f}</b>".format(self.data["bond_amount"]), extend_style(ps, fontSize=12, leading=12)),
         Spacer(0, 4 * mm),
         HRFlowable(width="100%", thickness=0.1 * mm, lineCap="butt", color="black"),
         Spacer(0, 28 * mm),
     ]
     return self._create_border_table(elems, table_width, border_inner=border_inner, border_outer=border_outer)
def myFirstPage(canvas, doc):
    canvas.saveState()
    canvas.setFont('Times-Bold', 16)
    canvas.drawCentredString(PAGE_WIDTH / 2.0, PAGE_HEIGHT - 108, title)
    canvas.setFont('Times-Roman', 9)
    canvas.drawString(inch, 0.75 * inch, "Page %d - %s" % (doc.page, title))

    frame_width = PAGE_WIDTH - 200
    hr = HRFlowable()
    space = Spacer(frame_width, 20)
    style = styles["Normal"]
    qr_info = """<para rightIndent=10 leftIndent=20 alignment=right>This document is signed with the QR code shown on the right. Validate it using a Barcode Scanner."""
    par = Paragraph(qr_info, style)
    im = Image("qrcode.png", 101, 101)
    pandi = ParagraphAndImage(par, im, xpad=3, ypad=30, side='right')

    frame = Frame(100, 0, frame_width, 200, showBoundary=1)
    frame.add(hr, canvas)
    frame.add(space, canvas)
    frame.add(pandi, canvas)
    canvas.restoreState()
    def serve_pdf(self, request, _suffix):
        """
        Builds and serves a PDF document containing user's freeform answers.
        """
        font_path = self._expand_static_url(
            self.custom_font, absolute=True) if self.custom_font else None
        styles = get_style_sheet(font_url=font_path)
        pdf_buffer = BytesIO()

        report_header_name = self.pdf_report_title or self._get_course_name()
        document = SimpleDocTemplate(pdf_buffer,
                                     pagesize=pagesizes.letter,
                                     title=report_header_name)
        story = [
            Paragraph(report_header_name, styles["Title"]),
        ]

        answer_sections = self.list_user_pb_answers_by_section()
        for section in answer_sections:
            story.append(Spacer(0, 16))
            story.append(Paragraph(section["name"], styles["h1"]))
            for question in section["questions"]:
                story.append(Paragraph(question["question"], styles["h2"]))
                story.append(Paragraph(question["answer"], styles["Normal"]))
                story.append(
                    HRFlowable(color=Color(0, 0, 0, 0.1),
                               width='100%',
                               spaceBefore=5,
                               spaceAfter=10))

        document.build(story)
        pdf_buffer.seek(0)
        pdf = pdf_buffer.read()

        response = webob.Response(
            body=pdf,
            content_type='application/pdf',
        )

        return response
Beispiel #25
0
 def hr_mini(self):
     self.story.append(
         HRFlowable(width='100%', thickness=0.2, color=colors.grey))
Beispiel #26
0
    def getContent(self, item, bump_headings=False):
        pdf = []
        if isinstance(item, Tag):
            className=item.get('class', '').split()
            item_type = item.name
            if item_type in ['h2', 'h3', 'h4', 'h5', 'h6']:
                item_style = self.tag_to_style.get(item_type)
                h = Paragraph(self.getItemText(item), self.styles[item_style])
                h.keepWithNext = True
                pdf.append(h)
                if item_type == 'h2' and not bump_headings:
                    hr = HRFlowable(width='100%', thickness=0.25, spaceBefore=2, spaceAfter=4, color=self.styles[item_style].textColor)
                    hr.keepWithNext = True
                    pdf.append(hr)
            elif item_type in ['table']:
                (table_data, table_style, caption) = self.getTableData(item)
                table = Table(table_data)
                table.setStyle(table_style)
                table.hAlign = 'LEFT'
                table.spaceBefore = 10
                table.spaceAfter = 10

                if caption:
                    caption_el = Paragraph(self.getInlineContents(caption), self.styles['Discreet'])
                    pdf.append(KeepTogether([table, caption_el]))
                else:
                    pdf.append(table)

            elif item_type in ['ul']:
                for i in item.findAll('li'):
                    pdf.append(Paragraph('<bullet>&bull;</bullet>%s' % self.getInlineContents(i), self.styles['BulletList']))
            elif item_type in ['ol']:
                # Sequences were incrementing based on previous PDF generations.
                # Including explicit ID and reset
                li_uuid = uuid1().hex
                for i in item.findAll('li'):
                    pdf.append(Paragraph('<seq id="%s" />. %s' % (li_uuid, self.getInlineContents(i)), self.styles['BulletList']))
                pdf.append(Paragraph('<seqReset id="%s" />' % li_uuid, self.styles['Normal']))
            elif item_type in ['p'] or (item_type in ['div'] and 'captionedImage' in className or 'callout' in className or 'pullquote' in className):

                has_image = False

                # Pull images out of items and add before
                for img in item.findAll('img'):
                    img.extract()
                    src = img['src'].replace(self.site.absolute_url(), '')

                    if src.startswith('/'):
                        src = src.replace('/', '', 1)

                    img_obj = self.getPloneImageObject(src)

                    if img_obj:
                        has_image = True

                        img_data = img_obj.image.data

                        try:
                            pil_image = self.getImageFromData(img_data)
                        except IOError:
                            pass
                        else:
                            pdf_image = self.getImage(pil_image)
                            pdf.append(pdf_image)

                # If we had an image, and the next paragraph has the
                # 'discreet' class (is a caption) then keep them together
                if has_image:
                    s = item.findNextSiblings()
                    if s and 'discreet' in s[0].get('class', ''):
                        pdf[-1].keepWithNext = True

                # Get paragraph contents
                p_contents = self.getInlineContents(item)

                # Don't add anything if no contents.
                if not p_contents:
                    pass
                elif 'callout' in className or 'pullquote' in className:
                    pdf.append(Paragraph(p_contents, self.styles['Callout']))
                elif 'discreet' in className or 'captionedImage' in className:
                    if len(pdf) and isinstance(pdf[-1], Image):
                        pdf[-1].keepWithNext = True
                    pdf.append(Paragraph(p_contents, self.styles['Discreet']))
                else:
                    pdf.append(Paragraph(p_contents, self.styles["Normal"]))

            elif item_type in ['div']:
                for i in item.contents:
                    pdf.extend(self.getContent(i))

            elif item_type == 'blockquote':
                pdf.append(Paragraph(self.getItemText(item), self.styles['Blockquote']))
            else:
                pdf.append(Paragraph(self.getItemText(item), self.styles["Normal"]))
        elif isinstance(item, NavigableString):
            if item.strip():
                pdf.append(Paragraph(item, self.styles["Normal"]))
        return pdf
    def make_pdf(self, data, start_date, end_date, filename, emails):

        width, height = A4
        styles = getSampleStyleSheet()
        styleN = styles["BodyText"]
        styleN.alignment = TA_LEFT
        styleN.fontName = 'Helvetica'
        styleN.textColor = colors.black
        styleBH = styles["Heading3"]
        styleBH.alignment = TA_CENTER
        styleBH.fontName = 'Helvetica'
        styleBH.textColor = colors.darkslategray
        styleTH = styles["Heading1"]
        styleTH.alignment = TA_CENTER
        styleTH.fontName = 'Helvetica'
        styleTH.textColor = colors.darkslateblue
        styleGH = styles["Heading2"]
        styleGH.alignment = TA_CENTER
        styleGH.fontName = 'Helvetica'
        styleGH.textColor = colors.darkslategray
        #styleGH.backColor = colors.lightgrey

        styleNC = styles["BodyText"]
        #styleNC.alignment = TA_CENTER
        styleNC.fontName = 'Helvetica'
   

        def coord(x, y, unit=1):
            x, y = x * unit, height -  y * unit
            return x, y

        def style_row(row_array, style):
            styled_array = []
            for each in row_array:
                styled_array.extend([Paragraph(str(each),style)])
            return styled_array
       
            
        c = canvas.Canvas(os.path.join(settings.PDF_REPORTS_DIR, 'gka_sms/')+filename+".pdf", pagesize=A4)
        #logo
        logo_image = Image("%s/images/akshara_logo.jpg" % settings.STATICFILES_DIRS) 
        logo_image.drawOn(c, *coord(14, 3, cm))
        #HR
        hr = HRFlowable(width="80%", thickness=1, lineCap='round', color=colors.lightgrey, spaceBefore=1, spaceAfter=1, hAlign='CENTER', vAlign='BOTTOM', dash=None)
        hr.wrapOn(c, width, height)
        hr.drawOn(c, *coord(1.8, 3.2, cm))
        #Headings
        header = Paragraph('GKA SMS Summary<br/><hr/>', styleTH)
        header.wrapOn(c, width, height)
        header.drawOn(c, *coord(0, 4, cm))
        #Date Range
        date_range = Paragraph("From " + start_date.strftime("%d %b, %Y") + " to " + end_date.strftime("%d %b, %Y"), styleBH)
        date_range.wrapOn(c, width, height)
        date_range.drawOn(c, *coord(0, 4.5, cm))
        #Details
        styled_data = [style_row(data[0],styleGH)]
        for row in data[1:4]:
            styled_data.append(style_row(row,styleN))

        table_header = Table(styled_data, colWidths=[7 * cm,
                                       5* cm, 5 * cm])
        table_header.setStyle(TableStyle([
                       ('INNERGRID', (0,0), (-1,-1), 0.25, colors.lightgrey),
                       ('BOX', (0,0), (-1,-1), 0.25, colors.lightgrey),
                       ('LINEBELOW', (0,0), (2, 0), 1.0, colors.darkgrey),
                       ('LINEBELOW', (0,3), (2, 3), 1.0, colors.darkgrey),
                       
                    ]))
        table_header.wrapOn(c, width, height)
        table_header.drawOn(c, *coord(1.8, 9, cm))
        #Questions
        styled_data =[style_row(['Questions','Yes','No','Yes','No'],styleBH)] 
        for row in data[4:len(data)]:
            styled_data.append(style_row(row,styleN))
        
        table = Table(styled_data, colWidths=[7 * cm,
                                       2.5 * cm, 2.5 * cm,
                                       2.5 * cm, 2.5 * cm])
        table.setStyle(TableStyle([
                       ('INNERGRID', (0,0), (-1,-1), 0.25, colors.lightgrey),
                       ('BOX', (0,0), (-1,-1), 0.25, colors.lightgrey),
                       #('LINEBELOW', (0,0), (2, 0), 1.0, colors.green),
                       
                    ]))
        table.wrapOn(c, width, height)
        table.drawOn(c, *coord(1.8, 17.5, cm))
        #Footer
        #HR
        hr = HRFlowable(width="80%", thickness=1, lineCap='round', color=colors.lightgrey, spaceBefore=1, spaceAfter=1, hAlign='CENTER', vAlign='BOTTOM', dash=None)
        hr.wrapOn(c, width, height)
        hr.drawOn(c, *coord(1.8, 27, cm))
        #Disclaimer
        klp_text = Paragraph("This report has been generated by Karnataka Learning Partnership(www.klp.org.in/gka) for Akshara Foundation.",styleN)
        klp_text.wrapOn(c, width, height)
        klp_text.drawOn(c, *coord(1.8, 27.5, cm))
        
        c.save()
        self.send_email(start_date.strftime("%d/%m/%Y") + " to " + end_date.strftime("%d/%m/%Y"),filename, emails)
Beispiel #28
0
 def hr(self):
     self.story.append(
         HRFlowable(width='100%', thickness=0.2, color=colors.black))
Beispiel #29
0
def birdcare_worksheet(request):

    try:

        styles = getSampleStyleSheet()
        styleN = styles['Normal']
        styleH = styles['Heading3']
        styleH2 = styles['Heading4']

        today = datetime.date.today()

        from birdlist.views.breeding.birdcare_main import get_checklist_information
        cage_list = get_checklist_information()

        title = "Birdcare Worksheet"
        author = 'Andreas Kotowicz'

        Story, buffer, doc, response = pdf_header(
            page_size=portrait(A4),
            filename="birdcare_worksheet.pdf",
            title=title,
            author=author)
        Story = add_title(title, Story, request, title_size=14)
        ''' calendar of this and previous month '''
        NOW = datetime.datetime.now()
        year = NOW.year
        month = NOW.month
        this_month = generate_calendar(year, month)

        prev_month, year = get_prev_month(month, year)
        prev = generate_calendar(year, prev_month)

        prev_month, year = get_prev_month(prev_month, year)
        prev2 = generate_calendar(year, prev_month)

        ts = TableStyle([
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
        ])

        data = [
            [[prev2], [prev], [this_month]],
        ]
        table = Table(data, (180, 180, 180), style=ts)
        Story.append(table)

        # add horizontal line
        Story.append(
            HRFlowable(width='100%',
                       thickness=2,
                       lineCap='round',
                       spaceBefore=0,
                       spaceAfter=0,
                       hAlign='CENTER',
                       vAlign='BOTTOM',
                       dash=None))
        ''' for each cage do: '''

        for i in cage_list:

            cage = i['cage']
            coupling = i['coupling']
            juveniles = i['juveniles']

            # first cage might have no coupling, because a new couple has to be
            # created, therefore we set reasonable defaults there.
            days_since_data = None
            transferred_to_string = ''
            juv_table = None

            header_string = cage.name

            # coupling in cage found
            if coupling:
                last_brood = coupling.get_last_brood()
                days_since_last_brood = ''
                if last_brood:
                    days_since_last_brood = last_brood.get_broods_birthday()
                    days_since_last_brood = today - days_since_last_brood
                    days_since_last_brood = days_since_last_brood.days.__str__(
                    )
                    days_since_data = True

                days_since_coupled = today - coupling.coupling_date
                days_since_coupled = days_since_coupled.days.__str__()

                comment = coupling.comment
                if comment:
                    comment = comment.replace('&', '&amp;')
                    comment = Paragraph(comment * 1, style)

                couple_separate = coupling.is_to_be_separated()
                couple_remove_nest = coupling.nest_has_to_be_removed()
                if couple_separate or couple_remove_nest:
                    header_string = header_string + '- Please '

                    if couple_remove_nest:
                        header_string = header_string + 'remove nest '

                    if couple_separate:
                        if couple_remove_nest:
                            header_string = header_string + 'and'
                        header_string = header_string + ' separate this couple'
                        transferred_to_string = 'transferred to:'

                # quite ugly because of duplicate code but I don't know python
                # enough to figure out how to only insert the part that's extra.
                if days_since_data:
                    couple = [
                        [
                            'father',
                            coupling.couple.get_male().name,
                            transferred_to_string, ''
                        ],
                        [
                            'mother',
                            coupling.couple.get_female().name,
                            transferred_to_string, ''
                        ],
                        ['coupling date', coupling.coupling_date],
                        ['# days coupled', days_since_coupled],
                        ['# days since\n last hatch', days_since_last_brood],
                        ['# broods',
                         coupling.get_number_of_broods()],
                        ['comment', comment],
                        ['Has white offspring? - Yes / No', ''],
                    ]
                else:
                    couple = [
                        [
                            'father',
                            coupling.couple.get_male().name,
                            transferred_to_string, ''
                        ],
                        [
                            'mother',
                            coupling.couple.get_female().name,
                            transferred_to_string, ''
                        ],
                        ['coupling date', coupling.coupling_date],
                        ['# days coupled', days_since_coupled],
                        ['comment', comment],
                        ['Has white offspring? - Yes / No', ''],
                    ]

            else:  # no coupling in cage
                couple = [['father:', 'taken from:'],
                          ['mother:', 'taken from:']]
                if cage.bird_set.count() == 0:
                    # cage is empty
                    header_string = header_string + ' - Please add new couple'
                else:
                    # sometimes, birds are found inside a breeding cage, show the list!
                    header_string = header_string + ' - Non empty breeding cage - Please check status'
                    juv_table = [[
                        'bird', 'dph (-)', 'renamed to', 'transferred to',
                        'sex(ed)'
                    ]]
                    juv_table = create_table_of_birds(juv_table,
                                                      cage.bird_set.all())

            # juveniles found in cage
            if juveniles:
                juv_table = [[
                    'juvenile', 'dph (-)', 'renamed to', 'transferred to',
                    'sex(ed)'
                ]]
                juv_table = create_table_of_birds(juv_table, juveniles)

            # table for newborns
            newborns = [['nbr newborns', 'first birthday', 'last birthday'],
                        ['# ', '', '']]
            ''' styles '''
            ts2 = TableStyle([
                ('LINEABOVE', (0, 0), (-1, 0), 2, colors.black),
                ('LINEBELOW', (0, 0), (-1, 0), 0.5, colors.black),
                ('LINEBELOW', (0, -1), (-1, -1), 0.5, colors.black),
                ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold', 8),
                ('FONT', (0, 1), (1, -1), 'Helvetica', 8),
                ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                ('ALIGN', (1, 1), (-1, -1), 'LEFT'),
            ])

            span_id = 4
            if days_since_data:
                span_id = 6

            ts3 = TableStyle([
                ('LINEABOVE', (0, 0), (-1, 0), 2, colors.black),
                ('LINEBELOW', (0, -1), (-1, -1), 2, colors.black),
                ('FONT', (0, 0), (0, -1), 'Helvetica-Bold', 7),
                ('VALIGN', (0, 1), (-1, -1), 'MIDDLE'),
                ('SPAN', (1, span_id), (3, span_id)),
                ('ALIGN', (1, 1), (-1, -1), 'LEFT'),
            ])

            if transferred_to_string.__len__() > 0:
                ts3.add('LINEBELOW', (2, 0), (3, 0), 0.5, colors.black)
                ts3.add('LINEBELOW', (2, 1), (3, 1), 0.5, colors.black)

            bst = TableStyle([
                ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ])
            ''' put together the tables '''
            if coupling and juveniles:
                table1 = Table(juv_table, (52, 43, 65, 60, 40), style=ts2)
                table2 = Table(couple, (60, 60, 60, 50), style=ts3)
                table3 = Table(newborns, (70, 95, 95), style=ts2)
                data = [
                    [[table2], [table1, blank_paragraph, table3]],
                ]

                table = Table(data, style=bst)

                paragraph = Paragraph(header_string, styleH)
                paragraph.keepWithNext = True
                Story.append(paragraph)
                Story.append(table)

            elif not coupling:

                ts1 = TableStyle([
                    ('LINEABOVE', (0, 0), (-1, 0), 2, colors.black),
                    ('LINEBELOW', (0, -1), (-1, -1), 2, colors.black),
                    ('FONT', (0, 0), (0, -1), 'Helvetica-Bold', 7),
                    ('FONT', (1, 0), (1, -1), 'Helvetica-Bold', 7),
                    ('VALIGN', (0, 1), (-1, -1), 'MIDDLE'),
                    ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                    ('ALIGN', (1, 1), (-1, -1), 'LEFT'),
                ])

                if juv_table == None:
                    # by default, a cage without a couple is empty
                    table2 = Table(couple, (140, 160), style=ts1)
                    data = [[table2]]
                    table = Table(data, style=bst)

                else:
                    # sometimes, birds are found inside a breeding cage, show the list!
                    table1 = Table(juv_table, (52, 43, 65, 60, 40), style=ts2)
                    table2 = Table(couple, (140, 160), style=ts1)
                    data = [
                        [[table2], [table1]],
                    ]
                    table = Table(data, style=bst)

                paragraph = Paragraph(header_string, styleH)
                paragraph.keepWithNext = True
                Story.append(paragraph)
                Story.append(table)

            elif coupling:

                ts1 = TableStyle([
                    ('LINEABOVE', (0, 0), (-1, 0), 2, colors.black),
                    ('LINEBELOW', (0, -1), (-1, -1), 2, colors.black),
                    ('FONT', (0, 0), (0, -1), 'Helvetica-Bold', 7),
                    ('VALIGN', (0, 1), (-1, -1), 'MIDDLE'),
                    ('ALIGN', (1, 1), (-1, -1), 'LEFT'),
                ])

                table1 = Paragraph("No previous juveniles", styleH2)
                table2 = Table(couple, (60, 60, 60, 50), style=ts3)
                table3 = Table(newborns, (70, 95, 95), style=ts2)
                data = [
                    [[table2], [table1, blank_paragraph, table3]],
                ]

                table = Table(data, style=bst)

                paragraph = Paragraph(header_string, styleH)
                paragraph.keepWithNext = True
                Story.append(paragraph)
                Story.append(table)

            #colwidths = (350, 250)
            #table = Table(data, colwidths, style=bst)

            # add space after table
            Story.append(Spacer(1, 15))
            # add horizontal line
            Story.append(
                HRFlowable(width='100%',
                           thickness=2,
                           lineCap='round',
                           spaceBefore=0,
                           spaceAfter=0,
                           hAlign='CENTER',
                           vAlign='BOTTOM',
                           dash=None))
            #table._argW[0]=100*mm
            #table._argW[1]=100*mm

        return pdf_close_and_return(doc, Story, buffer, response)

    except:
        return server_error(request)
Beispiel #30
0
    def make_pdf(self, data, start_date, end_date, filename, emails):

        width, height = A4
        styles = getSampleStyleSheet()
        styleN = styles["BodyText"]
        styleN.alignment = TA_LEFT
        styleN.fontName = 'Helvetica'
        styleN.textColor = colors.black
        styleBH = styles["Heading3"]
        styleBH.alignment = TA_CENTER
        styleBH.fontName = 'Helvetica'
        styleBH.textColor = colors.darkslategray
        styleTH = styles["Heading1"]
        styleTH.alignment = TA_CENTER
        styleTH.fontName = 'Helvetica'
        styleTH.textColor = colors.darkslateblue
        styleGH = styles["Heading2"]
        styleGH.alignment = TA_CENTER
        styleGH.fontName = 'Helvetica'
        styleGH.textColor = colors.darkslategray
        #styleGH.backColor = colors.lightgrey

        styleNC = styles["BodyText"]
        #styleNC.alignment = TA_CENTER
        styleNC.fontName = 'Helvetica'

        def coord(x, y, unit=1):
            x, y = x * unit, height - y * unit
            return x, y

        def style_row(row_array, style):
            styled_array = []
            for each in row_array:
                styled_array.extend([Paragraph(str(each), style)])
            return styled_array

        c = canvas.Canvas(os.path.join(settings.PDF_REPORTS_DIR, 'gka_sms/') +
                          filename + ".pdf",
                          pagesize=A4)
        #logo
        logo_image = Image("%s/images/akshara_logo.jpg" %
                           settings.STATICFILES_DIRS)
        logo_image.drawOn(c, *coord(14, 3, cm))
        #HR
        hr = HRFlowable(width="80%",
                        thickness=1,
                        lineCap='round',
                        color=colors.lightgrey,
                        spaceBefore=1,
                        spaceAfter=1,
                        hAlign='CENTER',
                        vAlign='BOTTOM',
                        dash=None)
        hr.wrapOn(c, width, height)
        hr.drawOn(c, *coord(1.8, 3.2, cm))
        #Headings
        header = Paragraph('GKA SMS Summary<br/><hr/>', styleTH)
        header.wrapOn(c, width, height)
        header.drawOn(c, *coord(0, 4, cm))
        #Date Range
        date_range = Paragraph(
            "From " + start_date.strftime("%d %b, %Y") + " to " +
            end_date.strftime("%d %b, %Y"), styleBH)
        date_range.wrapOn(c, width, height)
        date_range.drawOn(c, *coord(0, 4.5, cm))
        #Details
        styled_data = [style_row(data[0], styleGH)]
        for row in data[1:4]:
            styled_data.append(style_row(row, styleN))

        table_header = Table(styled_data, colWidths=[7 * cm, 5 * cm, 5 * cm])
        table_header.setStyle(
            TableStyle([
                ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.lightgrey),
                ('BOX', (0, 0), (-1, -1), 0.25, colors.lightgrey),
                ('LINEBELOW', (0, 0), (2, 0), 1.0, colors.darkgrey),
                ('LINEBELOW', (0, 3), (2, 3), 1.0, colors.darkgrey),
            ]))
        table_header.wrapOn(c, width, height)
        table_header.drawOn(c, *coord(1.8, 9, cm))
        #Questions
        styled_data = [
            style_row(['Questions', 'Yes', 'No', 'Yes', 'No'], styleBH)
        ]
        for row in data[4:len(data)]:
            styled_data.append(style_row(row, styleN))

        table = Table(
            styled_data,
            colWidths=[7 * cm, 2.5 * cm, 2.5 * cm, 2.5 * cm, 2.5 * cm])
        table.setStyle(
            TableStyle([
                ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.lightgrey),
                ('BOX', (0, 0), (-1, -1), 0.25, colors.lightgrey),
                #('LINEBELOW', (0,0), (2, 0), 1.0, colors.green),
            ]))
        table.wrapOn(c, width, height)
        table.drawOn(c, *coord(1.8, 17.5, cm))
        #Footer
        #HR
        hr = HRFlowable(width="80%",
                        thickness=1,
                        lineCap='round',
                        color=colors.lightgrey,
                        spaceBefore=1,
                        spaceAfter=1,
                        hAlign='CENTER',
                        vAlign='BOTTOM',
                        dash=None)
        hr.wrapOn(c, width, height)
        hr.drawOn(c, *coord(1.8, 27, cm))
        #Disclaimer
        klp_text = Paragraph(
            "This report has been generated by Karnataka Learning Partnership(www.klp.org.in/gka) for Akshara Foundation.",
            styleN)
        klp_text.wrapOn(c, width, height)
        klp_text.drawOn(c, *coord(1.8, 27.5, cm))

        c.save()
        self.send_email(
            start_date.strftime("%d/%m/%Y") + " to " +
            end_date.strftime("%d/%m/%Y"), filename, emails)
Beispiel #31
0
 def __init__(self, *args, **kwargs):
     self.sig_title = kwargs.pop('title', '(signature)')
     self.font = kwargs.pop('font', ('Helvetica-Oblique', 10))
     # reportlab is still old-style classes
     HRFlowable.__init__(self, **kwargs)
Beispiel #32
0
def first_title(text):
    return [BoxTitle(3, 10, text, 'hei', 12, '#2992F1'),
            HRFlowable(width="100%", color="#2992F1", spaceBefore=10, spaceAfter=5)]
Beispiel #33
0
def form_03(request_data):
    """
    Добровольное согласие на медицинское вмешательство
    --------------------------------------------------------------------------------------------------------------
    Приказ Министерства здравоохранения РФ от 20 декабря 2012 г. N 1177н
    "Об утверждении порядка дачи информированного добровольного согласия на медицинское вмешательство и
    отказа от медицинского вмешательства в отношении определенных видов медицинских вмешательств,
    форм информированного добровольного согласия на медицинское вмешательство и форм отказа
    от медицинского вмешательства" (с изменениями и дополнениями).

    Приказ Министерства здравоохранения и социального развития РФ от 23 апреля 2012 г. N 390н
   "Об утверждении Перечня определенных видов медицинских вмешательств, на которые граждане дают информированное добровольное
    согласие при выборе врача и медицинской организации для получения первичной медико-санитарной помощи
    :param request_date:
    :return:
    """

    ind_card = Card.objects.get(pk=request_data["card_pk"])
    # ind = Individual.objects.get(pk=request_data["individual"])
    ind = ind_card.individual
    ind_doc = Document.objects.filter(individual=ind, is_active=True)
    individual_age = ind.age()

    # Касьяненко
    # # передать законного представителья, если возраст меньше 15 лет, или имеется опекун, или доверенность
    # if request_data["agent_pk"]:
    #     ind_agent_card = Card.objects.get(pk=request_data["agent_pk"])
    #
    #
    # #Если пациенту меньше 15 лет у него д.б. законный прелстаитель
    # if individual_age < 15:
    #     patient_agent = ind_card.patient_agent
    #     ind_card = patient_agent
    #     ind = ind_card.individual
    #Касьяненко

    individual_fio = ind.fio()
    individual_date_born = ind.bd()


    if individual_age < 15:
        patient_agent = " Иванова Марья Ивановна"

    document_passport = "Паспорт РФ"
    documents = forms_func.get_all_doc(ind_doc)
    document_passport_num = documents['passport']['num']
    document_passport_serial = documents['passport']['serial']
    document_passport_date_start = documents['passport']['date_start']
    document_passport_issued = documents['passport']['issued']

    m=-1
    if ind_card.main_address:
        ind_address = ind_card.main_address
    else:
        m=0

    if m==0 and ind_card.fact_address:
        ind_address = ind_card.fact_address
    elif not ind_card.main_address:
        ind_address = "______________________________________________________________________"

    if sys.platform == 'win32':
        locale.setlocale(locale.LC_ALL, 'rus_rus')
    else:
        locale.setlocale(locale.LC_ALL, 'ru_RU.UTF-8')

    # Генерировать pdf-Лист на оплату
    pdfmetrics.registerFont(TTFont('PTAstraSerifBold', os.path.join(FONTS_FOLDER, 'PTAstraSerif-Bold.ttf')))
    pdfmetrics.registerFont(TTFont('PTAstraSerifReg', os.path.join(FONTS_FOLDER, 'PTAstraSerif-Regular.ttf')))

    buffer = BytesIO()
    doc = SimpleDocTemplate(buffer, pagesize=A4,
                            leftMargin=20 * mm,
                            rightMargin=5 * mm, topMargin=6 * mm,
                            bottomMargin=5 * mm, allowSplitting=1,
                            title="Форма {}".format("Лист на оплату"))
    width, height = portrait(A4)
    styleSheet = getSampleStyleSheet()
    style = styleSheet["Normal"]
    style.fontName = "PTAstraSerifReg"
    style.fontSize = 12
    style.leading = 14
    style.spaceAfter = 0 * mm
    style.alignment = TA_JUSTIFY
    style.firstLineIndent = 15

    styleBold = deepcopy(style)
    styleBold.fontName = "PTAstraSerifBold"

    styleCenter = deepcopy(style)
    styleCenter.alignment = TA_CENTER
    styleCenter.fontSize = 9
    styleCenter.leading = 10
    styleCenter.spaceAfter = 0 * mm

    styleCenterBold = deepcopy(styleBold)
    styleCenterBold.alignment = TA_CENTER
    styleCenterBold.firstLineIndent = 0
    styleCenterBold.fontSize = 12
    styleCenterBold.leading = 13
    styleCenterBold.face = 'PTAstraSerifBold'

    styleJustified = deepcopy(style)
    styleJustified.alignment = TA_JUSTIFY
    styleJustified.spaceAfter = 4.5 * mm
    styleJustified.fontSize = 12
    styleJustified.leading = 4.5 * mm

    objs = []

    objs = [
        Paragraph('Информированное добровольное согласие на виды медицинских вмешательств,<br/> включенные в Перечень определенных'
                  ' видов медицинских вмешательств,<br/> на которые граждане дают информированное добровольное согласие при '
                  'выборе врача и медицинской организации для получения первичной медико-санитарной помощи ', styleCenterBold),
        ]

    d = datetime.datetime.strptime(individual_date_born,'%d.%m.%Y').date()
    date_individual_born = pytils.dt.ru_strftime(u"\"%d\" %B %Y", inflected=True, date=d )

    objs.append(Spacer(1, 4.5 * mm))
    objs.append(Paragraph('Я, {}&nbsp; {} г. рождения, зарегистрированный по адресу:  {} '.
                          format(individual_fio,date_individual_born,ind_address),style))

    person_agent =''
    patient_agent =''
    if person_agent:
        patient_agent = "лицом, законным представителем которого я являюсь"
    else:
        patient_agent=''
    hospital_name = SettingManager.get("rmis_orgname")
    hospital_address = SettingManager.get("org_address")
    objs.append(Paragraph('даю информированное добровольное согласие на виды медицинских вмешательств, включенные в '
                          '\"Перечень\" определенных видов медицинских вмешательств, на которые граждане дают информированное '
                          'добровольное согласие при выборе врача и медицинской организации для получения первичной '
                          'медико-санитарной помощи, утвержденный  приказом  Министерства здравоохранения и социального развития '
                          'Российской Федерации от 23 апреля 2012 г. N 390н (зарегистрирован Министерством  юстиции '
                          'Российской Федерации 5 мая 2012 г. N 24082) (далее - \"Перечень\"), для  получения  первичной'
                          'медико-санитарной помощи {} в:<br/> {}'.format(patient_agent, hospital_name),style))

    ofname=''
    if ofname:
        doc_ofname = ofname
    else:
        doc_ofname = "________________________________________________________"

    objs.append(Paragraph('Медицинским работником {}'.format(doc_ofname),style))
    objs.append(Paragraph('в доступной для меня форме мне разъяснены цели, методы оказания медицинской помощи, связанный '
                          'с ними риск, возможные варианты медицинских вмешательств, их  последствия,  в  том  числе  '
                          'вероятность  развития  осложнений, а также предполагаемые  результаты оказания медицинской помощи. '
                          'Мне разъяснено, что я  имею  право  отказаться  от  одного  или  нескольких  видов  медицинских вмешательств,  '
                          'включенных в Перечень, или потребовать его (их) прекращения, за  исключением  случаев,  предусмотренных  '
                          'частью 9 статьи 20 Федерального закона  от 21 ноября 2011 г. N 323-ФЗ "Об основах охраны здоровья '
                          'граждан в Российской  Федерации"  (Собрание  законодательства  Российской  Федерации, 2011, '
                          'N 48, ст. 6724; 2012, N 26, ст. 3442, 3446).  ', style))
    if person_agent:
        patient_agent = 'лица,  законным представителем которого я являюсь (ненужное зачеркнуть)'
    else:
        patient_agent='моего здоровья'



    objs.append(Paragraph('Сведения  о  выбранных  мною  лицах, которым в соответствии с пунктом 5 части  5  статьи  19 '
                          'Федерального закона от 21 ноября 2011 г. N 323-ФЗ "Об основах охраны здоровья граждан в '
                          'Российской Федерации" может быть передана информация  о состоянии {}'.format(patient_agent), style))

    styleFCenter = deepcopy(style)
    styleFCenter.alignment = TA_CENTER

    styleBottom = deepcopy(style)
    styleBottom.fontSize = 8

    space_symbol = '&nbsp;'

    sign_fio_person = '(Ф.И.О .гражданина, контактный телефон)'
    sign_patient_agent = '(Ф.И.О. гражданина или законного представителя гражданина)'
    sign_fio_doc = '(Ф.И.О. медицинского работника)'

    objs.append(Spacer(1, 9 * mm))
    objs.append(Paragraph('', styleFCenter))
    objs.append(HRFlowable(width= 190 * mm, spaceAfter=0.3 * mm, spaceBefore=0.5 * mm, color=colors.black))
    objs.append(Paragraph('{} {}'.format(73 * space_symbol, sign_fio_person), styleBottom))

    objs.append(Spacer(1, 3 * mm))
    objs.append(Paragraph('{}'.format(individual_fio), styleFCenter))
    objs.append(HRFlowable(width=190 * mm, spaceAfter=0.3 * mm, spaceBefore=0.5 * mm, color=colors.black))
    objs.append(Paragraph('{} (подпись) {} {}'.format(16 * space_symbol, 38 * space_symbol, sign_patient_agent), styleBottom))

    objs.append(Spacer(1, 3 * mm))
    objs.append(Paragraph('{}'.format(space_symbol), styleFCenter))
    objs.append(HRFlowable(width=190 * mm, spaceAfter=0.3 * mm, spaceBefore=0.5 * mm, color=colors.black))
    objs.append(Paragraph('{} (подпись) {} {}'.format(16 * space_symbol, 38 * space_symbol, sign_fio_doc), styleBottom))

    date_now = pytils.dt.ru_strftime(u"%d %B %Y", inflected=True, date=datetime.datetime.now())
    objs.append(Spacer(1, 5 * mm))
    objs.append(Paragraph('{} г.'.format(date_now), style))
    objs.append(HRFlowable(width=46 * mm, spaceAfter=0.3 * mm, spaceBefore=0.5 * mm, color=colors.black, hAlign=TA_LEFT))
    objs.append(Paragraph('(дата оформления)', styleBottom))


    if document_passport_issued:
        passport_who_give = document_passport_issued
    else:
        passport_who_give = "______________________________________________________________________"



    doc.build(objs)
    pdf = buffer.getvalue()
    buffer.close()
    return pdf
Beispiel #34
0
def createStandardCoverPage(page_size=PAGE_SIZE_LETTER,
                            total_pages=1,
                            recipient_name='',
                            recipient_phone='',
                            recipient_fax='',
                            sender_name='',
                            sender_phone='',
                            sender_fax='',
                            sender_email='',
                            regarding='',
                            message='',
                            preserve_formatting=False,
                            output=None):

    s = getSampleStyleSheet()

    story = []

    #print prop.locale
    #TTFSearchPath.append('/usr/share/fonts/truetype/arphic')
    #pdfmetrics.registerFont(TTFont('UMing', 'uming.ttf'))

    ps = ParagraphStyle(
        name="title",
        parent=None,
        fontName='helvetica-bold',
        #fontName='STSong-Light',
        #fontName = 'UMing',
        fontSize=72,
    )

    story.append(Paragraph("FAX", ps))

    story.append(Spacer(1, inch))

    ps = ParagraphStyle(
        name='normal',
        fontName='Times-Roman',
        #fontName='STSong-Light',
        #fontName='UMing',
        fontSize=12)

    recipient_name_label = Paragraph("To:", ps)
    recipient_name_text = Paragraph(escape(recipient_name[:64]), ps)

    recipient_fax_label = Paragraph("Fax:", ps)
    recipient_fax_text = Paragraph(escape(recipient_fax[:64]), ps)

    recipient_phone_label = Paragraph("Phone:", ps)
    recipient_phone_text = Paragraph(escape(recipient_phone[:64]), ps)

    sender_name_label = Paragraph("From:", ps)
    sender_name_text = Paragraph(escape(sender_name[:64]), ps)

    sender_phone_label = Paragraph("Phone:", ps)
    sender_phone_text = Paragraph(escape(sender_phone[:64]), ps)

    sender_email_label = Paragraph("Email:", ps)
    sender_email_text = Paragraph(escape(sender_email[:64]), ps)

    regarding_label = Paragraph("Regarding:", ps)
    regarding_text = Paragraph(escape(regarding[:128]), ps)

    date_time_label = Paragraph("Date:", ps)
    date_time_text = Paragraph(
        strftime("%a, %d %b %Y %H:%M:%S (%Z)", localtime()), ps)

    total_pages_label = Paragraph("Total Pages:", ps)
    total_pages_text = Paragraph("%d" % total_pages, ps)

    data = [[
        recipient_name_label, recipient_name_text, sender_name_label,
        sender_name_text
    ],
            [
                recipient_fax_label, recipient_fax_text, sender_phone_label,
                sender_phone_text
            ],
            [
                date_time_label, date_time_text, sender_email_label,
                sender_email_text
            ],
            [
                regarding_label, regarding_text, total_pages_label,
                total_pages_text
            ]]

    LIST_STYLE = TableStyle([  #('LINEABOVE', (0,0), (-1,0), 2, colors.black),
        #('LINEABOVE', (0,1), (-1,-1), 0.25, colors.black),
        #('LINEBELOW', (0,-1), (-1,-1), 2, colors.black),
        ('ALIGN', (1, 1), (-1, -1), 'RIGHT'),
        ('VALIGN', (0, 0), (-1, -1), 'TOP'),
    ])

    story.append(HRFlowable(width='100%', color='black'))

    story.append(Table(data, style=LIST_STYLE))

    if message:
        MSG_STYLE = TableStyle([  #('LINEABOVE', (0,0), (-1,0), 2, colors.black),
            #('LINEABOVE', (0,1), (-1,-1), 0.25, colors.black),
            #('LINEBELOW', (0,-1), (-1,-1), 2, colors.black),
            ('ALIGN', (1, 1), (-1, -1), 'RIGHT'),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ('SPAN', (-2, 1), (-1, -1)),
        ])

        story.append(HRFlowable(width='100%', color='black'))
        story.append(Spacer(1, 0.5 * inch))

        if preserve_formatting:
            message = '\n'.join(message[:2048].splitlines()[:32])

            data = [
                [Paragraph("Comments/Notes:", ps), ''],
                [Preformatted(escape(message), ps), ''],
            ]
        else:
            data = [
                [Paragraph("Comments/Notes:", ps), ''],
                [Paragraph(escape(message[:2048]), ps), ''],
            ]

        story.append(HRFlowable(width='100%', color='black'))
        story.append(Table(data, style=MSG_STYLE))
        story.append(HRFlowable(width='100%', color='black'))

    if page_size == PAGE_SIZE_LETTER:
        pgsz = letter
    elif page_size == PAGE_SIZE_LEGAL:
        pgsz = legal
    else:
        pgsz = A4

    if output is None:
        f_fd, f = utils.make_temp_file()
    else:
        f = output

    doc = SimpleDocTemplate(f, pagesize=pgsz)
    doc.build(story)

    return f
Beispiel #35
0
SINGLE_HEADER_TABLE_STYLES = TABLE_STYLES + (
    ('ALIGN', (0, 0), (-1, 0), 'CENTER'),
    ('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey),
)


def _style(style_name, **kwargs):
    style = deepcopy(STYLES[style_name])
    if kwargs is not None:
        for k, v in kwargs.items():
            setattr(style, k, v)
    return style


hr = HRFlowable(
    width="100%", thickness=1, lineCap='round', color=colors.lightgrey,
    spaceBefore=1, spaceAfter=1, hAlign='CENTER', vAlign='BOTTOM', dash=None
)

_bodytext = partial(_style, 'BodyText', fontSize=FONTSIZE_DEFAULT, fontName='Helvetica')

centered_paragraph_style = _bodytext(alignment=TA_CENTER)
left_paragraph_style = _bodytext(alignment=TA_LEFT)
right_paragraph_style = _bodytext(alignment=TA_RIGHT)
bold_centered_paragraph_style = _bodytext(alignment=TA_CENTER, fontName='Helvetica-Bold')
bold_left_paragraph_style = _bodytext(alignment=TA_LEFT, fontName='Helvetica-Bold')
bold_right_paragraph_style = _bodytext(alignment=TA_RIGHT, fontName='Helvetica-Bold')
small_centered_paragraph_style = _bodytext(alignment=TA_CENTER, fontSize=FONTSIZE_SMALL)
small_left_paragraph_style = _bodytext(alignment=TA_LEFT, fontSize=FONTSIZE_SMALL)
small_right_paragraph_style = _bodytext(alignment=TA_RIGHT, fontSize=FONTSIZE_SMALL)
small_bold_centered_paragraph_style = _bodytext(alignment=TA_CENTER, fontSize=FONTSIZE_SMALL, fontName='Helvetica-Bold')
small_bold_left_paragraph_style = _bodytext(alignment=TA_LEFT, fontSize=FONTSIZE_SMALL, fontName='Helvetica-Bold')