Example #1
0
	def add_image(path,x,y,size):
		#setting image vars
		image_path = path
		x = x*mm
		y = y*mm
		size_x = size[0]*mm
		size_y = size[1]*mm

		#setting frame
		image_frame = Frame(x,y,size_x,size_y,id=str(path),bottomPadding=0,topPadding=0,leftPadding=0)
		page_frames.append(image_frame)

		#setting object in frame:
		image = Image(image_path,size_x,size_y,mask=[0,255, 0,255, 0,255])
		page_elements.append(image)
		page_elements.append(FrameBreak())
Example #2
0
    def build(self, style=1):
        self.h1 = self.styleSheet['Heading1']
        self.h1.fontName = 'Helvetica'
        self.bv = self.styleSheet['BodyText']
        self.bv.fontName = 'Helvetica'
        self.bv.fontSize = 7
        self.bv.spaceBefore = 0
        self.bv.spaceAfter = 0

        self.header = self.styleSheet['Heading3']
        self.header.fontName = 'Helvetica'

        self.data.append(Paragraph(translation.t(self.language, 'mediatumhelptitle'), self.h1))
        self.data.append(Paragraph(self.path, self.bv))

        self.data.append((FrameBreak()))

        # format content
        self.content = self.content.replace("\n", "")
        repl = {'p': 'BodyText', 'h1': 'Heading1', 'h2': 'Heading2', 'h3': 'Heading3', 'h4': 'Heading4', 'h5': 'Heading5', 'li': 'Bullet'}
        curstyle = "BodyText"
        for item in re.split(r'<(p|h[1-5]|li)>|<(/p|/h[1-5]|/li)>', self.content):
            if item and item != "":
                if item in repl.keys():
                    curstyle = repl[item]
                elif item[0] == "/" and item[1:] in repl.keys():
                    curstyle = ""
                else:
                    if item.strip != "" and curstyle != "":
                        print 'add', item, "-->", curstyle
                        if curstyle == "Bullet":
                            item = "- " + item
                            print "bullet", item
                        self.data.append(Paragraph(item, self.styleSheet[curstyle]))

        template = SimpleDocTemplate(config.get("paths.tempdir", "") + "help.pdf", showBoundary=0)
        tFirst = PageTemplate(id='First', onPage=self.myPages, pagesize=defaultPageSize)
        tNext = PageTemplate(id='Later', onPage=self.myPages, pagesize=defaultPageSize)

        template.addPageTemplates([tFirst, tNext])
        template.allowSplitting = 1
        BaseDocTemplate.build(template, self.data)

        template.canv.setAuthor(translation.t(self.language, "main_title"))
        template.canv.setTitle("%s \n'%s' - %s: %s" % (translation.t(self.language, "edit_stats_header"),
                                                       'sdfsdfsdf', translation.t(self.language, "edit_stats_period_header"), '2003'))
        return template.canv._doc.GetPDFData(template.canv)
Example #3
0
    def setHeader(self, collection):
        h1 = self.styleSheet['Heading1']
        h1.fontName = 'Helvetica'
        if not collection:
            self.header = Paragraph(t(self.language, "print_view_header"), h1)
        else:
            p = Paragraph(t(self.language, collection.name), h1)
            p.wrap(defaultPageSize[0], defaultPageSize[1])
            self.headerWidth = p.getActualLineWidths0()[0]
            self.header = p
            self.addData(self.header)
            self.addData(FrameBreak())

            if len(collection.get("system.logo")) > 1:
                for f in collection.getFiles():
                    fn = f.getName()
                    if fn.endswith(collection.get("system.logo")):
                        self.addImage(f.retrieveFile(), 1)
Example #4
0
	def add_image(path,x,y,size):
		#setting image vars
		image_path = path
		x = x
		y = y
		print 'size', size
		size_x = size[0]*mm
		size_y = size[1]*mm

		#setting frame
		image_frame = Frame(x,y,size_x,size_y,id=str(path),bottomPadding=0,topPadding=0,leftPadding=0,rightPadding=0)
		page_frames.append(image_frame)

		#setting object in frame:
		#image = Image(image_path,size_x,size_y,mask='auto')
		image_obj = flow.image.init(image_path,size_x,size_y)
		page_elements.append(image_obj)
		page_elements.append(FrameBreak())
Example #5
0
 def print_device_info(self):
     """
     Prints the device info to the pdf
     """
     self.story.append(
         Paragraph('Πληροφορίες Συσκευής', self.styleH)
     )
     self.story.append(
         Paragraph('<font color=(0,0.6,0.8)>Ημερομηνία Εισαγωγής: </font>{0}'.format(self.ticket.admission_date.strftime("%d-%m-%Y")), self.styleN)
     )
     self.story.append(
         Paragraph('<font color=(0,0.6,0.8)>Ημερομηνία Εξαγωγής: </font>{0}'.format(self.ticket.discharge_full_date()), self.styleN)
     )
     self.story.append(
         Paragraph('<font color=(0,0.6,0.8)>Συσκευή: </font>{0}'.format(self.ticket.device.model), self.styleN)
     )
     self.story.append(
         Paragraph('<font color=(0,0.6,0.8)>S/N: </font>{0}'.format(self.ticket.device.serial_number), self.styleN)
     )
     self.story.append(FrameBreak())
Example #6
0
        def build_title_page(doc, Story, title, subtitle):
            styles = getSampleStyleSheet()
            styles.add(
                ParagraphStyle(name='CenterTitle',
                               fontSize=24,
                               alignment=TA_CENTER))
            styles.add(
                ParagraphStyle(name='CenterSubtitle',
                               fontSize=16,
                               alignment=TA_CENTER,
                               leading=16))

            Story.append(Paragraph(title, styles['CenterTitle']))
            Story.append(FrameBreak())
            Story.append(Paragraph(subtitle, styles['CenterSubtitle']))
            Story.append(
                Paragraph(datetime.today().strftime('%Y-%m-%d'),
                          styles['CenterSubtitle']))
            # Story.append(PageBreak())
            return (Story)
Example #7
0
 def print_client_info(self):
     """
     Prints the client info to the pdf
     """
     self.story.append(
         Paragraph('Πληροφορίες Πελάτη', self.styleH)
     )
     self.story.append(
         Paragraph('<font color=(0,0.6,0.8)>Πελάτης: </font>{0}'.format(self.ticket.client.full_name()), self.styleN)
     )
     self.story.append(
         Paragraph('<font color=(0,0.6,0.8)>Σταθερό: </font>{0}'.format(self.ticket.client.landline()), self.styleN)
     )
     self.story.append(
         Paragraph('<font color=(0,0.6,0.8)>Κινητό: </font>{0}'.format(self.ticket.client.mobile_phone()), self.styleN)
     )
     self.story.append(
         Paragraph('<font color=(0,0.6,0.8)>Service ID: </font>{0}'.format(self.ticket.id), self.styleN)
     )
     self.story.append(FrameBreak())
Example #8
0
    def build_page(self, template_id, flowable_map):
        """Build a pdf page by looking up the specified template and then mapping the flowable_map items to the
        appropriate named Frame
        """
        pt = self.get_page_template(template_id)
        # If this is the first page then ensure the page template is ordered first and no breaks or changes
        # are requested otherwise blank page shows up
        if self.active_template_id is None:
            self.make_template_first(template_id)
            self.story.append(NextPageTemplate(template_id))
            self.inc_cover and self.story.append(PageBreak())
            self.active_template_id = template_id
        elif self.active_template_id == template_id:
            # TODO - understand why this is necessary to not get a blank page between pages
            self.story.append(PageBreak())
        else:
            self.story.append(NextPageTemplate(template_id))
            self.story.append(PageBreak())
            self.active_template_id = template_id

        for idx, frame in enumerate(pt.frames):
            if frame.id not in flowable_map:
                # Add a note to the template to show that nothing was defined for this area
                self.story.append(
                    Paragraph('NOT DEFINED: %s' % frame.id,
                              getSampleStyleSheet()['Normal']))
            else:
                flowables = flowable_map[frame.id]
                if not isinstance(flowables, Flowable) and hasattr(
                        flowables, '__iter__'):
                    [self.story.append(f) for f in flowables]
                else:
                    self.story.append(flowables)
            if idx < (len(pt.frames) - 1):
                self.story.append(FrameBreak())
        return self
Example #9
0
        def __init__(self, context, filename, headings, all_first_heads,
                     all_other_heads, all_ars, all_results, all_cats, all_oor,
                     all_dries, all_attachments, all_remarks, all_managers,
                     all_disclaimers, lab_title):
            def myFirstPage(canvas, doc):
                canvas.saveState()
                drawLogos(canvas, doc)
                canvas.restoreState()

            def myLaterPages(canvas, doc):
                canvas.saveState()
                drawLogos(canvas, doc)
                canvas.restoreState()

            def drawLogos(canvas, doc):
                if self.logos[self.logo_imgs[0]] is not None:
                    # draws the logo if it exists
                    (image, width, height) = self.logos[self.logo_imgs[0]]
                    canvas.drawImage(image, 0.75 * inch,
                                     doc.pagesize[1] - inch * 1.2, width / 1.5,
                                     height / 1.5)
                if self.logos[self.logo_imgs[1]] is not None:
                    # draws the accreditation logo if it exists
                    (image, width, height) = self.logos[self.logo_imgs[1]]
                    canvas.drawImage(image, 5.5 * inch,
                                     doc.pagesize[1] - inch * 1.2, width / 1.5,
                                     height / 1.5)
                canvas.setFont('Helvetica', 10)
                canvas.drawString(4 * inch, 0.75 * inch, "Page %d" % doc.page)

            # save some datas
            self.context = context
            self.built = 0
            self.objects = []

            # get all the images we need now, in case we've got
            # several pages this will save some CPU

            self.logos = {}
            self.logo_imgs = ['logo_print.jpg', 'accreditation_print.jpg']
            for pic in self.logo_imgs:
                image = self.getImageFP(pic)
                self.logos[pic] = image

            images = {}
            icons = [
                'no_invoice.png',
                'dry.png',
                'accredited.jpg',
                'exclamation.jpg',
                'telephone.jpg',
                'email.jpg',
            ]
            for pic in icons:
                image = self.getImageFromFS(pic, width=12)
                images[pic] = image
            for manager in all_managers:
                owner = manager
                pic = 'Signature'
                image = self.getImageFromZODB(pic, owner)
                images[manager.getId()] = image

            #   save some colors
            bordercolor = colors.HexColor(0x999933)
            #backgroundcolor = colors.HexColor(0xD3D3AD)
            backgroundcolor = colors.HexColor(0xFFFFFF)
            dryheadcolor = colors.HexColor(0xA6B5DB)
            #drybodycolor = colors.HexColor(0xDAE0F0)
            drybodycolor = colors.HexColor(0xFFFFFF)
            #catcolor = colors.HexColor(0xB6C0D1)
            catcolor = colors.HexColor(0xFFFFFF)

            # we will build an in-memory document
            # instead of creating an on-disk file.
            self.report = cStringIO.StringIO()

            # initialise a PDF document using ReportLab's platypus
            self.doc = SimpleDocTemplate(self.report)

            # get page size
            page_width = self.doc.pagesize[0] - 1.5 * inch
            h_col_width = page_width / 2
            page_height = self.doc.pagesize[1]

            # get the default style sheets
            self.StyleSheet = styles.getSampleStyleSheet()
            self.StyleSheet['Normal'].fontName = 'Helvetica'
            self.StyleSheet['Heading1'].fontName = 'Helvetica'

            # then build a simple doc with ReportLab's platypus
            self.append(Spacer(0, 20))

            h_table = platypus.Table(headings,
                                     colWidths=(h_col_width, h_col_width))

            style = platypus.TableStyle([
                ('ALIGN', (0, 0), (0, -1), 'LEFT'),
                ('ALIGN', (-1, 0), (-1, -1), 'RIGHT'),
                ('FONT', (0, 0), (-1, -1), 'Helvetica'),
            ])
            h_table.setStyle(style)
            self.append(h_table)

            self.append(Spacer(0, 10))

            no_ars = all_ars[0]

            col = page_width / ((no_ars * 2) + 4)

            for i in range(len(all_results)):
                these_ars = all_ars[i]
                these_results = all_results[i]
                these_dries = all_dries[i]
                cols = [
                    col * 4,
                ]
                """ make as fed column wider than dry column """
                for j in range(these_ars):
                    cols.append(col * 1.4)
                    cols.append(col * 0.6)
                col_widths = tuple(cols)
                first_page = True
                if i > 0:
                    self.append(FrameBreak())
                    self.append(Spacer(0, 10))
                """ attachments """
                attachments = all_attachments[i]
                if len(attachments) == 1:
                    attachments[0][1] == 'None'
                else:
                    a_table = platypus.Table(attachments)
                    table_style = [
                        ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
                        ('GRID', (0, 0), (-1, -1), 0.1, bordercolor),
                        ('TEXTCOLOR', (0, 0), (-1, -1), colors.black),
                        ('BACKGROUND', (0, 0), (0, -1), backgroundcolor),
                        ('BACKGROUND', (0, 0), (-1, 0), backgroundcolor),
                        ('FONT', (0, 0), (-1, -1), 'Helvetica'),
                        ('FONTSIZE', (0, 0), (-1, -1), 10),
                    ]
                    style = platypus.TableStyle(table_style)
                    a_table.setStyle(style)
                    a_table.setStyle(style)
                    self.append(a_table)

                self.append(Spacer(0, 10))
                """ determine no of lines in attachment table """
                attachment_count = 0
                for attachment in attachments:
                    attachment_count += 1
                    attachment_count += attachment.count('\n')
                """ headings and results """

                general_table_style = [
                    ('ALIGN', (0, 0), (0, -1), 'LEFT'),
                    ('ALIGN', (1, 0), (-1, -1), 'CENTER'),
                    ('TEXTCOLOR', (0, 0), (-1, -1), colors.black),
                    ('BACKGROUND', (0, 0), (0, -1), backgroundcolor),
                    ('FONT', (0, 0), (-1, -1), 'Helvetica'),
                    ('FONTSIZE', (0, 0), (-1, -1), 9),
                ]

                page_max = 18 - attachment_count

                these_oor = all_oor[i]
                these_cats = all_cats[i]
                num_lines = len(these_results)

                slice_end = 0

                while slice_end < num_lines:
                    """ headings """
                    table_style = list(general_table_style)
                    if first_page:
                        page_content = list(all_first_heads[i])
                        table_style.append(
                            ('GRID', (0, 0), (0, -1), 0.1, bordercolor))
                        table_style.append(
                            ('BACKGROUND', (0, 11), (-1, 11), backgroundcolor))
                        table_style.append(('LINEBELOW', (0, 10), (
                            -1,
                            10,
                        ), 1, bordercolor))
                        table_style.append(
                            ('LINEBELOW', (0, 11), (-1, 11), 1, bordercolor))
                        """ span and box the header lines """
                        for j in range(11):
                            for k in range(these_ars):
                                table_style.append(('SPAN', ((k * 2) + 1, j),
                                                    ((k * 2) + 2, j)))
                                table_style.append(
                                    ('BOX', ((k * 2) + 1, j), ((k * 2) + 2, j),
                                     0.1, bordercolor))

                    else:
                        self.append(FrameBreak())
                        self.append(Spacer(0, 20))
                        page_content = list(all_other_heads[i])
                        table_style.append(
                            ('GRID', (0, 0), (0, -1), 0.1, bordercolor))
                        table_style.append(
                            ('BACKGROUND', (0, 4), (-1, 4), backgroundcolor))
                        table_style.append(('LINEBELOW', (0, 3), (
                            -1,
                            3,
                        ), 1, bordercolor))
                        table_style.append(
                            ('LINEBELOW', (0, 4), (-1, 4), 1, bordercolor))
                        """ span and box the header lines """
                        for j in range(4):
                            for k in range(these_ars):
                                table_style.append(('SPAN', ((k * 2) + 1, j),
                                                    ((k * 2) + 2, j)))
                                table_style.append(
                                    ('BOX', ((k * 2) + 1, j), ((k * 2) + 2, j),
                                     0.1, bordercolor))

                    offset = len(page_content)

                    slice_start = slice_end
                    slice_end = slice_start + page_max
                    if slice_end > num_lines:
                        slice_end = num_lines
                    page_max = 30

                    page_results = these_results[slice_start:slice_end]
                    """ results """
                    page_content.extend(page_results)
                    c_table = platypus.Table(page_content,
                                             colWidths=col_widths)

                    for orig_highlight in these_oor:
                        if orig_highlight[1] < slice_start:
                            continue
                        if orig_highlight[1] >= slice_end:
                            continue
                        highlight = ((orig_highlight[0] * 2) + 1,
                                     orig_highlight[1] + offset - slice_start)
                        table_style.append(
                            ('TEXTCOLOR', highlight, highlight, colors.red))

                    table_length = len(page_content)
                    if first_page:
                        first_page = False
                        """ span and box the detail lines """
                        for k in range(these_ars):
                            for j in range(11, table_length):
                                if k in these_dries:
                                    table_style.append(
                                        ('BOX', ((k * 2) + 1, j),
                                         ((k * 2) + 1, j), 0.1, bordercolor))
                                    table_style.append(
                                        ('BOX', ((k * 2) + 2, j),
                                         ((k * 2) + 2, j), 0.1, bordercolor))
                                else:
                                    table_style.append(
                                        ('SPAN', ((k * 2) + 1, j),
                                         ((k * 2) + 2, j)))
                                    table_style.append(
                                        ('BOX', ((k * 2) + 1, j),
                                         ((k * 2) + 2, j), 0.1, bordercolor))
                        """ colour the dry matter columns """
                        for k in range(these_ars):
                            if k in these_dries:
                                table_style.append(
                                    ('BACKGROUND', ((k * 2) + 2, 11),
                                     ((k * 2) + 2, 11), dryheadcolor))
                                table_style.append(
                                    ('BACKGROUND', ((k * 2) + 2, 12),
                                     ((k * 2) + 2, -1), drybodycolor))
                    else:
                        """ span and box the detail lines """
                        for j in range(4, table_length):
                            for k in range(these_ars):
                                if k in these_dries:
                                    table_style.append(
                                        ('BOX', ((k * 2) + 1, j),
                                         ((k * 2) + 1, j), 0.1, bordercolor))
                                    table_style.append(
                                        ('BOX', ((k * 2) + 2, j),
                                         ((k * 2) + 2, j), 0.1, bordercolor))
                                else:
                                    table_style.append(
                                        ('SPAN', ((k * 2) + 1, j),
                                         ((k * 2) + 2, j)))
                                    table_style.append(
                                        ('BOX', ((k * 2) + 1, j),
                                         ((k * 2) + 2, j), 0.1, bordercolor))
                        """ colour the dry matter columns """
                        for k in range(these_ars):
                            if k in these_dries:
                                table_style.append(
                                    ('BACKGROUND', ((k * 2) + 2, 4),
                                     ((k * 2) + 2, 4), dryheadcolor))
                                table_style.append(
                                    ('BACKGROUND', ((k * 2) + 2, 5),
                                     ((k * 2) + 2, -1), drybodycolor))
                    """ colour and span the category lines """
                    for cat in these_cats:
                        if cat < slice_start:
                            continue
                        if cat >= slice_end:
                            continue
                        cat_box_start = (0, cat + offset - slice_start)
                        cat_box_end = (-1, cat + offset - slice_start)
                        table_style.append(
                            ('SPAN', cat_box_start, cat_box_end))
                        table_style.append(('BACKGROUND', cat_box_start,
                                            cat_box_end, catcolor))
                    style = platypus.TableStyle(table_style)
                    c_table.setStyle(style)
                    self.append(c_table)

                self.append(Spacer(0, 10))
                """ remarks """
                remarks = all_remarks[i]
                if remarks:
                    r_table = platypus.Table(remarks)
                    table_style = [
                        ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
                        ('GRID', (0, 0), (-1, -1), 0.1, bordercolor),
                        ('TEXTCOLOR', (0, 0), (-1, -1), colors.black),
                        ('BACKGROUND', (0, 0), (0, -1), backgroundcolor),
                        ('BACKGROUND', (0, 0), (-1, 0), backgroundcolor),
                        ('FONT', (0, 0), (-1, -1), 'Helvetica'),
                        ('FONTSIZE', (0, 0), (-1, -1), 9),
                    ]
                    style = platypus.TableStyle(table_style)
                    r_table.setStyle(style)
                    self.append(KeepTogether(r_table))

                self.append(Spacer(0, 10))
                """ disclaimers """
                disclaimers = all_disclaimers[i]
                table_style = [
                    ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
                    ('TEXTCOLOR', (0, 0), (-1, -1), colors.darkgray),
                    ('FONT', (0, 0), (-1, -1), 'Helvetica'),
                    ('FONTSIZE', (0, 0), (-1, -1), 9),
                ]
                style = platypus.TableStyle(table_style)
                h_spacer = 10
                d_stuff = []
                for disclaimer in disclaimers:
                    disclaimer.append(' ')
                d_table = platypus.Table(disclaimers,
                                         colWidths=(page_width - 3, 3))
                d_table.setStyle(style)
                self.append(d_table)

                i += 1

            self.append(Spacer(0, 10))
            """ signatures"""

            textStyle = ParagraphStyle('BodyText',
                                       alignment=0,
                                       fontName='Helvetica',
                                       fontSize=10)
            table_style = [
                ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
                ('TEXTCOLOR', (0, 0), (-1, -1), colors.black),
                ('FONT', (0, 0), (-1, -1), 'Helvetica'),
                ('FONTSIZE', (0, 0), (-1, -1), 10),
            ]
            style = platypus.TableStyle(table_style)
            h_spacer = 6
            for manager in all_managers:
                keepers = []

                signatures = [
                    (images[manager.getId()], ' '),
                ]

                s_table = platypus.Table(signatures,
                                         colWidths=(h_col_width, h_col_width))

                s_table.setStyle(style)
                keepers.append(s_table)

                m_stuff = []
                name = manager.Title()
                phone = manager.getBusinessPhone()
                email = manager.getEmailAddress()

                m_stuff.append([
                    name, images['telephone.jpg'], phone, images['email.jpg'],
                    email
                ])
                x = page_width - (len(name) * h_spacer) - (
                    len(phone) * h_spacer) - len(email) - 36
                m_table = platypus.Table(m_stuff,
                                         colWidths=(len(name) * h_spacer, 18,
                                                    len(phone) * h_spacer, 18,
                                                    len(email) + x))
                m_table.setStyle(style)
                keepers.append(m_table)
                para = Paragraph(lab_title, textStyle)
                keepers.append(para)
                keepers.append(Spacer(0, 10))
                self.append(KeepTogether(keepers))

            # generation du document PDF
            self.doc.build(self.objects,
                           onFirstPage=myFirstPage,
                           onLaterPages=myLaterPages)

            self.built = 1
Example #10
0
    def draw(self):
        graph_counter = 0
        map_counter = 0
        current_date = datetime.today().strftime('%d/%m/%Y')
        p = DParagraph(
            str(self.content[0]['user_title']) + ' Report', 'Centred')
        p.render(self.elements)
        p = DParagraph('Date: ' + current_date, 'Centred')
        p.render(self.elements)
        self.elements.append(FrameBreak())
        p = DParagraph(
            'Harwell'
            'G.21-25, Building R71, Rutherford Appleton Laboratory '
            'Harwell Campus, Didcot, OX11 0QX '
            'United Kingdom '
            '+44 (0) 1235 567238', 'Centred_footer')
        p.render(self.elements)
        # self.elements.append(FrameBreak())
        # self.elements.append(PageBreak())
        # content = json.load(open('content.json'))
        # gr = json.load(open('./src/reportPDF/dummy.json'))
        # print(type(self.content))
        if type(self.content) is list:
            pass
        else:
            self.content = json.loads(self.content)
        counter = 0
        for element in self.content:
            if element['type'] == 'graph':
                graph_counter = graph_counter + 1
                # for attribute in self.content[element]:
                self.elements.append(NextPageTemplate('graph'))
                g = PDFgraph(self.__doc, self.template_obj, self.elements, [
                    element['title'], element['description'],
                    element['graph_description'], element['updated_at'],
                    element['label']
                ], graph_counter)
                img = GraphIMG(element['values'], element['units'])
                timestamp = img.create()
                # g.create_graph(self.canvas, self.__doc)
                g.insert_graph_img(timestamp)
                self.images.append(timestamp)
                self.elements = g.get_elements()
                counter = counter + 1
            if element['type'] == 'map':
                map_counter = map_counter + 1
                self.elements.append(NextPageTemplate('map'))
                map_image = Map(self.__doc, self.elements, element['path'],
                                element['title'], element['legend'],
                                element['description'],
                                element['map_description'], element['units'],
                                element['updated_at'],
                                element['map_parameters'], element['label'],
                                map_counter)
                self.images.append(element['path'])
                self.elements = map_image.get_elements()
                imgs = map_image.get_timestamps()
                for img in imgs:
                    self.images.append(img)
                counter = counter + 1
        if counter != 0:
            self.elements.append(PageBreak())

        for element in self.content:
            if element['type'] == 'image':
                self.elements.append(NextPageTemplate('image'))
                t = DTitle(element['title'])
                t.render(self.elements)
                self.elements.append(FrameBreak())
                p = DParagraph(element['description'], 'Normal_Justified')
                p.render(self.elements)
                self.elements.append(FrameBreak())
                img = ImagePIL.open(str(element['path']))
                w, h = img.size
                ratio = min(400 / w, 320 / h)
                pic = Image(str(element['path']), w * ratio, h * ratio)
                self.elements.append(pic)
                self.elements.append(PageBreak())
        for element in self.content:
            if element['type'] == 'textarea':
                self.elements.append(NextPageTemplate('text'))
                t = DTitle(element['title'])
                t.render(self.elements)
                self.elements.append(FrameBreak())
                p = DParagraph(element['description'], 'Normal_Justified')
                p.render(self.elements)
                # self.elements.append(FrameBreak())
                self.elements.append(PageBreak())
def getCommentary():
    """Returns the story for the commentary - all the paragraphs."""

    styleSheet = getSampleStyleSheet()

    story = []
    story.append(
        Paragraph("""
        PLATYPUS User Guide and Test Script
        """, styleSheet['Heading1']))

    spam = """
    Welcome to PLATYPUS!

    Platypus stands for "Page Layout and Typography Using Scripts".  It is a high
    level page layout library which lets you programmatically create complex
    documents with a minimum of effort.

    This document is both the user guide &amp; the output of the test script.
    In other words, a script used platypus to create the document you are now
    reading, and the fact that you are reading it proves that it works.  Or
    rather, that it worked for this script anyway.  It is a first release!

    Platypus is built 'on top of' PDFgen, the Python library for creating PDF
    documents.  To learn about PDFgen, read the document testpdfgen.pdf.

    """

    for text in getParagraphs(spam):
        story.append(Paragraph(text, styleSheet['BodyText']))

    story.append(
        Paragraph(
            """
        What concepts does PLATYPUS deal with?
        """, styleSheet['Heading2']))
    story.append(
        Paragraph(
            """
        The central concepts in PLATYPUS are Flowable Objects, Frames, Flow
        Management, Styles and Style Sheets, Paragraphs and Tables.  This is
        best explained in contrast to PDFgen, the layer underneath PLATYPUS.
        PDFgen is a graphics library, and has primitive commans to draw lines
        and strings.  There is nothing in it to manage the flow of text down
        the page.  PLATYPUS works at the conceptual level fo a desktop publishing
        package; you can write programs which deal intelligently with graphic
        objects and fit them onto the page.
        """, styleSheet['BodyText']))

    story.append(
        Paragraph("""
        How is this document organized?
        """, styleSheet['Heading2']))

    story.append(
        Paragraph(
            """
        Since this is a test script, we'll just note how it is organized.
        the top of each page contains commentary.  The bottom half contains
        example drawings and graphic elements to whicht he commentary will
        relate.  Down below, you can see the outline of a text frame, and
        various bits and pieces within it.  We'll explain how they work
        on the next page.
        """, styleSheet['BodyText']))

    story.append(FrameBreak())
    #######################################################################
    #     Commentary Page 2
    #######################################################################

    story.append(
        Paragraph("""
        Flowable Objects
        """, styleSheet['Heading2']))
    spam = """
        The first and most fundamental concept is that of a 'Flowable Object'.
        In PDFgen, you draw stuff by calling methods of the canvas to set up
        the colors, fonts and line styles, and draw the graphics primitives.
        If you set the pen color to blue, everything you draw after will be
        blue until you change it again.  And you have to handle all of the X-Y
        coordinates yourself.

        A 'Flowable object' is exactly what it says.  It knows how to draw itself
        on the canvas, and the way it does so is totally independent of what
        you drew before or after.  Furthermore, it draws itself at the location
        on the page you specify.

        The most fundamental Flowable Objects in most documents are likely to be
        paragraphs, tables, diagrams/charts and images - but there is no
        restriction.  You can write your own easily, and I hope that people
        will start to contribute them.  PINGO users - we provide a "PINGO flowable" object to let
        you insert platform-independent graphics into the flow of a document.

        When you write a flowable object, you inherit from Flowable and
        must implement two methods.  object.wrap(availWidth, availHeight) will be called by other parts of
        the system, and tells you how much space you have.  You should return
        how much space you are going to use.  For a fixed-size object, this
        is trivial, but it is critical - PLATYPUS needs to figure out if things
        will fit on the page before drawing them.  For other objects such as paragraphs,
        the height is obviously determined by the available width.


        The second method is object.draw().  Here, you do whatever you want.
        The Flowable base class sets things up so that you have an origin of
        (0,0) for your drawing, and everything will fit nicely if you got the
        height and width right.  It also saves and restores the graphics state
        around your calls, so you don;t have to reset all the properties you
        changed.

        Programs which actually draw a Flowable don't
        call draw() this directly - they call object.drawOn(canvas, x, y).
        So you can write code in your own coordinate system, and things
        can be drawn anywhere on the page (possibly even scaled or rotated).
        """
    for text in getParagraphs(spam):
        story.append(Paragraph(text, styleSheet['BodyText']))

    story.append(FrameBreak())
    #######################################################################
    #     Commentary Page 3
    #######################################################################

    story.append(
        Paragraph("""
        Available Flowable Objects
        """, styleSheet['Heading2']))

    story.append(
        Paragraph(
            """
        Platypus comes with a basic set of flowable objects.  Here we list their
        class names and tell you what they do:
        """, styleSheet['BodyText']))
    #we can use the bullet feature to do a definition list
    story.append(
        Paragraph(
            """
        <para color=green bcolor=red bg=pink>This is a <font bgcolor=yellow color=red>contrived</font> object to give an example of a Flowable -
        just a fixed-size box with an X through it and a centred string.</para>""",
            styleSheet['Definition'],
            bulletText='XBox  '  #hack - spot the extra space after
        ))

    story.append(
        Paragraph(
            """
        This is the basic unit of a document.  Paragraphs can be finely
        tuned and offer a host of properties through their associated
        ParagraphStyle.""",
            styleSheet['Definition'],
            bulletText='Paragraph  '  #hack - spot the extra space after
        ))

    story.append(
        Paragraph(
            """
        This is used for printing code and other preformatted text.
        There is no wrapping, and line breaks are taken where they occur.
        Many paragraph style properties do not apply.  You may supply
        an optional 'dedent' parameter to trim a number of characters
        off the front of each line.""",
            styleSheet['Definition'],
            bulletText='Preformatted  '  #hack - spot the extra space after
        ))
    story.append(
        Paragraph(
            """
        This is a straight wrapper around an external image file.  By default
        the image will be drawn at a scale of one pixel equals one point, and
        centred in the frame.  You may supply an optional width and height.""",
            styleSheet['Definition'],
            bulletText='Image  '  #hack - spot the extra space after
        ))

    story.append(
        Paragraph(
            """
        This is a table drawing class; it is intended to be simpler
        than a full HTML table model yet be able to draw attractive output,
        and behave intelligently when the numbers of rows and columns vary.
        Still need to add the cell properties (shading, alignment, font etc.)""",
            styleSheet['Definition'],
            bulletText='Table  '  #hack - spot the extra space after
        ))

    story.append(
        Paragraph(
            """
        This is a 'null object' which merely takes up space on the page.
        Use it when you want some extra padding betweene elements.""",
            styleSheet['Definition'],
            bulletText='Spacer '  #hack - spot the extra space after
        ))

    story.append(
        Paragraph(
            """
        A FrameBreak causes the document to call its handle_frameEnd method.""",
            styleSheet['Definition'],
            bulletText='FrameBreak  '  #hack - spot the extra space after
        ))

    story.append(
        Paragraph(
            """
        This is in progress, but a macro is basically a chunk of Python code to
        be evaluated when it is drawn.  It could do lots of neat things.""",
            styleSheet['Definition'],
            bulletText='Macro  '  #hack - spot the extra space after
        ))

    story.append(FrameBreak())

    story.append(
        Paragraph("The next example uses a custom font", styleSheet['Italic']))

    def code(txt, story=story, styleSheet=styleSheet):
        story.append(Preformatted(txt, styleSheet['Code']))

    code('''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("""We can use images via the file name""",
                      styleSheet['BodyText']))
        code('''    story.append(platypus.Image('%s'))''' % _GIFFSEnc)
        code('''    story.append(platypus.Image(fileName2FSEnc('%s')))''' %
             _GIFFSEnc)
        story.append(
            Paragraph(
                """They can also be used with a file URI or from an open python file!""",
                styleSheet['BodyText']))
        code('''    story.append(platypus.Image('%s'))''' % getFurl(_GIFFSEnc))
        code('''    story.append(platypus.Image(open_for_read('%s','b')))''' %
             _GIFFSEnc)
        story.append(FrameBreak())
        story.append(
            Paragraph("""Images can even be obtained from the internet.""",
                      styleSheet['BodyText']))
        code(
            '''    img = platypus.Image('http://www.reportlab.com/rsrc/encryption.gif')
    story.append(img)''')
        story.append(FrameBreak())

    if _JPG:
        story.append(
            Paragraph(
                """JPEGs are a native PDF image format. They should be available even if PIL cannot be used.""",
                styleSheet['BodyText']))
        story.append(FrameBreak())
    return story
        else:
            print "WARN: No user plots for facility '{}', year 2018".format(fac)
        
        if 2019 in affiliation_data[fac_eng]:
            u19_plot = user_plot(affiliation_data[fac_eng][2019], fac, str(2019), "_{}".format(str(2019)), "svg")
            caller_dict['usr19'] = dict(impath=u19_plot, title="Users 2019", style=styles["pie_plot_title"], **fac_grph.get("figsize", {}).get("u19", {}))
            if 'usr19' not in frames_to_work:
                exit("ERROR: For facility '{}' user plot 2019 available but frame not mentioned in '{}'".format(fac, frames_to_work))
        else:
            print "WARN: No user plots for facility '{}', year 2019".format(fac)
    else:
        print "WARN: No user plots for facility '{}' all years".format(fac)
    
    # call for frames
    for frm in frames_to_work:
        if frm in caller_dict:
            story.extend(get_image_story(**caller_dict[frm]))
        else:
            story.append(FrameBreak())
    
    fac_replab.make_page_templates(**fac_grph.get("frames", {}))
    fac_replab.doc.build(story)








Example #13
0
    def build_doc(self, fhandle):
        def text(s):
            return escape(s).replace("\n", "<br/>")

        doc = BaseDocTemplate(fhandle, pagesize=self.pagesize)
        frames = [
            Frame(
                15 * mm,
                15 * mm,
                100 * mm,
                120 * mm,
                leftPadding=0,
                rightPadding=0,
                topPadding=0,
                bottomPadding=0,
                id='normal',
            ),
            Frame(125 * mm,
                  25 * mm,
                  70 * mm,
                  110 * mm,
                  leftPadding=0,
                  rightPadding=0,
                  topPadding=0,
                  bottomPadding=0,
                  id='normal'),
        ]
        doc.addPageTemplates([
            PageTemplate(id='AllPages',
                         frames=frames,
                         pagesize=self.pagesize,
                         onPage=self._draw_qr)
        ])

        meta = []
        if self.obj.job_location:
            meta.append('Location: {}'.format(self.obj.job_location))
        if self.obj.job_remote:
            meta.append('Remote')
        if self.obj.job_salary_range:
            meta.append('Salary: {}'.format(self.obj.job_salary_range))
        meta = ' · '.join(meta)

        company_story = []
        if self.obj.logo:
            im = Image(os.path.join(settings.MEDIA_ROOT, self.obj.logo.name),
                       height=30 * mm,
                       width=70 * mm,
                       kind='proportional')
            company_story.append(im)
            company_story.append(Spacer(1 * mm, 3 * mm))

        company_story.append(
            Paragraph(text(self.obj.company_name),
                      style=self.stylesheet['Heading1']), )
        company_story.append(
            Paragraph(text(self.obj.company_description),
                      style=self.stylesheet['Normal']), )
        if self.obj.company_contact:
            company_story.append(Spacer(1 * mm, 3 * mm))
            company_story.append(
                Paragraph('Contact', style=self.stylesheet['Heading1']), )
            company_story.append(
                Paragraph(text(self.obj.company_contact),
                          style=self.stylesheet['Normal']), )

        doc.build([
            KeepInFrame(
                110 * mm,
                120 * mm, [
                    Paragraph(text(self.obj.job_title),
                              style=self.stylesheet['Heading1']),
                    Spacer(1 * mm, 2 * mm),
                    Paragraph(text(meta), style=self.stylesheet['Meta']),
                    Spacer(1 * mm, 2 * mm),
                    Paragraph(text(self.obj.job_description),
                              style=self.stylesheet['Normal'])
                ],
                mode='truncate'),
            FrameBreak(),
            KeepInFrame(70 * mm, 110 * mm, company_story, mode='truncate')
        ])
Example #14
0
    def publicationReport(self, plan, publication, ads):
        styles = getSampleStyleSheet()
        Elements = []
        doc = BaseDocTemplate(self.buffer)
        column_gap = 1 * inch
        templates = []
        top = Frame(doc.leftMargin,
                    doc.bottomMargin,
                    doc.width,
                    doc.height,
                    rightPadding=column_gap / 2,
                    showBoundary=0)
        left = Frame(doc.leftMargin,
                     doc.bottomMargin,
                     doc.width,
                     doc.height - ((plan.designs.count() * inch) + 1 * inch),
                     showBoundary=0)
        designs = Frame(doc.leftMargin + doc.width / 2,
                        doc.bottomMargin,
                        doc.width / 2,
                        doc.height - .5 * inch,
                        showBoundary=0)
        columns = []
        columns.append(top)
        columns.append(designs)
        columns.append(left)
        templates.append(PageTemplate(frames=columns, id="columns"))
        doc.addPageTemplates(templates)

        styles.add(
            ParagraphStyle(name='line',
                           parent=styles['BodyText'],
                           spaceBefore=0))
        styles.add(
            ParagraphStyle(name='campaign-name',
                           parent=styles['h4'],
                           spaceBefore=0,
                           spaceAfter=0,
                           fontName='Helvetica-Bold'))

        image = Image(
            '/Users/estyrosenberg/Desktop/MediaPlan/mediaPlan/mediaPlan/static/img/mediaotg-small.png',
            122.25, 31.75)
        image.hAlign = 'LEFT'
        Elements.append(Spacer(width=0, height=.25 * inch))
        Elements.append(image)
        Elements.append(Spacer(width=0, height=.5 * inch))

        Elements.append(Paragraph(str(publication.name), styles['line']))
        Elements.append(Paragraph(str(publication.contactName),
                                  styles['line']))
        Elements.append(Spacer(width=0, height=.25 * inch))

        Elements.append(Paragraph('Plan no: ' + str(plan.pk), styles['line']))
        Elements.append(Paragraph(str(plan.name), styles['campaign-name']))
        client = plan.client
        if plan.client.parent != None:
            client += ' - ' + plan.client.parent
        Elements.append(Paragraph(str(client), styles['line']))
        Elements.append(
            Paragraph('Created: ' + f'{plan.created_at:%b %d, %Y}',
                      styles['line']))
        Elements.append(FrameBreak())

        designList = []
        for design in plan.designs.all():
            tempImage = ''
            if design.thumbnail is not None:
                print('WIDTH: ' + str(design.thumbnail.image.width))
                tempImage = Image(
                    "/Users/estyrosenberg/Desktop/MediaPlan/mediaPlan/mediaPlan/"
                    + design.thumbnail.image.url,
                    design.thumbnail.image.width / 20,
                    design.thumbnail.image.height / 20)
            designList.append([design.name, tempImage])
        Elements.append(Spacer(width=0, height=.25 * inch))
        designList.insert(0, ['Designs', ''])
        wh_table = Table(designList, colWidths=[1.25 * inch] * 5)
        wh_table.setStyle(
            TableStyle([('INNERGRID', (0, 1), (-1, -1), 0.25,
                         colors.Color(red=(200.0 / 255),
                                      green=(200.0 / 255),
                                      blue=(200.0 / 255))),
                        ('BOX', (0, 0), (-1, -1), 0.5,
                         colors.Color(red=(200.0 / 255),
                                      green=(200.0 / 255),
                                      blue=(200.0 / 255))),
                        ('VALIGN', (0, 0), (-1, 0), 'MIDDLE'),
                        ('BACKGROUND', (0, 0), (-1, 0),
                         colors.Color(red=(230.0 / 255),
                                      green=(230.0 / 255),
                                      blue=(230.0 / 255))),
                        ('TEXTCOLOR', (0, 0), (-1, -1),
                         colors.Color(red=(50.0 / 255),
                                      green=(50.0 / 255),
                                      blue=(50.0 / 255)))]))
        Elements.append(wh_table)
        Elements.append(FrameBreak())

        adsList = []
        for ad in ads:
            deadline = ''
            if hasattr(ad, 'week'):
                deadline = str(ad.week.start) + ' - ' + str(ad.week.end)
            else:
                deadline = ad.deadline
            adsList.append([
                ad.rate.rateName, deadline, ad.design,
                '$' + ('%.2f' % int(ad.rate.price))
            ])
        Elements.append(Spacer(width=0, height=.25 * inch))
        adsList.insert(0, ['Ads', '', '', ''])
        wh_table = Table(adsList, colWidths=[1.05 * inch])
        wh_table._argW[1] = 3 * inch

        wh_table.setStyle(
            TableStyle([('INNERGRID', (0, 1), (-1, -1), 0.25,
                         colors.Color(red=(200.0 / 255),
                                      green=(200.0 / 255),
                                      blue=(200.0 / 255))),
                        ('BOX', (0, 0), (-1, -1), 0.5,
                         colors.Color(red=(200.0 / 255),
                                      green=(200.0 / 255),
                                      blue=(200.0 / 255))),
                        ('VALIGN', (0, 0), (-1, 0), 'MIDDLE'),
                        ('BACKGROUND', (0, 0), (-1, 0),
                         colors.Color(red=(230.0 / 255),
                                      green=(230.0 / 255),
                                      blue=(230.0 / 255))),
                        ('TEXTCOLOR', (0, 0), (-1, -1),
                         colors.Color(red=(50.0 / 255),
                                      green=(50.0 / 255),
                                      blue=(50.0 / 255)))]))
        Elements.append(wh_table)

        doc.build(Elements)
        pdf = self.buffer.getvalue()
        self.buffer.close()
        return pdf
Example #15
0
    def planReport(self, table_data, title, plan):
        styles = getSampleStyleSheet()
        Elements = []
        doc = BaseDocTemplate(self.buffer)
        column_gap = 1 * inch
        templates = []
        top = Frame(doc.leftMargin,
                    doc.bottomMargin,
                    doc.width,
                    doc.height,
                    rightPadding=column_gap / 2,
                    showBoundary=0)
        left = Frame(doc.leftMargin,
                     doc.bottomMargin,
                     doc.width,
                     doc.height - ((plan.designs.count() * inch)),
                     showBoundary=0)
        designs = Frame(doc.leftMargin + doc.width / 2,
                        doc.bottomMargin,
                        doc.width / 2,
                        doc.height - .5 * inch,
                        showBoundary=0)
        columns = []
        # tops = []
        columns.append(top)
        columns.append(designs)
        columns.append(left)
        # templates.append(PageTemplate(frames=tops, id="top"))
        templates.append(PageTemplate(frames=columns, id="columns"))
        doc.addPageTemplates(templates)

        styles.add(
            ParagraphStyle(name='line',
                           parent=styles['BodyText'],
                           spaceBefore=0))
        styles.add(
            ParagraphStyle(name='campaign-name',
                           parent=styles['h4'],
                           spaceBefore=0,
                           spaceAfter=0,
                           fontName='Helvetica-Bold'))
        image = Image(
            'http://mediaplan.herokuapp.com/static/img/mediaotg-small.png',
            122.25, 31.75)
        image.hAlign = 'LEFT'
        Elements.append(Spacer(width=0, height=.25 * inch))
        Elements.append(image)
        Elements.append(Spacer(width=0, height=.5 * inch))
        Elements.append(Paragraph('Plan no: ' + str(plan.pk), styles['line']))
        Elements.append(Paragraph(str(plan.name), styles['campaign-name']))
        client = plan.client
        if plan.client.parent != None:
            client += ' - ' + plan.client.parent
        Elements.append(Paragraph(str(client), styles['line']))
        Elements.append(
            Paragraph('Created: ' + f'{plan.created_at:%b %d, %Y}',
                      styles['line']))
        Elements.append(FrameBreak())

        designList = []
        for design in plan.designs.all():
            tempImage = ''
            if design.thumbnail is not None:
                print('WIDTH: ' + str(design.thumbnail.image.width))
                tempImage = Image(
                    "/Users/estyrosenberg/Desktop/MediaPlan/mediaPlan/mediaPlan/"
                    + design.thumbnail.image.url,
                    design.thumbnail.image.width / 20,
                    design.thumbnail.image.height / 20)
            designList.append([design.name, tempImage])
        Elements.append(Spacer(width=0, height=.25 * inch))
        designList.insert(0, ['Designs', ''])
        wh_table = Table(designList, colWidths=[1.25 * inch] * 5)
        wh_table.setStyle(
            TableStyle([('INNERGRID', (0, 1), (-1, -1), 0.25,
                         colors.Color(red=(200.0 / 255),
                                      green=(200.0 / 255),
                                      blue=(200.0 / 255))),
                        ('BOX', (0, 0), (-1, -1), 0.5,
                         colors.Color(red=(200.0 / 255),
                                      green=(200.0 / 255),
                                      blue=(200.0 / 255))),
                        ('VALIGN', (0, 0), (-1, 0), 'MIDDLE'),
                        ('BACKGROUND', (0, 0), (-1, 0),
                         colors.Color(red=(230.0 / 255),
                                      green=(230.0 / 255),
                                      blue=(230.0 / 255))),
                        ('TEXTCOLOR', (0, 0), (-1, -1),
                         colors.Color(red=(50.0 / 255),
                                      green=(50.0 / 255),
                                      blue=(50.0 / 255)))]))
        Elements.append(wh_table)

        Elements.append(FrameBreak())
        for table in table_data:
            Elements.append(Spacer(width=0, height=.25 * inch))
            wh_table = Table(table['table'], colWidths=[1.25 * inch] * 5)
            wh_table.setStyle(
                TableStyle([('INNERGRID', (0, 1), (-1, -1), 0.25,
                             colors.Color(red=(200.0 / 255),
                                          green=(200.0 / 255),
                                          blue=(200.0 / 255))),
                            ('BOX', (0, 0), (-1, -1), 0.5,
                             colors.Color(red=(200.0 / 255),
                                          green=(200.0 / 255),
                                          blue=(200.0 / 255))),
                            ('VALIGN', (0, 0), (-1, 0), 'MIDDLE'),
                            ('BACKGROUND', (0, 0), (-1, 0),
                             colors.Color(red=(230.0 / 255),
                                          green=(230.0 / 255),
                                          blue=(230.0 / 255))),
                            ('TEXTCOLOR', (0, 0), (-1, -1),
                             colors.Color(red=(50.0 / 255),
                                          green=(50.0 / 255),
                                          blue=(50.0 / 255)))]))
            Elements.append(wh_table)

        if plan.full_ads.count() > 0:
            fullList = []
            fullTotal = 0
            for ad in plan.full_ads.all():
                fullList.append([
                    ad.rate.publication.name, ad.rate.rateName, ad.deadline,
                    ad.design, '$' + ('%.2f' % int(ad.rate.price))
                ])
                fullTotal += int(ad.rate.price)
            Elements.append(Spacer(width=0, height=.25 * inch))
            fullList.insert(
                0,
                ['Full Campaign', '', '', '', '$' + ('%.2f' % int(fullTotal))])
            wh_table = Table(fullList, colWidths=[1.25 * inch] * 5)
            wh_table.setStyle(
                TableStyle([('INNERGRID', (0, 1), (-1, -1), 0.25,
                             colors.Color(red=(200.0 / 255),
                                          green=(200.0 / 255),
                                          blue=(200.0 / 255))),
                            ('BOX', (0, 0), (-1, -1), 0.5,
                             colors.Color(red=(200.0 / 255),
                                          green=(200.0 / 255),
                                          blue=(200.0 / 255))),
                            ('VALIGN', (0, 0), (-1, 0), 'MIDDLE'),
                            ('BACKGROUND', (0, 0), (-1, 0),
                             colors.Color(red=(230.0 / 255),
                                          green=(230.0 / 255),
                                          blue=(230.0 / 255))),
                            ('TEXTCOLOR', (0, 0), (-1, -1),
                             colors.Color(red=(50.0 / 255),
                                          green=(50.0 / 255),
                                          blue=(50.0 / 255)))]))
            Elements.append(wh_table)

        if plan.expenses.count() > 0:
            extraList = []
            extraTotal = 0
            for ad in plan.expenses.all():
                extraList.append([
                    ad.name, '', ad.deadline, '',
                    '$' + ('%.2f' % int(ad.total))
                ])
                extraTotal += int(ad.total)
            Elements.append(Spacer(width=0, height=.25 * inch))
            extraList.insert(0, [
                'Additional Expenses', '', '', '', '$' +
                ('%.2f' % int(extraTotal))
            ])
            wh_table = Table(extraList, colWidths=[1.25 * inch] * 5)
            wh_table.setStyle(
                TableStyle([('INNERGRID', (0, 1), (-1, -1), 0.25,
                             colors.Color(red=(200.0 / 255),
                                          green=(200.0 / 255),
                                          blue=(200.0 / 255))),
                            ('BOX', (0, 0), (-1, -1), 0.5,
                             colors.Color(red=(200.0 / 255),
                                          green=(200.0 / 255),
                                          blue=(200.0 / 255))),
                            ('VALIGN', (0, 0), (-1, 0), 'MIDDLE'),
                            ('BACKGROUND', (0, 0), (-1, 0),
                             colors.Color(red=(230.0 / 255),
                                          green=(230.0 / 255),
                                          blue=(230.0 / 255))),
                            ('TEXTCOLOR', (0, 0), (-1, -1),
                             colors.Color(red=(50.0 / 255),
                                          green=(50.0 / 255),
                                          blue=(50.0 / 255)))]))
            Elements.append(wh_table)

        Elements.append(Spacer(width=0, height=.25 * inch))
        totals = [['Totals']]
        weekly = 0
        for ad in plan.weekly_ads.all():
            weekly += int(ad.rate.price)
        totals.append(['Weeklys', '$' + ('%.2f' % int(weekly))])
        wh_table = Table(totals, colWidths=[1.25 * inch] * 5)
        wh_table.setStyle(
            TableStyle([('INNERGRID', (0, 1), (-1, -1), 0.25,
                         colors.Color(red=(200.0 / 255),
                                      green=(200.0 / 255),
                                      blue=(200.0 / 255))),
                        ('BOX', (0, 0), (-1, -1), 0.5,
                         colors.Color(red=(200.0 / 255),
                                      green=(200.0 / 255),
                                      blue=(200.0 / 255))),
                        ('VALIGN', (0, 0), (-1, 0), 'MIDDLE'),
                        ('BACKGROUND', (0, 0), (-1, 0),
                         colors.Color(red=(230.0 / 255),
                                      green=(230.0 / 255),
                                      blue=(230.0 / 255))),
                        ('TEXTCOLOR', (0, 0), (-1, -1),
                         colors.Color(red=(50.0 / 255),
                                      green=(50.0 / 255),
                                      blue=(50.0 / 255)))]))
        wh_table.hAlign = 'RIGHT'
        Elements.append(wh_table)

        doc.build(Elements)
        pdf = self.buffer.getvalue()
        self.buffer.close()
        return pdf
    ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
    ('VALIGN', (3, 0), (3, 0), 'BOTTOM'),
    ('BACKGROUND', (3, 0), (3, 0), colors.limegreen),
    ('BACKGROUND', (3, 1), (3, 1), colors.khaki),
    ('ALIGN', (3, 1), (3, 1), 'CENTER'),
    ('BACKGROUND', (3, 2), (3, 2), colors.beige),
    ('ALIGN', (3, 2), (3, 2), 'LEFT'),
]
#end debug

#sequence
Ilogo = Image('.\\logo.jpg')
Ilogo.drawHeight = 4 * xc * I.drawHeight / I.drawWidth
Ilogo.drawWidth = 4 * xc
Elements.append(Ilogo)
Elements.append(FrameBreak())
Elements.append(Paragraph('Title', styles['title']))
Elements.append(FrameBreak())
Elements.append(Paragraph('Date', styles['title']))
Elements.append(FrameBreak())
Elements.append(Paragraph('Author', styles['title']))
Elements.append(FrameBreak())
Elements.append(Paragraph('Part no.', styles['h6']))
Elements.append(FrameBreak())
Elements.append(Paragraph('Part description', styles['h6']))
Elements.append(FrameBreak())
Elements.append(Paragraph('Part rev.', styles['h6']))
Elements.append(FrameBreak())
Elements.append(Paragraph('Step no.', styles['h6']))
Elements.append(FrameBreak())
Elements.append(Paragraph('Step description', styles['h6']))
Example #17
0
def some_view3(request, *args, **kwargs):

    from django.http import HttpResponse

    from reportlab.lib import colors
    from reportlab.lib.pagesizes import letter, inch
    from reportlab.platypus import Image, Paragraph, SimpleDocTemplate, Table, TableStyle, Frame, PageTemplate, BaseDocTemplate, FrameBreak, Spacer
    from reportlab.lib.styles import getSampleStyleSheet

    # Create the HttpResponse object with the appropriate PDF headers.
    response = HttpResponse(content_type='application/pdf')
    #response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"'

    #A4 width = 8.5 inches

    # define frames - for frames in page
    # frameHeader = Frame(x1=0*inch, y1=10.0*inch, width=8.5*inch, height=1.0*inch, showBoundary=1)

    # frameTable1 = Frame(x1=0.0*inch, y1=6.25*inch, width=3.8*inch, height=3.95*inch, showBoundary=1)
    # frameTable2 = Frame(x1=3.8*inch, y1=6.25*inch, width=4.7*inch, height=3.95*inch, showBoundary=1)

    # #Articles
    # frameTable3 = Frame(x1=0*inch, y1=2.0*inch, width=8.5*inch, height=4.25*inch, showBoundary=1)

    # frameTable4 = Frame(x1=0.0*inch, y1=0.7*inch, width=4.25*inch, height=1.3*inch, showBoundary=1)
    # frameTable5 = Frame(x1=4.25*inch, y1=0.7*inch, width=4.25*inch, height=1.3*inch, showBoundary=1)

    # frameTable6 = Frame(x1=0.4*inch, y1=0.0*inch, width=1.6*inch, height=0.7*inch, showBoundary=1)
    # frameTable7 = Frame(x1=2.0*inch, y1=0.0*inch, width=1.5*inch, height=0.7*inch, showBoundary=1)
    # frameTable8 = Frame(x1=3.5*inch, y1=0.0*inch, width=1.5*inch, height=0.7*inch, showBoundary=1)
    # frameTable9 = Frame(x1=5.0*inch, y1=0.0*inch, width=1.5*inch, height=0.7*inch, showBoundary=1)
    # frameTable10 = Frame(x1=6.5*inch, y1=0.0*inch, width=1.6*inch, height=0.7*inch, showBoundary=1)

    frameHeader = Frame(
        x1=0 * inch,
        y1=10.0 * inch,
        width=8.5 * inch,
        height=1.0 * inch,
    )

    frameTable1 = Frame(x1=0.0 * inch,
                        y1=6.25 * inch,
                        width=3.8 * inch,
                        height=3.95 * inch)
    frameTable2 = Frame(x1=3.8 * inch,
                        y1=6.25 * inch,
                        width=4.7 * inch,
                        height=3.95 * inch)

    #Articles
    frameTable3 = Frame(x1=0 * inch,
                        y1=2.0 * inch,
                        width=8.5 * inch,
                        height=4.50 * inch)

    frameTable4 = Frame(x1=0.2 * inch,
                        y1=0.7 * inch,
                        width=4.25 * inch,
                        height=1.3 * inch)
    frameTable5 = Frame(x1=4.48 * inch,
                        y1=0.7 * inch,
                        width=4.25 * inch,
                        height=1.3 * inch)

    frameTable6 = Frame(x1=0.4 * inch,
                        y1=0.0 * inch,
                        width=1.6 * inch,
                        height=0.7 * inch)
    frameTable7 = Frame(x1=2.0 * inch,
                        y1=0.0 * inch,
                        width=1.5 * inch,
                        height=0.7 * inch)
    frameTable8 = Frame(x1=3.5 * inch,
                        y1=0.0 * inch,
                        width=1.5 * inch,
                        height=0.7 * inch)
    frameTable9 = Frame(x1=5.0 * inch,
                        y1=0.0 * inch,
                        width=1.5 * inch,
                        height=0.7 * inch)
    frameTable10 = Frame(x1=6.5 * inch,
                         y1=0.0 * inch,
                         width=1.6 * inch,
                         height=0.7 * inch)

    #frameTable6 = Frame(x1=5.5625*inch, y1=7.0*inch, width=1.5*inch, height=1.0*inch)
    #Checkboxes
    #frameTable7 = Frame(x1=1.0625*inch, y1=1.5*inch, width=1.5*inch, height=6.2*inch)
    #frameTable8 = Frame(x1=2.5625*inch, y1=1.5*inch, width=5.5*inch, height=5.5*inch)
    #Signature
    #frameTable9 = Frame(x1=0*inch, y1=0.5*inch, width=8.5*inch, height=1.0*inch)

    # define pageTemplates - for page in document
    mainPage = PageTemplate(frames=[
        frameHeader, frameTable1, frameTable2, frameTable3, frameTable4,
        frameTable5, frameTable6, frameTable7, frameTable8, frameTable9,
        frameTable10
    ])

    # define BasicDocTemplate - for document
    doc = BaseDocTemplate(response, pagesize=letter, pageTemplates=mainPage)

    # styles
    styleSheet = getSampleStyleSheet()
    styleH = styleSheet['Heading1']

    # create a story
    # container for the 'Flowable' objects
    elements = []

    # Add all the flowables to different frames
    #elements.append(heading)
    #elements.append(FrameBreak())      # move to next frame

    #TESTING FRAMES
    #Two Columns
    #frame1 = Frame(doc.leftMargin, doc.bottomMargin, doc.width/2-6, doc.height, id='col1', showBoundary=1)
    #frame2 = Frame(doc.leftMargin+doc.width/2+6, doc.bottomMargin, doc.width/2-6, doc.height, id='col2', showBoundary=1)
    #doc.addPageTemplates([PageTemplate(id='TwoCol',frames=[frame1,frame2]), ])

    #I = Image('replogo.gif')
    #I.drawHeight = 1.25*inch*I.drawHeight / I.drawWidth
    #I.drawWidth = 1.25*inch

    ###############################################################
    #Hamta modeller som kommer anvandas fran databasen

    workorder = Workorder.objects.get(pk=kwargs.get('pk', None))

    #Serviceprotocol.objects.get(pk=kwargs.get('pk', None))
    #print(Serviceprotocol)
    #  for product in Product.objects.all():
    #   p = Paragraph("%s" % product.name, style)
    #   Catalog.append(p)
    #   s = Spacer(1, 0.25*inch)
    #   Catalog.append(s)
    # doc.build(Catalog)

    ###############################################################

    ###############################################################
    #Rubrik

    h = Paragraph("""<para align=center spaceb=3><b>Arbetsorder</b></para>""",
                  styleH)

    elements.append(h)

    g = Spacer(1, 0.05 * inch)

    elements.append(g)

    ###############################################################

    ###############################################################
    #DATUM
    data = [['Datum:', workorder.date]]
    a = Table(
        data,
        style=[
            #('BOX',(0,0),(-1,-1),2,colors.black),
            ('LINEBELOW', (0, 0), (1, 0), 1, colors.black),
            ('ALIGN', (0, 0), (0, 0), 'CENTER'),
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ])
    a._argW[-1] = 1.1 * inch

    elements.append(a)
    elements.append(FrameBreak())

    ###############################################################

    ###############################################################
    #Company information

    data = [
        ["Nilsson's MC Shop AB"],
        ['Industrigatan 48'],
        ['58277 Linköping'],
        ['Tel 013-141458'],
        #['Verkstad Mob. 072-7141471'],
        ['ESD 2012']
    ]

    b = Table(
        data,
        style=[  #(col, row)
            ('ALIGN', (0, 0), (0, 4), 'CENTER'),
        ])
    #f._argW[0]=1.6*inch

    elements.append(b)
    elements.append(FrameBreak())
    ###############################################################

    ###############################################################
    #Customer and motorcykle information
    #foo = 'Blablabla bla bla blall bllalall bla bla blall bllalall bla bal Blablabla bla bla blall bllalall bla bal Blablabla bla bla blall bllalall bla bal Blablabla bla bla blall bllalall bla bal bla bal bla b !MAX 4 RADER!'
    #bar = 'Foo Bar foobar foobar fo bar fofofo bar Foo Bar foobar foobar fo bar fofofo bar Foo Bar foobar foobar fo bar fofofo bar Foo Bar foobar foobar fo bar fofofo bar fo bar fofofo bar !MAX 4 RADER!'

    p1 = Paragraph("%s" % workorder.job, styleSheet["BodyText"])
    p2 = Paragraph("%s" % workorder.notification, styleSheet["BodyText"])

    data = [[
        'Kund:',
        workorder.customer.first_name + " " + workorder.customer.last_name
    ], ['Adress:', workorder.customer.street],
            ['Telefon:', workorder.customer.telephone_set.all()[0]],
            ['Mc:', workorder.brand], ['Modell:', workorder.model],
            ['År:', workorder.year], ['Motor:', workorder.motor],
            ['Arbete:', p1], ['Anm:', p2],
            ['Regnr:', workorder.registration_nr], ['Km:', workorder.km]]

    c = Table(
        data,
        style=[  #(col, row)
            #('GRID',(0,0),(-1,-1),2,colors.black),
            #('LINEABOVE',(1,1),(1,1),1,colors.black),
            #('LINEABOVE',(1,2),(1,2),1,colors.black),
            #('LINEABOVE',(1,3),(1,3),1,colors.black),
            #('LINEABOVE',(1,4),(1,4),1,colors.black),
            ('VALIGN', (0, 7), (0, 8), 'TOP'),
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ])
    c._argW[1] = 3.7 * inch

    elements.append(c)

    elements.append(FrameBreak())
    ###############################################################

    ###############################################################
    #Articles

    data = [['Art.nr.', 'Antal', 'Benämning', 'Pris st', 'Pris']]

    d = Table(
        data,
        style=[  #(col, row)
            ('GRID', (0, 1), (-1, -1), 2, colors.black),
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ])
    d._argW[0] = 1.0 * inch
    d._argW[1] = 1.0 * inch
    d._argW[2] = 3.0 * inch
    d._argW[3] = 1.0 * inch
    d._argW[4] = 1.0 * inch

    elements.append(d)

    #For varje artikel lagg till rad med information
    #MAX 15 articles

    existing_articles = int(workorder.article_set.all().count())
    max_articles = 15
    #Check if workorder has any articles

    #counter = 0
    for article in workorder.article_set.all():
        #counter += 1
        data = [[
            article.article_nr, article.quantity, article.description,
            remove_exponent(article.price),
            remove_exponent(article.price_total)
        ]]
        e = Table(
            data,
            style=[  #(col, row)
                ('GRID', (0, 0), (-1, -1), 2, colors.black),
                ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
            ])
        e._argW[0] = 1.0 * inch
        e._argW[1] = 1.0 * inch
        e._argW[2] = 3.0 * inch
        e._argW[3] = 1.0 * inch
        e._argW[4] = 1.0 * inch

        elements.append(e)

    #Calculate how many empty rows to fill up
    rest = (max_articles - existing_articles)
    for empty_articles in range(rest):
        data = [['', '', '', '', '']]
        e = Table(
            data,
            style=[  #(col, row)
                ('GRID', (0, 0), (-1, -1), 2, colors.black),
                ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
            ])
        e._argW[0] = 1.0 * inch
        e._argW[1] = 1.0 * inch
        e._argW[2] = 3.0 * inch
        e._argW[3] = 1.0 * inch
        e._argW[4] = 1.0 * inch

        elements.append(e)

    elements.append(FrameBreak())
    ###############################################################

    ###############################################################
    #Anmarkning
    #foo = "asfadf asdasd asd asdas sadsa d s dsd  s d sds ds sdsss sd sds ss sfadf asdasd asd asdas sadsa d s dsd  s d sds ds sdsss sd sds ss sfadf asdasd asd asdas sadsa d s dsd  s d sds ds !MAX 4 RADER!"

    p3 = Paragraph("%s" % workorder.comment, styleSheet["BodyText"])

    data = [['Anmärkning.'], [p3]]

    f = Table(
        data,
        style=[  #(col, row)
            #('GRID',(0,1),(-1,-1),2,colors.black),
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ])
    #f._argW[0]=1.0*inch
    f._argW[0] = 3.3 * inch

    elements.append(f)

    elements.append(FrameBreak())
    ###############################################################

    ###############################################################
    #Summering

    cal = workorder.workorder_calculations()

    # data = [['Fö. Matr..', cal['expendables']],
    # ['Summa', cal['sum']],
    # ['Moms:', cal['vat']],
    # ['Att betala:', cal['total']]]

    data = [['Summa', remove_exponent(cal['sum'])],
            ['Moms:', remove_exponent(cal['vat'])],
            ['Att betala:', remove_exponent(cal['total'])]]

    g = Table(
        data,
        style=[  #(col, row)
            ('GRID', (1, 0), (-1, -1), 2, colors.black),
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ])
    g._argW[1] = 1.5 * inch

    elements.append(g)

    elements.append(FrameBreak())
    ###############################################################

    ###############################################################
    #

    data = [["Orgnnr."], ['556877-4938']]

    h = Table(
        data,
        style=[  #(col, row)
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
        ])
    #f._argW[0]=1.6*inch

    elements.append(h)
    elements.append(FrameBreak())
    ###############################################################

    ###############################################################
    #
    data = [["Momsregnn/VAT"], ['SE5568774938']]

    h = Table(
        data,
        style=[  #(col, row)
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
        ])
    #f._argW[0]=1.6*inch

    elements.append(h)
    elements.append(FrameBreak())
    ###############################################################

    ###############################################################
    #
    data = [["Bankgiro"], ['830-5682']]

    h = Table(
        data,
        style=[  #(col, row)
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
        ])
    #f._argW[0]=1.6*inch

    elements.append(h)
    elements.append(FrameBreak())
    ###############################################################

    ###############################################################
    #
    data = [["Tel.nr"], ['013-141458']]

    h = Table(
        data,
        style=[  #(col, row)
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
        ])
    #f._argW[0]=1.6*inch

    elements.append(h)
    elements.append(FrameBreak())
    ###############################################################

    ###############################################################
    #
    data = [["Faxnr."], ['013-141458']]

    h = Table(
        data,
        style=[  #(col, row)
            ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
        ])
    #f._argW[0]=1.6*inch

    elements.append(h)
    ###############################################################

    # write the document to disk
    doc.build(elements)

    return response
Example #18
0
def generate(name, event):
    '''
    Retona pdf em memória (StringIO)

    name -- Nome do participante
    event -- Instância de event
    '''
    img_path = os.path.join(settings.PROJECT_ROOT, 'static_files/img/cert/')

    frame_header = Frame(x1=0, y1=0, width=700, height=460)
    frame_body = Frame(x1=100, y1=0, width=500, height=300)
    frame_sign = Frame(x1=50, y1=0, width=300, height=130)
    frame_logo = Frame(x1=400, y1=0, width=300, height=130)

    mainPage = PageTemplate(
        frames=[frame_header, frame_body, frame_sign, frame_logo], )

    dest = StringIO()
    doc = BaseDocTemplate(
        dest,
        pageTemplates=mainPage,
        pagesize=landscape(B5),
        rightMargin=72,
        leftMargin=72,
        topMargin=72,
        bottomMargin=18,
    )

    cert = []
    cert.append(get_image(os.path.join(img_path, 'logo2.png'), 5 * cm))

    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle('Body2', leading=22))
    styles.add(ParagraphStyle('NormalCenter', alignment=TA_CENTER))

    cert.append(
        Paragraph(u'<font size=25>Certificado de Participação</font>',
                  styles['Title']), )

    cert.append(FrameBreak())

    text = (u'Certificamos que <b>{name}</b> participou do '
            u'Encontro do {event}, '
            u'realizado em {local} com carga horária de {len} horas, '
            u'na qualidade de <b>participante</b>.')
    text = text.format(
        name=name,
        event=event,
        local=event.location,
        len=event.length,
    )

    cert.append(
        Paragraph(u'<font size=16.0>{0}</font>'.format(text),
                  styles['Body2']), )

    cert.append(FrameBreak())

    cert.append(get_image(event.signature.signature, 7 * cm))
    cert.append(
        Paragraph(u'_' * len(event.signature.name), styles['NormalCenter']), )
    cert.append(
        Paragraph(u'{0}'.format(event.signature.name),
                  styles['NormalCenter']), )
    cert.append(
        Paragraph(u'{0}'.format(event.signature.title),
                  styles['NormalCenter']), )
    cert.append(FrameBreak())

    cert.append(Paragraph(u'<b>Realização</b>', styles['NormalCenter']))
    cert.append(get_image(os.path.join(img_path, 'logo_pug.jpg'), 7 * cm))

    doc.build(cert)
    dest.seek(0)
    return dest
def run():
    from reportlab.platypus import  BaseDocTemplate, PageTemplate, Image, Frame, PageTemplate, \
                                    ShowBoundaryValue, SimpleDocTemplate, FrameBG, Paragraph, \
                                    FrameBreak
    from reportlab.lib.colors import toColor
    from reportlab.lib.utils import haveImages, _RL_DIR, rl_isfile, open_for_read, fileName2FSEnc, asNative
    from reportlab.lib.styles import getSampleStyleSheet
    styleSheet = getSampleStyleSheet()
    if haveImages:
        _GIF = os.path.join(testsFolder, 'pythonpowered.gif')
        if not rl_isfile(_GIF): _GIF = None
        _GAPNG = os.path.join(testsFolder, 'gray-alpha.png')
        if not rl_isfile(_GAPNG): _GAPNG = None
    else:
        _GIF = None
    if _GIF: _GIFFSEnc = fileName2FSEnc(_GIF)
    if _GAPNG: _GAPNGFSEnc = fileName2FSEnc(_GAPNG)

    _JPG = os.path.join(testsFolder, '..', 'docs', 'images', 'lj8100.jpg')
    if not rl_isfile(_JPG): _JPG = None

    doc = SimpleDocTemplate(outputfile('test_platypus_images.pdf'))
    story = [
        FrameBG(color=toColor('lightblue'), start='frame-permanent'),
    ]
    if _GIF:
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from a string GIF filename.",
                styleSheet['Italic']))
        story.append(Image(_GIF))
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from a utf8 GIF filename.",
                styleSheet['Italic']))
        #story.append(Image(fileName2FSEnc(_GIF)))
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from a string GIF file url.",
                styleSheet['Italic']))
        story.append(Image(getFurl(_GIF)))
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from an open GIF file.",
                styleSheet['Italic']))
        story.append(Image(open_for_read(_GIF, 'b')))
        story.append(FrameBreak())
        img = Image('http://www.reportlab.com/rsrc/encryption.gif')
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from a string GIF http url.",
                styleSheet['Italic']))
        story.append(img)
        story.append(FrameBreak())

    if _GAPNG:
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from a string PNGA filename.",
                styleSheet['Italic']))
        story.append(Image('rltw-icon-tr.png'))
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from a string PNG filename.",
                styleSheet['Italic']))
        story.append(Image(_GAPNG))
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from a utf8 PNG filename.",
                styleSheet['Italic']))
        #story.append(Image(fileName2FSEnc(_GAPNG)))
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from a string file PNG url.",
                styleSheet['Italic']))
        story.append(Image(getFurl(_GAPNG)))
        story.append(
            Paragraph(
                "Here is an Image flowable obtained from an open PNG file.",
                styleSheet['Italic']))
        story.append(Image(open_for_read(_GAPNG, 'b')))
        story.append(FrameBreak())

    if _JPG:
        img = Image(_JPG)
        story.append(
            Paragraph(
                "Here is an JPEG Image flowable obtained from a JPEG filename.",
                styleSheet['Italic']))
        story.append(img)
        story.append(
            Paragraph(
                "Here is an JPEG Image flowable obtained from an open JPEG file.",
                styleSheet['Italic']))
        img = Image(open_for_read(_JPG, 'b'))
        story.append(img)
        story.append(FrameBreak())
    doc.build(story)
Example #20
0
def pdf_create_page(monster_dict):
    """Create PDF pages of formatted monster cards.
    """
    m = monster_dict
    # Name, HP, Armor
    hp_label = None
    hp_value = None
    armor_label = None
    armor_value = None
    if m["hp"]:
        hp_label = "HP:"
        hp_value = m["hp"]
    if m["armor"]:
        armor_label = "Armor:"
        armor_value = m["armor"]
    name = m["name"].upper()
    words = list()
    for word in name.split(" "):
        words.append("%s<font size=14>%s</font>" % (word[0:1], word[1:]))
    name = " ".join(words)
    name = Paragraph(name, style_title)
    table = [[name, hp_label, hp_value], ["", armor_label, armor_value]]
    style = [
        ("LINEABOVE", (0, 0), (2, 0), 1, colors.black),
        ("LEFTPADDING", (0, 0), (2, 1), 0),
        ("RIGHTPADDING", (0, 0), (2, 1), 0),
        ("BOTTOMPADDING", (0, 0), (2, 1), 0),
        ("TOPPADDING", (0, 0), (2, 1), 0),
        ("TOPPADDING", (1, 0), (2, 0), (spacer / 2)),
        ("VALIGN", (0, 0), (2, 1), "TOP"),
        ("SPAN", (0, 0), (0, 1)),
        ("FONT", (1, 0), (2, 1), font_default, 8),
        ("ALIGN", (1, 0), (2, 1), "RIGHT"),
    ]
    elements.append(
        Table(table, [(3.15 * inch) - 8, 0.4 * inch, 0.2 * inch], style=style))
    # Tags
    monster_tags = combine_monster_tags(m, formatted=True)
    if monster_tags:
        elements.append(Paragraph(monster_tags, style_hang))
    # Weapon
    weapon = combine_weapon(m, formatted=True)
    if weapon:
        elements.append(Paragraph(weapon, style_hang))
    # Instincts
    if m["instincts"]:
        elements.append(Spacer(box_width, spacer))
        label = Paragraph("<b>Instincts</b>", style_default)
        items = list()
        for item in m["instincts"]:
            items.append(Paragraph(item, style_list))
        table = [[label, items]]
        style = [
            ("LEFTPADDING", (0, 0), (1, 0), 0),
            ("RIGHTPADDING", (0, 0), (1, 0), 0),
            ("BOTTOMPADDING", (0, 0), (1, 0), 0),
            ("TOPPADDING", (0, 0), (1, 0), 0),
            ("VALIGN", (0, 0), (1, 0), "TOP"),
        ]
        elements.append(
            Table(table, [0.675 * inch, (3.075 * inch) - 8], style=style))
    # Qualities
    if m["qualities"]:
        elements.append(Spacer(box_width, spacer))
        label = Paragraph("<b>Qualities</b>", style_default)
        items = list()
        for item in m["qualities"]:
            items.append(Paragraph(item, style_list))
        table = [[label, items]]
        style = [
            ("LEFTPADDING", (0, 0), (1, 0), 0),
            ("RIGHTPADDING", (0, 0), (1, 0), 0),
            ("BOTTOMPADDING", (0, 0), (1, 0), 0),
            ("TOPPADDING", (0, 0), (1, 0), 0),
            ("VALIGN", (0, 0), (1, 0), "TOP"),
        ]
        elements.append(
            Table(table, [0.675 * inch, (3.075 * inch) - 8], style=style))
    # Description
    elements.append(Spacer(box_width, spacer))
    table = [[Paragraph(m["description"], style_desc)]]
    style = [
        ("LINEABOVE", (0, 0), (0, 0), 0.5, colors.black),
        ("LINEBELOW", (0, 0), (0, 0), 0.5, colors.black),
        ("LEFTPADDING", (0, 0), (0, 0), 0),
        ("RIGHTPADDING", (0, 0), (0, 0), 0),
        ("BOTTOMPADDING", (0, 0), (0, 0), (spacer / 2)),
        ("TOPPADDING", (0, 0), (0, 0), (spacer / 2)),
        ("VALIGN", (0, 0), (0, 0), "TOP"),
    ]
    elements.append(Table(table, [box_width - 8], style=style))
    # References
    elements.append(Spacer(box_width, (spacer / 2)))
    reference = "%s of the %s" % (m["name"], m["setting"])
    elements.append(Paragraph(reference, style_ref))
    reference = None
    if m["reference"] and m["setting_reference"]:
        reference = "[DW %d, %d]" % (m["reference"], m["setting_reference"])
    elif m["setting_reference"]:
        reference = "[DW %d]" % (m["setting_reference"])
    if reference:
        elements.append(Paragraph(reference, style_ref))
    # Next card
    elements.append(FrameBreak())
Example #21
0
Este cuaderno tiene como objetivo eliminar las dificultades de comunicación entre la paciente y su acompañante con el equipo sanitario a lo largo de todo el ingreso en el Servicio de Obstetricia del HUMS, aumentando el confort y la seguridad en el parto y puerperio. 
Está formado por láminas con pictogramas. Cada cuaderno tiene una estructura diferente, según las necesidades que vemos los profesionales en cada parte del Servicio de Obstetricia.

<i>Servicio de Obstetricia H.U.M.S. 2017 (Versión 0.1)</i>'''

condiciones = '''Los pictogramas de <b>arasaac</b> (ver <u><a href=http://blog.arasaac.org/p/condiciones-de-uso_19.html>http://blog.arasaac.org/p/condiciones-de-uso_19.html</a></u>) son propiedad del Gobierno de Aragón.
 Sus recursos se publican bajo Licencia Creative Commons (BY-NC-SA).'''

materiales = '''Nuestros materiales, como <b>Proyecto de Mejora de la Calidad del H.U.M.S</b>, están
a disposición del personal sanitario que los quiera utilizar o mejorar, siempre que se cite su procedencia.'''

beta= '''Estos materiales están en fase de prueba y en ningún caso garantizan la perfecta comunicación entre la paciente y el personal sanitario. 
Es éste el que tiene que valorar la validez de la comunicación.'''

destino = 'pdfs/'
doc = Documento(fichero= destino + 'objetivos.pdf')
doc.titulo = 'Cuadernos para la comunicación'
estilo_texto = doc.stylesheet['Normal']
estilo_texto.spaceAfter = 6
doc.pagina_de_texto(texto)
doc.elements.append(FrameBreak())
doc.elements.append(Paragraph('Condiciones de uso', style=doc.stylesheet['Heading2']))
doc.elements.append(Paragraph(condiciones, style=estilo_texto))
doc.elements.append(Paragraph(materiales, style=estilo_texto))
doc.elements.append(Paragraph('Limitación de responsabilidad', style=doc.stylesheet['Heading2']))
doc.elements.append(Paragraph(beta, style=estilo_texto))

doc.generarwm('Servicio de Obstetricia. HUMS')


Example #22
0
def form_01(request_data):
    """
    форма Пасопрт здоровья Приказ Министерства здравоохранения и социального развития РФ от 12 апреля 2011 г. N 302н
    """
    ind_card = Card.objects.get(pk=request_data["card_pk"])
    ind = ind_card.individual
    ind_doc = Document.objects.filter(individual=ind, is_active=True)

    hospital_name = "ОГАУЗ \"Иркутская медикосанитарная часть № 2\""
    hospital_address = "г. Иркутс, ул. Байкальская 201"
    hospital_kod_ogrn = "1033801542576"
    health_passport_num = "1"  # номер id patient из базы

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

    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']
    document_polis = documents['polis']['num']
    document_snils = documents['snils']['num']

    indivudual_insurance_org = "38014_ИРКУТСКИЙ ФИЛИАЛ АО \"СТРАХОВАЯ КОМПАНИЯ \"СОГАЗ-МЕД\" (Область Иркутская)"
    individual_benefit_code = "_________"

    # card_attr = forms_func.get_card_attr(ind_card)
    ind_card_address = ind_card.main_address

    individual_work_organization = "Управление Федераньной службы по ветеринарному и фитосанитрному надзору по Иркутской области" \
                                   "и Усть-Ордынскому бурятскому автономному округу"  # реест организаций
    work_organization_okved = "91.5 - Обслуживание и ремонт компютерной и оргтехники, заправка картриджей" \
                              "обслуживание принтеров"
    individual_department = "отдел информационных технология, ораганизаци ремонта и обслуживания медицинского оборудования"
    individual_profession = "старший государственный таможенный инспектор"  # реест профессий

    list_result = [
        'Общ. анализ крови', 'Общ.анализ мочи', 'Глюкоза крови', 'Холестерин',
        'RW', 'Флюорография', 'ЭКГ', 'Спирометрия', 'УЗИ м/желёз (маммогр.)',
        'Аудиометрия', 'УЗИ огр.м/таза', 'Исслед. вестибулярн. аппарата',
        'Исслед.вибрационн. чувствительности', 'Острота зрения',
        'Рефрактометрия', 'Объём аккомодации', 'Исслед.бинокулярн. зрения',
        'Цветоощущение', 'Офтальмотонометрия', 'Биомикроскопия сред глаза',
        'Поля зрения', 'Бактериоскопия мазка', 'Офтальмоскопия глазного дня',
        'Мазок из зева и носа', 'Ретикулоциты', 'АЛК или КП в моче',
        'Метгемоглобины', 'Базальн. Зернист. Эритроцитов'
    ]  # список лабораторных, инструментальных исследований
    list_doctor = [
        'Терапевт', 'Психиатр', 'Нарколог', 'Гинеколог', 'Офтальмолог', 'Лор',
        'Невролог', 'Дерматолог', 'Хирург', 'Стоматолог'
    ]  # список врачей-специалистов

    for i in range(0, 3):
        list_doctor.append('')

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

    pdfmetrics.registerFont(
        TTFont('PTAstraSerifBold',
               os.path.join(FONTS_FOLDER, 'PTAstraSerif-Bold.ttf')))
    pdfmetrics.registerFont(
        TTFont('PTAstraSerifReg',
               os.path.join(FONTS_FOLDER, 'PTAstraSerif-Regular.ttf')))
    # http://www.cnews.ru/news/top/2018-12-10_rossijskim_chinovnikam_zapretili_ispolzovat
    # Причина PTAstraSerif использовать

    buffer = BytesIO()

    doc = SimpleDocTemplate(buffer,
                            pagesize=A4,
                            leftMargin=10 * mm,
                            rightMargin=10 * mm,
                            topMargin=10 * mm,
                            bottomMargin=10 * mm,
                            allowSplitting=1,
                            title="Форма {}".format("Паспорт здоровья"))
    width, height = landscape(A4)
    styleSheet = getSampleStyleSheet()
    style = styleSheet["Normal"]
    style.fontName = "PTAstraSerifBold"
    style.fontSize = 9
    style.leading = 6
    styleBold = deepcopy(style)
    styleBold.fontName = "PTAstraSerifBold"
    styleCenter = deepcopy(style)
    styleCenter.alignment = TA_CENTER
    styleCenterBold = deepcopy(styleBold)
    styleCenterBold.alignment = TA_CENTER
    styleJustified = deepcopy(style)
    styleJustified.alignment = TA_JUSTIFY
    styleJustified.spaceAfter = 4.5 * mm
    styleJustified.fontSize = 12
    styleJustified.leading = 4.5 * mm

    righ_frame = Frame(148.5 * mm,
                       0 * mm,
                       width=148.5 * mm,
                       height=210 * mm,
                       leftPadding=10 * mm,
                       bottomPadding=6,
                       rightPadding=10 * mm,
                       topPadding=6,
                       showBoundary=1)
    left_frame = Frame(0 * mm,
                       0 * mm,
                       width=148.5 * mm,
                       height=210 * mm,
                       leftPadding=10 * mm,
                       bottomPadding=6,
                       rightPadding=10 * mm,
                       topPadding=6,
                       showBoundary=1)
    doc.addPageTemplates(
        PageTemplate(id='TwoCol',
                     frames=[righ_frame, left_frame],
                     pagesize=landscape(A4)))

    space = 5.5 * mm
    objs = [
        Spacer(1, 3 * mm),
        Paragraph(
            '<font face="PTAstraSerifBold">Министерство здравоохранения Российской Федерации</font>',
            styleCenter),
        Spacer(1, 3 * mm),
        Paragraph(
            '<font face="PTAstraSerifBold"><u>{}</u></font>'.format(
                hospital_name), styleCenter),
        Spacer(1, 2 * mm),
        Paragraph(
            '<font face="PTAstraSerifReg"><font size=9>(наименование медицинской организации)</font></font>',
            styleCenter),
        Spacer(1, 3 * mm),
        Paragraph(
            '<font face="PTAstraSerifBold"><u>{}</u></font>'.format(
                hospital_address), styleCenter),
        Spacer(1, 5 * mm),
        Paragraph(
            '<font face="PTAstraSerifBold" size=12>Код ОГРН {}</font>'.format(
                hospital_kod_ogrn), styleCenter),
        Spacer(1, 10 * mm),
        Paragraph(
            '<font face="PTAstraSerifBold" size=12>ПАСПОРТ ЗДОРОВЬЯ РАБОТНИКА № <u>{}</u></font>'
            .format(health_passport_num), styleCenter),
        Spacer(1, space),
        Paragraph(
            '<font face="PTAstraSerifReg"size=10><u>{} года</u></font>'.format(
                pytils.dt.ru_strftime(u"%d %B %Y",
                                      inflected=True,
                                      date=datetime.datetime.now())),
            styleCenter),
        Spacer(1, 7),
        Paragraph(
            '<font face="PTAstraSerifReg" size=7>(дата оформления)</font>',
            styleCenter),
        Spacer(1, space),
        Paragraph(
            '<font face="PTAstraSerifReg">1.Фамилия, имя, отчество:'
            '<u>{}</u> </font>'.format(individual_fio), styleJustified),
        Paragraph(
            '<font face="PTAstraSerifReg">2.Пол: <u>{}</u> <img src="forms/img/FFFFFF-space.png" width="90" />'
            '3.Дата Рождения: <u>{}</u> </font>'.format(
                individual_sex, individual_date_born), styleJustified),
        Paragraph(
            '<font face="PTAstraSerifReg">4.Паспорт: серия <u>{}</u> <img src="forms/img/FFFFFF-space.png" width="25"/>'
            'номер: <u>{}</u></font>'.format(document_passport_serial,
                                             document_passport_num),
            styleJustified),
        Paragraph(
            '<font face="PTAstraSerifReg">Дата выдачи: <u>{}</u></font>'.
            format(document_passport_date_start), styleJustified),
        Paragraph(
            '<font face="PTAstraSerifReg"> Кем Выдан: <u>{}</u></font>'.format(
                document_passport_issued), styleJustified),
        Paragraph(
            '<font face="PTAstraSerifReg">5. Адрес регистрации по месту жительства (пребывания):'
            ' <u>{}</u></font>'.format(ind_card_address), styleJustified),
        Paragraph(
            '<font face="PTAstraSerifReg">6. Номер страхового полиса(ЕНП):'
            ' <u>{}</u></font>'.format(document_polis), styleJustified),
        Paragraph(
            '<font face="PTAstraSerifReg">7. Наименование работодателя:'
            ' <u>{}</u></font>'.format(individual_work_organization),
            styleJustified),
        Paragraph(
            '<font face="PTAstraSerifReg">7.1 Форма собственности и вид экономической деятельности '
            'работодателя по ОКВЭД: <u>{}</u></font>'.format(
                work_organization_okved), styleJustified),
        Paragraph(
            '<font face="PTAstraSerifReg">7.2  Наименование структурного подразделения (цех, участок, отдел):'
            ' <u> {} </u></font>'.format(individual_department),
            styleJustified),
        Paragraph(
            '<font face="PTAstraSerifReg">8. Профессия (должность) (в настоящее время):'
            ' <u>{}</u></font>'.format(individual_profession), styleJustified),
        FrameBreak(),
        Spacer(1, space),
        Paragraph('<font face="PTAstraSerifReg">12. Заключение:</font>',
                  styleJustified),
    ]
    styleT = deepcopy(style)
    styleT.alignment = TA_CENTER
    styleT.fontSize = 10
    styleT.leading = 4.5 * mm

    opinion = [
        [
            Paragraph(
                '<font face="PTAstraSerifReg">Заключение по результатам предварительного '
                'и периодического медицинского осмотра</font>', styleT),
            Paragraph(
                '<font face="PTAstraSerifReg">Дата получения заключения</font>',
                styleT),
            Paragraph(
                '<font face="PTAstraSerifReg"> Подпись профпатолога</font>',
                styleT)
        ],
    ]

    for i in range(0, 5):
        para = [
            Paragraph(
                '<font face="PTAstraSerifReg" size=11>Профпригоден/\nпрофнепригоден</font>',
                styleT)
        ]
        opinion.append(para)

    tbl = Table(opinion,
                colWidths=(48 * mm, 40 * mm, 40 * mm),
                hAlign='LEFT',
                style=[
                    ('GRID', (0, 0), (-1, -1), 0.7, colors.black),
                    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                    ('TOPPADDING', (0, 0), (-1, -1), 1.5 * mm),
                    ('BOTTOMPADDING', (0, 0), (-1, -1), 1.5 * mm),
                ])

    objs.append(tbl)

    objs.append(Spacer(1, 10 * mm))
    objs.append(
        Paragraph('<font face="PTAstraSerifReg">Для заметок:</font>',
                  styleJustified))

    s = "___________________________________________________________"
    for i in range(0, 6):
        objs.append(Spacer(1, 1 * mm))
        objs.append(
            Paragraph('<font face="PTAstraSerifReg">{}</font>'.format(s),
                      styleJustified))

    objs.append(NextPageTemplate("TwoCol"))
    objs.append(FrameBreak())
    objs.append(Spacer(1, 7 * mm))
    objs.append(
        Paragraph(
            '<font face="PTAstraSerifReg">11. Результаты лабораторных и инструментальных исследований'
            '</font>', styleJustified))

    tbl_result = [[
        Paragraph(
            '<font face="PTAstraSerifReg" size=11>Вид исследования</font>',
            styleT),
        Paragraph(
            '<font face="PTAstraSerifReg" size=11>Даты исследований</font>',
            styleT), '', '', '', ''
    ], ['', '', '', '', '', '']]

    styleTR = deepcopy(styleT)
    styleTR.alignment = TA_LEFT
    styleTR.fontSize = 11
    styleTR.spaceAfter = 12 * mm

    for i in list_result:
        para = [
            Paragraph('<font face="PTAstraSerifReg">{}</font>'.format(i),
                      styleTR)
        ]
        tbl_result.append(para)

    tbl = Table(tbl_result,
                colWidths=(41 * mm, 22 * mm, 17 * mm, 17 * mm, 17 * mm,
                           17 * mm),
                hAlign='LEFT',
                style=[
                    ('GRID', (0, 0), (-1, -1), 0.7, colors.black),
                    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                    ('TOPPADDING', (0, 0), (-1, -1), 0.01 * mm),
                    ('BOTTOMPADDING', (0, 0), (-1, -1), 0.01 * mm),
                    ('SPAN', (0, 0), (0, 1)),
                    ('SPAN', (1, 0), (-1, 0)),
                ])
    objs.append(tbl)

    objs.append(FrameBreak())
    objs.append(Spacer(1, 7 * mm))
    objs.append(
        Paragraph(
            '<font face="PTAstraSerifReg">9. Условия труда в настоящее время</font>',
            styleJustified))

    tbl_result = [[
        Paragraph(
            '<font face="PTAstraSerifReg" size=10>Наименование производственного фактора, вида работы с '
            'указанием пункта</font>', styleT),
        Paragraph(
            '<font face="PTAstraSerifReg" size=10>Стаж работы с фактором</font>',
            styleT),
    ]]
    for i in range(0, 4):
        para = ['', '']
        tbl_result.append(para)

    row_height = []
    for i in tbl_result:
        row_height.append(8 * mm)

    row_height[0] = None
    tbl = Table(tbl_result,
                colWidths=(75 * mm, 55 * mm),
                rowHeights=row_height,
                hAlign='LEFT',
                style=[
                    ('GRID', (0, 0), (-1, -1), 0.7, colors.black),
                    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                    ('TOPPADDING', (0, 0), (-1, -1), 0.01 * mm),
                    ('BOTTOMPADDING', (0, 0), (-1, -1), 0.01 * mm),
                    ('LEFTPADDING ', (0, 2), (0, -1), 0.1 * mm),
                    ('SPAN', (1, 1), (1, -1)),
                ])

    objs.append(tbl)

    objs.append(Spacer(1, 5 * mm))

    styleDoc = deepcopy(styleJustified)
    styleDoc.spaceAfter = 1 * mm
    objs.append(
        Paragraph(
            '<font face="PTAstraSerifReg">10. Заключения врачей - специалистов:</font>',
            styleDoc,
        ))
    tbl_result = [[
        Paragraph(
            '<font face="PTAstraSerifReg" size=11>Врач-специалист</font>',
            styleT),
        Paragraph(
            '<font face="PTAstraSerifReg" size=11>Даты исследований</font>',
            styleT), '', '', '', ''
    ], ['', '', '', '', '', '']]

    for i in list_doctor:
        para = [
            Paragraph('<font face="PTAstraSerifReg">{}</font>'.format(i),
                      styleTR)
        ]
        tbl_result.append(para)

    row_height = []
    for i in tbl_result:
        row_height.append(9 * mm)

    row_height[0] = None
    row_height[1] = None
    tbl = Table(tbl_result,
                colWidths=(41 * mm, 22 * mm, 17 * mm, 17 * mm, 17 * mm,
                           17 * mm),
                rowHeights=row_height,
                hAlign='LEFT',
                style=[
                    ('GRID', (0, 0), (-1, -1), 0.7, colors.black),
                    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                    ('TOPPADDING', (0, 0), (-1, -1), 0.01 * mm),
                    ('BOTTOMPADDING', (0, 0), (-1, -1), 0.01 * mm),
                    ('LEFTPADDING ', (0, 2), (0, -1), 0.1 * mm),
                    ('SPAN', (0, 0), (0, 1)),
                    ('SPAN', (1, 0), (-1, 0)),
                ])
    objs.append(tbl)

    doc.build(objs)

    pdf = buffer.getvalue()
    buffer.close()
    return pdf
Example #23
0
def generate_school_task_cards(data, filename="/tmp/school_tasks.pdf"):
    A4_width, A4_height = A4[0], A4[1]
    doc = SimpleDocTemplate(filename,
                            pagesize=A4,
                            rightMargin=0,
                            leftMargin=0,
                            topMargin=0,
                            bottomMargin=0)
    pdf_content = []
    frames = []
    w_counter = 0
    h_counter = 1
    width_position = 0
    same_line = True
    frame_w = 88.5 * mm
    frame_h = 140 * mm
    height_position = h_counter * frame_h
    frame_counter = 1
    for d in data:
        if A4_width - w_counter * frame_w > frame_w:
            if w_counter % 2 == 0:
                add = 0
            else:
                add = 40
            width_position = w_counter * frame_w + add
            same_line = True
        else:
            same_line = False
            w_counter = 0
            width_position = 0

        if not same_line:
            if A4_height - h_counter * frame_h >= frame_h:
                h_counter -= 1
                height_position = h_counter * frame_h
                same_line = True
        w_counter += 1

        frame_content = create_meeting_task_card(d)
        left_padding = (A4_width - 2 * 88.5 * mm - 40) / 2
        bottom_padding = (A4_height - 2 * 140 * mm) / 2
        frames.append(
            MyFrame(left_padding + width_position,
                    bottom_padding + height_position,
                    88.5 * mm,
                    140 * mm,
                    showBoundary=1))
        pdf_content.extend(frame_content)
        if len(frames) < len(data):
            pdf_content.append(FrameBreak())

        if frame_counter % 4 == 0 and len(data) - frame_counter > 0:
            w_counter = 0
            h_counter = 1
            same_line = True
            width_position = 0
            height_position = h_counter * frame_h
            pdf_content.append(NextPageTemplate("main_template"))
            pdf_content.append(PageBreak())

        frame_counter += 1

    template = PageTemplate(id='main_template', frames=frames)
    doc.addPageTemplates(template)
    doc.build(pdf_content)
Example #24
0
    def cevirPDF(self):
        for j in range(0,4):
            self.dersAdi = ""
            self.listSoru = []
            self.listA = []
            self.listB = []
            self.listC = []
            self.listD = []
            self.listE = []


            if j==0:
                self.kTürü='A'
            elif j==1:
                self.kTürü='B'
            elif j==2:
                self.kTürü='C'
            elif j==3:
                self.kTürü='D'
            Elements = []
            dAdi = 'Oturum-'+self.kTürü+'.pdf'
            doc = BaseDocTemplate(dAdi, showBoundary=0)

            for t in range(0,len(self.filesPath)):

                self.gExcel = pandas.read_excel(io=self.filesPath[t], parse_cols=2, index_col=2, sheetname=j)
                for i in range(0, 25):
                    self.listSoru.append(self.gExcel.index[i])
                self.gExcel = pandas.read_excel(io=self.filesPath[t], parse_cols=10, index_col=10, sheetname=j)
                for i in range(0, 25):
                    self.listA.append(self.gExcel.index[i])
                self.gExcel = pandas.read_excel(io=self.filesPath[t], parse_cols=11, index_col=11, sheetname=j)
                for i in range(0, 25):
                    self.listB.append(self.gExcel.index[i])
                self.gExcel = pandas.read_excel(io=self.filesPath[t], parse_cols=12, index_col=12, sheetname=j)
                for i in range(0, 25):
                    self.listC.append(self.gExcel.index[i])
                self.gExcel = pandas.read_excel(io=self.filesPath[t], parse_cols=13, index_col=13, sheetname=j)
                for i in range(0, 25):
                    self.listD.append(self.gExcel.index[i])
                self.gExcel = pandas.read_excel(io=self.filesPath[t], parse_cols=14, index_col=14, sheetname=j)
                for i in range(0, 25):
                    self.listE.append(self.gExcel.index[i])
                self.gExcel = pandas.read_excel(io=self.filesPath[t], parse_cols=28, index_col=28, sheetname=j)
                self.dersAdi = self.gExcel.index[0]
                self.gExcel = pandas.read_excel(io=self.filesPath[t], parse_cols=27, index_col=27, sheetname=j)
                self.dersAdik = self.gExcel.index[0]
                for i in range(0, 25):
                    self.listSoru[i] = self.listSoru[i].replace('\n', '<br />\n')

                print("Excelden çekildi.")


                styles = getSampleStyleSheet()
                pdfmetrics.registerFont(TTFont('Arial', 'Arial.ttf'))
                pdfmetrics.registerFont(TTFont('ArialBd', 'ArialBd.ttf'))

                # Baslık icin yazı ayarlarını yaptık
                titleStyle = styles["Title"]
                titleStyle.fontSize = 16
                titleStyle.fontName = 'ArialBd'
                titleStyle.leading = 65

                #Soru için font
                arStyle = styles["Heading1"]
                arStyle.fontSize = 10
                arStyle.fontName = 'ArialBd'
                arStyle.leading = 11
                arStyle.alignment = TA_JUSTIFY


                # Paragraflar için yazı tipini ayarladık
                parStyle = styles["Normal"]
                parStyle.fontSize = 10
                parStyle.fontName = 'Arial'
                parStyle.leading = 16
                #parStyle.alignment = TA_LEFT

                # Acıklama için yazı tipini ayarladık
                parStyle2 = styles["Normal"]
                parStyle2.fontSize = 10
                parStyle2.fontName = 'Arial'
                parStyle2.leading = 16
                parStyle2.alignment = TA_JUSTIFY

                # column için ölçüleri oluşturduk
                frameHeight = doc.height + 2 * inch
                firstPageHeight = 6 * inch
                firstPageBottom = frameHeight - firstPageHeight

                # Baslık frame'i
                frameT = Frame(2.7 * cm, firstPageBottom, doc.width, firstPageHeight)

                # Two column - burda oluşturduk
                frame1 = Frame(2.7 * cm,2.7 * cm,7.5 * cm,23.3 * cm, id='col1')
                frame2 = Frame(11.6 * cm,2.7 * cm,7.5 * cm,23.3 * cm, id='col2')

                Elements.append(Paragraph('<br />\n'+self.dersAdi, titleStyle))
                Elements.append(NextPageTemplate('TwoCol'))
                Elements.append(FrameBreak())

                for i in range(0, 25):
                    if i != 24:
                        index = self.listSoru[i].rfind("\n")
                        imagel=self.listSoru[i].find("&")
                        image2 = self.listSoru[i].rfind("&")
                        if imagel == -1 or image2 == -1:
                            if index == -1:
                                ptext = '<font fontSize=10 fontName=ArialBd>%s.&nbsp;&nbsp;</font>' % str(i+1)
                                pptext = ptext+self.listSoru[i]
                                Soru = Paragraph(pptext, arStyle)
                                Bosluk = Spacer(1, 0.3 * cm)
                                A = Paragraph('A)&nbsp;&nbsp;' + str(self.listA[i]), parStyle)
                                B = Paragraph('B)&nbsp;&nbsp;' + str(self.listB[i]), parStyle)
                                C = Paragraph('C)&nbsp;&nbsp;' + str(self.listC[i]), parStyle)
                                D = Paragraph('D)&nbsp;&nbsp;' + str(self.listD[i]), parStyle)
                                E = Paragraph('E)&nbsp;&nbsp;' + str(self.listE[i]), parStyle)
                                Bosluk2 = Spacer(1, self.bMiktari * cm)
                                Elements.append(KeepTogether([Soru, Bosluk, A, B, C, D, E, Bosluk2]))
                            else:
                                soru1 = self.listSoru[i][0:index]
                                soru2 = self.listSoru[i][index:]
                                ptext = '<font fontSize=10 fontName=ArialBd>%s.&nbsp;&nbsp;</font>' % str(i + 1)
                                pptext = ptext + soru1
                                Soruy1 = Paragraph(pptext, parStyle2)
                                Soruy2 = Paragraph(soru2,arStyle)
                                Bosluk = Spacer(1, 0.3 * cm)
                                A = Paragraph('A)&nbsp;&nbsp;' + str(self.listA[i]), parStyle)
                                B = Paragraph('B)&nbsp;&nbsp;' + str(self.listB[i]), parStyle)
                                C = Paragraph('C)&nbsp;&nbsp;' + str(self.listC[i]), parStyle)
                                D = Paragraph('D)&nbsp;&nbsp;' + str(self.listD[i]), parStyle)
                                E = Paragraph('E)&nbsp;&nbsp;' + str(self.listE[i]), parStyle)
                                Bosluk2 = Spacer(1, self.bMiktari * cm)
                                Elements.append(KeepTogether([Soruy1,Soruy2, Bosluk, A, B, C, D, E, Bosluk2]))
                        else:
                            imageAd=self.listSoru[i][imagel+1:image2]
                            imageK=self.listSoru[i][imagel:image2+1]
                            soru1 = self.listSoru[i][0:index]
                            soruBas = soru1[0:imagel]
                            soruSon = soru1[image2+1:]
                            soru2 = self.listSoru[i][index:]
                            imagePath="C:\Image\\" + imageAd
                            im = Image(imagePath,7.5 * cm, 5*cm)
                            ySoru = self.listSoru[i]
                            yySoru = ySoru.replace(imageK,"")
                            if index == -1:
                                ptext = Paragraph(str(i+1)+".&nbsp;&nbsp;",arStyle)
                                Soru = Paragraph(yySoru, arStyle)
                                Bosluk = Spacer(1, 0.3 * cm)
                                A = Paragraph('A)&nbsp;&nbsp;' + str(self.listA[i]), parStyle)
                                B = Paragraph('B)&nbsp;&nbsp;' + str(self.listB[i]), parStyle)
                                C = Paragraph('C)&nbsp;&nbsp;' + str(self.listC[i]), parStyle)
                                D = Paragraph('D)&nbsp;&nbsp;' + str(self.listD[i]), parStyle)
                                E = Paragraph('E)&nbsp;&nbsp;' + str(self.listE[i]), parStyle)
                                Bosluk2 = Spacer(1, self.bMiktari * cm)
                                Elements.append(KeepTogether([ptext,im,Soru, Bosluk, A, B, C, D, E, Bosluk2]))
                            else:

                                ptext = '<font fontSize=10 fontName=ArialBd>%s.&nbsp;&nbsp;</font>' % str(i + 1)
                                pptext = ptext + soruBas
                                soruy1Bas = Paragraph(pptext, parStyle2)
                                soruy1Son = Paragraph(soruSon,parStyle2)
                                Soruy2 = Paragraph(soru2,arStyle)
                                Bosluk = Spacer(1, 0.3 * cm)
                                A = Paragraph('A)&nbsp;&nbsp;' + str(self.listA[i]), parStyle)
                                B = Paragraph('B)&nbsp;&nbsp;' + str(self.listB[i]), parStyle)
                                C = Paragraph('C)&nbsp;&nbsp;' + str(self.listC[i]), parStyle)
                                D = Paragraph('D)&nbsp;&nbsp;' + str(self.listD[i]), parStyle)
                                E = Paragraph('E)&nbsp;&nbsp;' + str(self.listE[i]), parStyle)
                                Bosluk2 = Spacer(1, self.bMiktari * cm)
                                Elements.append(KeepTogether([soruy1Bas,im,soruy1Son,Soruy2, Bosluk, A, B, C, D, E, Bosluk2]))
                    else:
                        index = self.listSoru[i].rfind("\n")
                        imagel = self.listSoru[i].find("&")
                        image2 = self.listSoru[i].rfind("&")
                        if imagel == -1 or image2 == -1:
                            if index == -1:
                                ptext = '<font fontSize=10 fontName=ArialBd>%s.&nbsp;&nbsp;</font>' % str(i + 1)
                                pptext = ptext + self.listSoru[i]
                                Soru = Paragraph(pptext, arStyle)
                                Bosluk = Spacer(1, 0.3 * cm)
                                A = Paragraph('A)&nbsp;&nbsp;' + str(self.listA[i]), parStyle)
                                B = Paragraph('B)&nbsp;&nbsp;' + str(self.listB[i]), parStyle)
                                C = Paragraph('C)&nbsp;&nbsp;' + str(self.listC[i]), parStyle)
                                D = Paragraph('D)&nbsp;&nbsp;' + str(self.listD[i]), parStyle)
                                E = Paragraph('E)&nbsp;&nbsp;' + str(self.listE[i]), parStyle)
                                Bosluk2 = Spacer(1, self.bMiktari * cm)
                                tBitti = Paragraph(self.dersAdi + ' TESTİ BİTTİ.', arStyle)
                                Elements.append(KeepTogether([Soru, Bosluk, A, B, C, D, E, Bosluk2,tBitti]))

                            else:
                                soru1 = self.listSoru[i][0:index]
                                soru2 = self.listSoru[i][index:]
                                ptext = '<font fontSize=10 fontName=ArialBd>%s.&nbsp;&nbsp;</font>' % str(i + 1)
                                pptext = ptext + soru1
                                Soruy1 = Paragraph(pptext, parStyle2)
                                Soruy2 = Paragraph(soru2, arStyle)
                                Bosluk = Spacer(1, 0.3 * cm)
                                A = Paragraph('A)&nbsp;&nbsp;' + str(self.listA[i]), parStyle)
                                B = Paragraph('B)&nbsp;&nbsp;' + str(self.listB[i]), parStyle)
                                C = Paragraph('C)&nbsp;&nbsp;' + str(self.listC[i]), parStyle)
                                D = Paragraph('D)&nbsp;&nbsp;' + str(self.listD[i]), parStyle)
                                E = Paragraph('E)&nbsp;&nbsp;' + str(self.listE[i]), parStyle)
                                Bosluk2 = Spacer(1, self.bMiktari * cm)
                                tBitti = Paragraph(self.dersAdi + ' TESTİ BİTTİ.', arStyle)
                                Elements.append(KeepTogether([Soruy1, Soruy2, Bosluk, A, B, C, D, E, Bosluk2,tBitti]))

                        else:
                            imageAd = self.listSoru[i][imagel + 1:image2]
                            imageK = self.listSoru[i][imagel:image2 + 1]
                            soru1 = self.listSoru[i][0:index]
                            soruBas = soru1[0:imagel]
                            soruSon = soru1[image2 + 1:]
                            soru2 = self.listSoru[i][index:]
                            imagePath = "D:\İçerikler\Python\ExcelToWord\Image\\" + imageAd
                            im = Image(imagePath, 7.5 * cm, 5 * cm)
                            ySoru = self.listSoru[i]
                            yySoru = ySoru.replace(imageK, "")
                            if index == -1:
                                ptext = Paragraph(str(i + 1) + ".&nbsp;&nbsp;", arStyle)
                                Soru = Paragraph(yySoru, arStyle)
                                Bosluk = Spacer(1, 0.3 * cm)
                                A = Paragraph('A)&nbsp;&nbsp;' + str(self.listA[i]), parStyle)
                                B = Paragraph('B)&nbsp;&nbsp;' + str(self.listB[i]), parStyle)
                                C = Paragraph('C)&nbsp;&nbsp;' + str(self.listC[i]), parStyle)
                                D = Paragraph('D)&nbsp;&nbsp;' + str(self.listD[i]), parStyle)
                                E = Paragraph('E)&nbsp;&nbsp;' + str(self.listE[i]), parStyle)
                                Bosluk2 = Spacer(1, self.bMiktari * cm)
                                tBitti = Paragraph(self.dersAdi + ' TESTİ BİTTİ.', arStyle)
                                Elements.append(KeepTogether([ptext, im, Soru, Bosluk, A, B, C, D, E, Bosluk2,tBitti]))

                            else:

                                ptext = '<font fontSize=10 fontName=ArialBd>%s.&nbsp;&nbsp;</font>' % str(i + 1)
                                pptext = ptext + soruBas
                                soruy1Bas = Paragraph(pptext, parStyle2)
                                soruy1Son = Paragraph(soruSon, parStyle2)
                                Soruy2 = Paragraph(soru2, arStyle)
                                Bosluk = Spacer(1, 0.3 * cm)
                                A = Paragraph('A)&nbsp;&nbsp;' + str(self.listA[i]), parStyle)
                                B = Paragraph('B)&nbsp;&nbsp;' + str(self.listB[i]), parStyle)
                                C = Paragraph('C)&nbsp;&nbsp;' + str(self.listC[i]), parStyle)
                                D = Paragraph('D)&nbsp;&nbsp;' + str(self.listD[i]), parStyle)
                                E = Paragraph('E)&nbsp;&nbsp;' + str(self.listE[i]), parStyle)
                                Bosluk2 = Spacer(1, self.bMiktari * cm)
                                tBitti = Paragraph(self.dersAdi+' TESTİ BİTTİ.',arStyle)
                                Elements.append(KeepTogether([soruy1Bas, im, soruy1Son, Soruy2, Bosluk, A, B, C, D, E, Bosluk2,tBitti]))


                Elements.append(NextPageTemplate('Title'))
                Elements.append(PageBreak())

                doc.addPageTemplates([PageTemplate(id='Title', frames=[frameT, frame1, frame2], onPage=self.addPageNumber),
                                      PageTemplate(id='TwoCol', frames=[frame1, frame2], onPage=self.addPageNumber), ])

                self.listSoru.clear()
                self.listA.clear()
                self.listB.clear()
                self.listC.clear()
                self.listD.clear()
                self.listE.clear()

            doc.build(Elements)

            print("PDF'e çevrildi.")
def create_annual_rental_fee_awaiting_payment_confirmation(
        invoice_buffer, annual_rental_fee):
    global DPAW_HEADER_LOGO
    DPAW_HEADER_LOGO = os.path.join(settings.PROJECT_DIR, 'payments', 'static',
                                    'payments', 'img', 'dbca_logo.jpg')
    every_page_frame = Frame(PAGE_MARGIN,
                             PAGE_MARGIN + 250,
                             PAGE_WIDTH - 2 * PAGE_MARGIN,
                             PAGE_HEIGHT - 450,
                             id='EveryPagesFrame',
                             showBoundary=0)
    remit_frame = Frame(PAGE_MARGIN,
                        PAGE_MARGIN,
                        PAGE_WIDTH - 2 * PAGE_MARGIN,
                        PAGE_HEIGHT - 600,
                        id='RemitFrame',
                        showBoundary=0)
    every_page_template = PageTemplate(id='EveryPages',
                                       frames=[every_page_frame, remit_frame],
                                       onPage=_create_header)
    doc = BaseDocTemplate(invoice_buffer,
                          pageTemplates=[every_page_template],
                          pagesize=A4)

    # this is the only way to get data into the onPage callback function
    # doc.invoice = invoice
    # doc.proposal = proposal
    doc.approval = annual_rental_fee.approval
    doc.annual_rental_fee = annual_rental_fee

    # owner = invoice.owner

    elements = []
    #elements.append(Spacer(1, SECTION_BUFFER_HEIGHT * 5))

    # Draw Products Table
    invoice_table_style = TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP'),
                                      ('GRID', (0, 0), (-1, -1), 1,
                                       colors.black),
                                      ('ALIGN', (0, 0), (-1, -1), 'LEFT')])
    # items = invoice.order.lines.all()
    items = annual_rental_fee.lines
    # discounts = invoice.order.basket_discounts
    # if invoice.text:
    #     elements.append(Paragraph(invoice.text, styles['Left']))
    #     elements.append(Spacer(1, SECTION_BUFFER_HEIGHT * 2))
    data = [['Item', 'Product', 'Quantity', 'Unit Price', 'Total']]
    val = 1
    s = styles["BodyText"]
    s.wordWrap = 'CJK'

    total_amount = 0.0
    # for item in items:
    for val, item in enumerate(items):
        amount = float(item['price_incl_tax']) * item['quantity']
        data.append([
            val,
            Paragraph(item['ledger_description'], s), item['quantity'],
            currency(item['price_incl_tax']),
            currency(amount)
        ])
        total_amount += amount
        val += 1

    data.append(['', 'Total', '', '', currency(total_amount)])

    t = Table(data,
              style=invoice_table_style,
              hAlign='LEFT',
              colWidths=(
                  0.7 * inch,
                  None,
                  0.7 * inch,
                  1.0 * inch,
                  1.0 * inch,
              ))
    elements.append(t)
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT * 2))
    # /Products Table
    # if invoice.payment_status != 'paid' and invoice.payment_status != 'over_paid':
    #     elements.append(Paragraph(settings.INVOICE_UNPAID_WARNING, styles['Left']))

    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT * 6))

    # Remitttance Frame
    elements.append(FrameBreak())
    boundary = BrokenLine(PAGE_WIDTH - 2 * (PAGE_MARGIN * 1.1))
    elements.append(boundary)
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    # remittance = Remittance(HEADER_MARGIN,HEADER_MARGIN - 10, proposal, invoice)
    # elements.append(remittance)
    #_create_remittance(invoice_buffer,doc)
    doc.build(elements)

    return invoice_buffer
Example #26
0
File: pdf.py Project: tawazz/ledger
def _create_invoice(invoice_buffer, invoice):
    every_page_frame = Frame(PAGE_MARGIN,
                             PAGE_MARGIN + 250,
                             PAGE_WIDTH - 2 * PAGE_MARGIN,
                             PAGE_HEIGHT - 430,
                             id='EveryPagesFrame',
                             showBoundary=0)
    remit_frame = Frame(PAGE_MARGIN,
                        PAGE_MARGIN,
                        PAGE_WIDTH - 2 * PAGE_MARGIN,
                        PAGE_HEIGHT - 600,
                        id='RemitFrame',
                        showBoundary=0)
    every_page_template = PageTemplate(id='EveryPages',
                                       frames=[every_page_frame, remit_frame],
                                       onPage=_create_header)

    doc = BaseDocTemplate(invoice_buffer,
                          pageTemplates=[every_page_template],
                          pagesize=A4)

    # this is the only way to get data into the onPage callback function
    doc.invoice = invoice
    owner = invoice.owner

    elements = []
    #elements.append(Spacer(1, SECTION_BUFFER_HEIGHT * 5))

    # Draw Products Table
    invoice_table_style = TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP'),
                                      ('GRID', (0, 0), (-1, -1), 1,
                                       colors.black),
                                      ('ALIGN', (0, 0), (-1, -1), 'LEFT')])
    items = invoice.order.lines.all()
    discounts = invoice.order.basket_discounts
    data = [['Item', 'Product', 'Quantity', 'Unit Price', 'GST', 'Amount']]
    val = 1
    for item in items:
        data.append([
            val,
            Paragraph(item.description, styles['Normal']), item.quantity,
            '${}'.format(item.line_price_before_discounts_excl_tax),
            '${}'.format(item.line_price_before_discounts_incl_tax -
                         item.line_price_before_discounts_excl_tax),
            '${}'.format(item.line_price_before_discounts_incl_tax)
        ])
        val += 1
    # Discounts
    data.append(['', '', '', '', '', ''])
    for discount in discounts:
        data.append(
            ['', discount.offer, '', '', '', '-${}'.format(discount.amount)])
        val += 1
    t = Table(data, style=invoice_table_style, hAlign='LEFT')
    t._argW[1] = 3.4 * inch
    t._argW[2] = 0.7 * inch
    for x in range(3, 6):
        t._argW[x] = 1.0 * inch
    elements.append(t)
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT * 2))
    # /Products Table
    elements.append(
        Paragraph(
            'Your application cannot be processed until payment is received.',
            styles['Left']))

    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT * 6))

    # Remitttance Frame
    elements.append(FrameBreak())
    boundary = BrokenLine(PAGE_WIDTH - 2 * (PAGE_MARGIN * 1.1))
    elements.append(boundary)
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    remittance = Remittance(HEADER_MARGIN, HEADER_MARGIN - 10, invoice)
    elements.append(remittance)
    #_create_remittance(invoice_buffer,doc)
    doc.build(elements)

    return invoice_buffer
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 #28
0
def layout(data,page_size,imageDb_path,output_dir,file_name):
	def add_image(path,x,y,size):
		#setting image vars
		image_path = path
		x = x*mm
		y = y*mm
		size_x = size[0]*mm
		size_y = size[1]*mm

		#setting frame
		image_frame = Frame(x,y,size_x,size_y,id=str(path),bottomPadding=0,topPadding=0,leftPadding=0)
		page_frames.append(image_frame)

		#setting object in frame:
		image = Image(image_path,size_x,size_y,mask=[0,255, 0,255, 0,255])
		page_elements.append(image)
		page_elements.append(FrameBreak())

	def add_price(price,x,y,scale = 1):
		price_rub,price_kop = price.split('.')[0],price.split('.')[1]
		price_obj = flow.Price_std(price_rub,price_kop,scale=scale)
		size_x,size_y = price_obj.content_width,price_obj.content_height
		price_frame = Frame(x*mm,y*mm,size_x,size_y,id=str('price_main'),bottomPadding=0,topPadding=0,leftPadding=0)
		page_frames.append(price_frame)

		page_elements.append(price_obj)
		page_elements.append(FrameBreak())

	def add_text(header,body,x,y,scale = 1):
		text_obj = flow.offer_text(header,body,scale = scale)
		size_x,size_y = text_obj.content_width,text_obj.content_height
		text_frame = Frame(x*mm,y*mm,size_x,size_y,id=str('text_main'),bottomPadding=0,topPadding=0,leftPadding=0)
		page_frames.append(text_frame)

		page_elements.append(text_obj)
		page_elements.append(FrameBreak())

	def add_text_wback(content,x,y,size):
		obj = flow.text_wback(content,x,y,size)
		size_x,size_y = size
		obj_frame = Frame(x*mm,y*mm,size_x,size_y,id=str('obj'),bottomPadding=0,topPadding=0,leftPadding=0)
		page_frames.append(obj_frame)

		page_elements.append(obj)
		page_elements.append(FrameBreak())
	
	def add_h_dotted_line(x,y,width):
		obj = flow.HRFlowable_dotted(width)
		obj_frame = Frame(x,y,width,1,id=str('h_dotted_line'),bottomPadding=0,topPadding=0,leftPadding=0)
		page_frames.append(obj_frame)

		page_elements.append(obj)
		page_elements.append(FrameBreak())
	
	def add_v_dotted_line(x,y,lheight):
		obj = flow.VRFlowable_dotted(lheight)
		obj_frame = Frame(x,y,0,lheight,id=str('v_dotted_line'),bottomPadding=0,topPadding=0,leftPadding=0)
		page_frames.append(obj_frame)
		
		page_elements.append(obj)
		page_elements.append(FrameBreak())

	def add_text_string(x,y,font,font_size,string,color = '#FFFFFF'):
		obj = flow.text_string(string,font,font_size,color)
		size_x,size_y = obj.content_width,obj.content_height
		obj_frame = Frame(x*mm,y*mm,size_x,size_y,id=str('text_string'),bottomPadding=0,topPadding=0,leftPadding=0)

		page_frames.append(obj_frame)

		page_elements.append(obj)
		page_elements.append(FrameBreak())

	#page settings
	page_size_x = page_size[0]*mm
	page_size_y = page_size[1]*mm
	page_left_margin = 0
	page_right_margin = 0

	#page setting containers
	page_frames = []
	page_elements = []

	#layouting
	for name,props in data.iteritems():
		#print props
		if props['type'] == 'image':
			#setting image vars
			image_path = props['file_name']
			image_x = props['x']*mm
			image_y = props['y']*mm
			size_x = props['size'][0]*mm
			size_y = props['size'][1]*mm

			#setting frame
			image_frame = Frame(image_x,image_y,size_x,size_y,id=str(name),bottomPadding=0,topPadding=0,leftPadding=0)
			page_frames.append(image_frame)

			#setting object in frame:
			image = Image(image_path,size_x,size_y)
			page_elements.append(image)
			page_elements.append(FrameBreak())


		elif props['type'] == 'box' or props['type'] == 'frame':
			x = props['x']*mm
			y = props['y']*mm
			size_x = props['size'][0]*mm
			size_y = props['size'][1]*mm
			image_frame = Frame(x,y,size_x,size_y,id=str(name),bottomPadding=0,topPadding=0,leftPadding=0)
			page_frames.append(image_frame)
			page_elements.append(FrameBreak())

		elif props['type'] == 'h_dotted_line':
			x = props['x']*mm
			y = props['y']*mm
			size_x = props['width']
			size_y = 5*mm
			add_h_dotted_line(x,y,size_x)
		elif props['type'] == 'v_dotted_line':
			x = props['x']*mm
			y = props['y']*mm
			size_y = props['height']
			add_v_dotted_line(x,y,size_y)

	for name,props in data.iteritems():
		if props['type'] == 'price':
			value = props['value']
			x = props['x']
			y = props['y']
			scale = props['scale']
			add_price(value,x,y,scale)

		if props['type'] == 'logo':
			#setting image vars
			image_path = props['file_name']
			image_x = props['x']*mm
			image_y = props['y']*mm
			size_x = int(props['size'][0])*mm
			size_y = int(props['size'][1])*mm

			#setting frame
			image_frame = Frame(image_x,image_y,size_x,size_y,id=str(name),bottomPadding=0,topPadding=0,leftPadding=0)
			page_frames.append(image_frame)

			#setting object in frame:
			image = Image(image_path,size_x,size_y)
			page_elements.append(image)
			page_elements.append(FrameBreak())

	for name,props in data.iteritems():
		if props['type'] == 'offer text':
			header = props['header']
			body = props['body']
			body = body.replace('Нугар','Нуга')
			x = props['x']
			y = props['y']
			scale = props['scale']
			add_text(header,body,x,y,scale)

		if props['type'] == 'text_string':
			string = props['text']
			#print 'layouting',string
			font = props['font']
			font_size = props['font size']
			x = props['x']
			y = props['y']
			try:
				color = props['color']
				add_text_string(x,y,font,font_size,string,color)
			except:
				add_text_string(x,y,font,font_size,string)

		elif props['type'] == 'text_wback2':
			x = object_data['x']
			y = object_data['y']
			size = object_data['size']
			content = object_data['content']
			add_text_wback(content,x,y,size)

		elif props['type'] == 'frame2':
			for object_data in  props['frame content']:
				if object_data['type'] == 'image':
					x = object_data['x']
					y = object_data['y']
					size = object_data['size']
					path = object_data['file_name']
					add_image(path,x,y,size)
				if object_data['type'] == 'price':
					#print 'price layouting'
					value = object_data['value']
					x = object_data['x']
					y = object_data['y']
					size = object_data['size']
					add_price(value,x,y,scale = 3)
					if verbose == True:
						print 'price:',value,x,y,page_elements
				if object_data['type'] == 'offer text':
					x = object_data['x']
					y = object_data['y']
					size = object_data['size']
					header = object_data['header']
					body = object_data['body']
					add_text(header,body,x,y,size,scale = 1.8)




	# Building page
	current_page = PageTemplate(frames=page_frames)
	doc = BaseDocTemplate(os.path.join(output_dir,str(file_name)),
		pageTemplates=current_page,
		leftMargin=0,
		rightMargin=0,
		topMargin=0,
		bottomMargin=0,
		showBoundary=0,
		cropMarks = False,
		colorSpace='RGB',
		pagesize=(page_size_x,page_size_y))
	doc.addPageTemplates([PageTemplate(id='Test',frames=page_frames)])
	doc.build(page_elements)
Example #29
0
def _create_invoice(invoice_buffer, invoice, proposal):

    global DPAW_HEADER_LOGO
    #    if  cols_var["TEMPLATE_GROUP"] == 'rottnest':
    #        DPAW_HEADER_LOGO = os.path.join(settings.BASE_DIR, 'mooring', 'static', 'mooring', 'img','logo-rottnest-island-sm.png')
    #    else:
    #        DPAW_HEADER_LOGO = os.path.join(settings.BASE_DIR, 'ledger', 'payments','static', 'payments', 'img','dbca_logo.jpg')
    DPAW_HEADER_LOGO = os.path.join(settings.PROJECT_DIR, 'payments', 'static',
                                    'payments', 'img', 'dbca_logo.jpg')

    every_page_frame = Frame(PAGE_MARGIN,
                             PAGE_MARGIN + 250,
                             PAGE_WIDTH - 2 * PAGE_MARGIN,
                             PAGE_HEIGHT - 450,
                             id='EveryPagesFrame',
                             showBoundary=0)
    remit_frame = Frame(PAGE_MARGIN,
                        PAGE_MARGIN,
                        PAGE_WIDTH - 2 * PAGE_MARGIN,
                        PAGE_HEIGHT - 600,
                        id='RemitFrame',
                        showBoundary=0)
    every_page_template = PageTemplate(id='EveryPages',
                                       frames=[every_page_frame, remit_frame],
                                       onPage=_create_header)

    doc = BaseDocTemplate(invoice_buffer,
                          pageTemplates=[every_page_template],
                          pagesize=A4)

    # this is the only way to get data into the onPage callback function
    doc.invoice = invoice
    doc.proposal = proposal
    owner = invoice.owner

    elements = []
    #elements.append(Spacer(1, SECTION_BUFFER_HEIGHT * 5))

    # Draw Products Table
    invoice_table_style = TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP'),
                                      ('GRID', (0, 0), (-1, -1), 1,
                                       colors.black),
                                      ('ALIGN', (0, 0), (-1, -1), 'LEFT')])
    items = invoice.order.lines.all()
    discounts = invoice.order.basket_discounts
    if invoice.text:
        elements.append(Paragraph(invoice.text, styles['Left']))
        elements.append(Spacer(1, SECTION_BUFFER_HEIGHT * 2))
    data = [['Item', 'Product', 'Quantity', 'Unit Price', 'Total']]
    val = 1
    s = styles["BodyText"]
    s.wordWrap = 'CJK'

    for item in items:
        data.append([
            val,
            Paragraph(item.description, s), item.quantity,
            currency(item.unit_price_incl_tax),
            currency(item.line_price_before_discounts_incl_tax)
        ])
        val += 1
    # Discounts
    data.append(['', '', '', ''])
    for discount in discounts:
        data.append(
            ['', discount.offer, '', '', '-${}'.format(discount.amount)])
        val += 1
    t = Table(data,
              style=invoice_table_style,
              hAlign='LEFT',
              colWidths=(
                  0.7 * inch,
                  None,
                  0.7 * inch,
                  1.0 * inch,
                  1.0 * inch,
              ))
    elements.append(t)
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT * 2))
    # /Products Table
    if invoice.payment_status != 'paid' and invoice.payment_status != 'over_paid':
        elements.append(
            Paragraph(settings.INVOICE_UNPAID_WARNING, styles['Left']))

    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT * 6))

    # Remitttance Frame
    elements.append(FrameBreak())
    boundary = BrokenLine(PAGE_WIDTH - 2 * (PAGE_MARGIN * 1.1))
    elements.append(boundary)
    elements.append(Spacer(1, SECTION_BUFFER_HEIGHT))

    remittance = Remittance(HEADER_MARGIN, HEADER_MARGIN - 10, proposal,
                            invoice)
    elements.append(remittance)
    #_create_remittance(invoice_buffer,doc)
    doc.build(elements)

    return invoice_buffer
Example #30
0
from tutorial.myreportlib import *

from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.pagesizes import letter
from reportlab.platypus import Paragraph, SimpleDocTemplate, FrameBreak

text_page1 = 'Hello World!'
text_page2 = 'How are you.'

style = getSampleStyleSheet()['Normal']

flowables = []
flowables.append(Paragraph(text_page1, style))
flowables.append(FrameBreak())
flowables.append(Paragraph(text_page2, style))

doc = SimpleDocTemplate(pdf_filename, pagesize=letter)
doc.build(flowables)