Example #1
0
    def __init__(self, output):
        self.base_path = os.path.abspath(os.path.dirname(__file__))
        self.width, self.height = portrait(A4)
        self.y = self.height
        self.margin = 2.5
        self.x = self.margin
        self.pdf = output or tempfile.TemporaryFile()
        times_new_roman = os.path.join(self.base_path, "templates", "fonts", "times.ttf")
        times_new_roman_bold = os.path.join(self.base_path, "templates", "fonts", "timesbd.ttf")
        pdfmetrics.registerFont(TTFont('Times New Roman', times_new_roman))
        pdfmetrics.registerFont(TTFont('Times New Roman Bold', times_new_roman_bold))

        self.canvas = canvas.Canvas(self.pdf, pagesize=portrait(A4))
def generate_pages(card_sizes,cards, filename="placecards.pdf", custom_font = None):
    pagesize = pagesizes.portrait( ( 8.5 * pagesizes.inch, 11 * pagesizes.inch))
    pdf = Canvas(filename, pagesize=pagesize,pdfVersion=(1,4))
    pdf.setAuthor('placecardboardgenerate.py')
    pdf.setSubject('wedding placecards')
    pdf.setTitle('Placecards for Wedding Reception')
    pdf.setKeywords(('wedding', 'placecards'))
    if custom_font is not None:
        pdf.setFont(custom_font,14)#FIXME don't hardcode font size
            
    adjusted_card_sizes = (card_sizes[0] * pagesizes.inch, card_sizes[1] * pagesizes.inch)
    card_printer = CardPrinter(pagesize,adjusted_card_sizes)

    (cardsPerRow,rowsPerPage) = (card_printer.cards_per_row, card_printer.cards_per_column)

    (page_width, page_height) = pagesize

    groupedCards = group_cards(cards, cardsPerRow, rowsPerPage)
    for (page_index,pageOfCards) in enumerate(groupedCards):
        if custom_font is not None:
            pdf.setFont(custom_font,14)#FIXME don't hardcode font size
        for (row_index,rowOfCards) in enumerate(pageOfCards):
            for (column_index,card) in enumerate(rowOfCards):
                card_printer.print_on_front_page(pdf,card,row_index, column_index)
        pdf.drawCentredString(page_width/2.0,20,"front of page %i" % (page_index + 1))
        pdf.showPage()
        if custom_font is not None:
            pdf.setFont(custom_font,14)#FIXME don't hardcode font size
        for (row_index,rowOfCards) in enumerate(pageOfCards):
            for (column_index,card) in enumerate(rowOfCards):
                card_printer.print_on_back_page(pdf,card,row_index, column_index)                
        pdf.drawCentredString(page_width/2.0,20,"back of page %i" % (page_index + 1))
        pdf.showPage()

    pdf.save()
Example #3
0
def PrintPdf(projectNo, probeInf, holelist, index=None):
    import os
    from config import basedir
    cptPath = os.path.join(basedir, 'app', 'static', 'download')

    if not os.path.exists(cptPath):
        os.makedirs(cptPath)
    doc = SimpleDocTemplate(cptPath,
                            pagesize=A4,
                            rightMargin=10,
                            leftMargin=20,
                            topMargin=30,
                            bottomMargin=20
                            )
    doc.pagesize = portrait(A4)
    filename = ''
    elements = []
    for i in range(len(holelist)):
        if index is not None:
            i = index
            filename = projectNo + '__' + holelist[i].holeName + '.pdf'
            # Attenion:where elments.extend must be used,but not elements.append
            elements.extend(Cpt2Pdf(holelist[i], probeInf))
            break;
        else:
            filename = projectNo + '__' + 'all.pdf'
            # Attenion:where elments.extend must be used,but not elements.append
            elements.extend(Cpt2Pdf(holelist[i], probeInf))
    doc.filename = os.path.join(cptPath, filename)
    print("dd" + doc.filename)
    doc.build(elements)
    # url='/'.join(['download',projectNo,filename])
    # os.path.join('download',projectNo,filename)将返回download\projectNo\filename,浏览器无法识别
    return doc.filename
Example #4
0
 def test5(self):
     '''extreme test inspired by Moritz Pfeiffer https://bitbucket.org/moritzpfeiffer/'''
     with self.assertRaises(LayoutError):
         text="""
         Clearly, the natural general principle that will subsume this case is
         not subject to a parasitic gap construction.  Presumably, most of the
         methodological work in modern linguistics can be defined in such a way
         as to impose the system of base rules exclusive of the lexicon.  In the
         discussion of resumptive pronouns following (81), the fundamental error
         of regarding functional notions as categorial is to be regarded as a
         descriptive <span color="red">fact</span>.<br/>So far, the earlier discussion of deviance is not
         quite equivalent to a parasitic gap construction.  To characterize a
         linguistic level L, a case of semigrammaticalness of a different sort
         may remedy and, at the same time, eliminate irrelevant intervening
         contexts in selectional <span color="red">rules</span>.<br/>
         Summarizing, then, we assume that the descriptive power of the base
         component can be defined in such a way as to impose nondistinctness in
         the sense of distinctive feature theory.
         """
         styleSheet = getSampleStyleSheet()
         story = []
         story.append(Paragraph(text, styleSheet['Normal']))
         doc = BaseDocTemplate(
             outputfile('test_platypus_much_too_large.pdf'),
             pagesize=portrait(A4),
             pageTemplates=[PageTemplate(
                 'page_template',
                 [Frame(0, 0, 0, 0, leftPadding=0, rightPadding=0, topPadding=0, bottomPadding=0, id='DUMMY_FRAME')],
                 )],
             )
         doc.build(story)
Example #5
0
    def print_pdf(pages, outfile, fontsize = 7, orientation='portrait',
                  blocks_per_page=1):

        if orientation == 'portrait':
            pagesize = portrait(letter)
        elif orientation == 'landscape':
            pagesize = landscape(letter)

        #precalculate some basics
        top_margin = pagesize[1] - .75*inch
        bottom_margin = 0.75*inch
        left_margin = 0.5*inch
        right_margin = pagesize[0] - 0.5*inch
        frame_width = right_margin - left_margin

        top_margin_offset = 0

        document_font = 'Courier'

        def drawPageFrame(canv):

            # pagecount = len(pages)
            pagecount = len(pageIter)
            pg = canv.getPageNumber()
            ofn = os.path.split(outfile)[-1]

            page_center = 0.5 * pagesize[0]

            canv.drawCentredString(page_center, top_margin + 0.3*inch,
                '%(ofn)s' % locals())

            lineycoord = top_margin + 0.25*inch
            canv.line(left_margin, lineycoord, right_margin, lineycoord)
    #       canv.setFont(document_font,fontsize)

            canv.drawCentredString(page_center, 0.5*inch,
                'Page %(pg)s of %(pagecount)s' % locals())

        canv = canvas.Canvas(outfile, invariant=1, pagesize=pagesize)
        canv.setPageCompression(1)

        pageIter = list(grouper(blocks_per_page, pages, pad=False))

        for pagegroup in pageIter:
            drawPageFrame(canv)
            canv.setFont(document_font, fontsize)
            tx = canv.beginText(left_margin, top_margin - top_margin_offset)

            for i, page in enumerate(pagegroup):
                for line in page:
                    tx.textLine(line)
                # separate blocks
                if blocks_per_page > 1 and i + 1 < blocks_per_page:
                    tx.textLine('')

            canv.drawText(tx)
            canv.showPage()

        canv.save()
Example #6
0
def convertImageToPDF(_fileName, _swfslides, isDocin):
    print "convecting files to pdf..."
    pdfCanvas = canvas.Canvas("%s.pdf" % _fileName, pagesize=portrait(A4))
    # pdfCanvas.drawString(150,700,"Welcome to flash slides downloader");
    # pdfCanvas.drawString(180,680,"contact: [email protected]");
    # pdfCanvas.showPage()
    numberOfSlides = 1
    for iswf in _swfslides:
        doc = gfx.open("swf", iswf)
        print iswf
        if doc:
            if isDocin == False:
                for pagenr in range(1, doc.pages + 1):
                    page1 = doc.getPage(pagenr)
                    print "Page", pagenr, "has dimensions", page1.width, "x", page1.height
                    pdfCanvas.setPageSize((page1.width * 2, page1.height * 2))
                    imageName = "image-%s-%s.png" % (numberOfSlides, pagenr)
                    imgRGBBuf = page1.asImage(page1.width * 2, page1.height * 2)
                    im = Image.fromstring(
                        "RGB", (page1.width * 2, page1.height * 2), imgRGBBuf
                    )  # convert to PIL Object
                    # img = gfx.ImageList()
                    # 				img.setparameter("antialise", "4") # turn on antialisin
                    # img.setparameter("zoom", "100")
                    # img.startpage(page1.width,page1.height)
                    # 				page1.render(img)
                    # 				img.endpage()
                    # pageNumOfThisSwf+=1"thumbnail%s.png" % pagenr
                    # img.save(imageName)
                    # pdfCanvas.drawImage(imageName,0,0,width= page1.width,height= page1.height,mask='auto')
                    pdfCanvas.drawImage(
                        ImageReader(im), 0, 0, width=page1.width * 2, height=page1.height * 2, mask="auto"
                    )
                    pdfCanvas.showPage()
                    # os.remove(imageName) # delete temp image
            else:
                # damn docins bad header.
                page1 = doc.getPage(1)
                print "Page %d" % numberOfSlides, "has dimensions", page1.width, "x", page1.height
                pdfCanvas.setPageSize((page1.width * 2, page1.height * 2))
                imageName = "image-%s-%s.png" % (numberOfSlides, 1)
                imgRGBBuf = page1.asImage(page1.width * 2, page1.height * 2)
                im = Image.fromstring("RGB", (page1.width * 2, page1.height * 2), imgRGBBuf)  # convert to PIL Object
                # img = gfx.ImageList()
                # img.setparameter("antialise", "4") # turn on antialisin
                # img.setparameter("zoom", "100")
                # img.startpage(page1.width,page1.height)
                # page1.render(img)
                # img.endpage()
                # pageNumOfThisSwf+=1"thumbnail%s.png" % pagenr
                # img.save(imageName)
                # pdfCanvas.drawImage(imageName,0,0,width= page1.width,height= page1.height,mask='auto')
                pdfCanvas.drawImage(ImageReader(im), 0, 0, width=page1.width * 2, height=page1.height * 2, mask="auto")
                pdfCanvas.showPage()
                # os.remove(imageName) # delete temp image
        numberOfSlides += 1
        os.remove(iswf)  # delete temp swf
    pdfCanvas.save()
Example #7
0
def export(listino, luogoDiRiferimento):
    response = http.HttpResponse(content_type='application/pdf')
    width, height = portrait(A4)

    pageTemplates = [
        PageTemplate(id='Listino', onPage=onPageListino),
    ]

    doc = BaseDocTemplate(
        response,
        pagesize=(width, height),
        leftMargin=1 * cm,
        rightMargin=1 * cm,
        bottomMargin=1.5 * cm,
        topMargin=1 * cm,
        showBoundary=test,
        pageTemplates=pageTemplates,
    )

    doc.listino = listino  # arricchisco il doc

    righe_prezzo = listino.prezzolistino_set.all()

    story = []

    listinoEsclusivo = getTabellaListino(doc, righe_prezzo, 'T', luogoDiRiferimento)
    if listinoEsclusivo:
        title = Paragraph("SERVIZIO TAXI ESCLUSIVO", normalStyle)
        story.append(title)
        story.append(listinoEsclusivo)

    listinoCollettivo = getTabellaListino(doc, righe_prezzo, 'C', luogoDiRiferimento)
    if listinoEsclusivo and listinoCollettivo:
        story.append(Spacer(1, 1.5 * cm))
    if listinoCollettivo:
        title = Paragraph("SEVIZIO COLLETIVO MINIBUS", normalStyle)
        story.append(KeepTogether([title, listinoCollettivo]))

    if not listinoCollettivo and not listinoEsclusivo:
        story.append(
            Paragraph("Non abbiamo nessuna corsa specificata nel listino.", normal_style)
        )

    # footer
    footer_style = ParagraphStyle(name='Justify', alignment=TA_JUSTIFY, fontSize=8)
    # footer_height = 0
    if LISTINO_FOOTER:
        note_finali_lines = [LISTINO_FOOTER]
        story.append(Spacer(1, 1 * cm))
        note_finali = Paragraph("<br/>".join(note_finali_lines),
                                footer_style)
        # note_finali.wrap(width - doc.rightMargin - doc.leftMargin, 5 * cm)
        # note_finali.drawOn(canvas, doc.leftMargin, doc.bottomMargin)
        # footer_height = note_finali.height
        story.append(note_finali)

    doc.build(story, canvasmaker=NumberedCanvas)
    return response
Example #8
0
def render( root, pdf, **kwargs ):

	debug = False
	mycanvas = None
	if kwargs is not None:
		try:
			fonts = kwargs['fonts']
			map(pdfmetrics.registerFont, fonts)
		except:
			pass
		
		try:
			debug = kwargs['showframes']
		except:
			pass
		try:
			mycanvas = kwargs['canvas']
		except:
			pass
	doc_pagesize = pagesizes.letter
	root_pagesize = root._style.getattribute('pagesize',str)
	root_pageorientation = root._style.getattribute('orientation',str)

	pagesize_tuple = root_pagesize.split(':')
	if len(pagesize_tuple) > 1:
		doc_pagesize = (float(pagesize_tuple[0]),float(pagesize_tuple[1]))

	if root_pageorientation == 'landscape':
		doc_pagesize = pagesizes.landscape(doc_pagesize)
	if root_pageorientation == 'portrait':
		doc_pagesize = pagesizes.portrait(doc_pagesize)        

	if mycanvas is None:
		pdf_canvas = NumberedCanvas(pdf, pagesize=doc_pagesize)        
	else:
		mycanvas.setPageSize(doc_pagesize)
		pdf_canvas = mycanvas                

	page_manager = pagemgr(pdf_canvas)        
	page_manager.showframes(debug)

	rlroot = rlobject(root)
	rlroot.render(page_manager)

	start = time.time()

	if mycanvas is None:
		pdf_canvas.save()

	end = time.time()
	delta = end - start
	adddeltatimer('canvas',delta)

	final_delta = 0

	return 0
Example #9
0
 def set_canvas(self):
     """
     Il metodo si fa carico di impostare il formato di pagina conseguentemente all'orientamento
     specificato.
     """
     if self.oPageFormat.orientamento=="landscape":    
         x=landscape((self.oPageFormat.larghezza,self.oPageFormat.altezza))
     else:
         x=portrait((self.oPageFormat.larghezza,self.oPageFormat.altezza))
     return astraCanvas(self.oPageFormat.nomepdf,pagesize=x)
Example #10
0
File: pdf.py Project: awriel/eden
 def _calc(self):
     if self.defaultPage == "Landscape":
         self.pagesize = landscape(self.paper_size)
     else:
         self.pagesize = portrait(self.paper_size)
     BaseDocTemplate._calc(self)
     self.height = self.pagesize[PDF_HEIGHT]
     self.width = self.pagesize[PDF_WIDTH]
     self.printable_width = self.width - self.leftMargin - self.rightMargin - self.insideMargin
     self.printable_height = self.height - self.topMargin - self.bottomMargin
Example #11
0
def main(infile, outfile, color, font, font_size, portrait, scale, no_times,
         no_weekends, start_monday):
    """
    Weekly schedule typesetter

    Visit <https://github.com/jwodder/schedule> for more information.
    """
    if font in available_fonts():
        font_name = font
    else:
        # Assume we've been given a path to a .ttf file
        font_name = 'CustomFont'
        ### TODO: Use the basename of the filename as the font name?  (Could
        ### that ever cause problems?)
        pdfmetrics.registerFont(TTFont(font_name, font))
    if portrait:
        page_width, page_height = pagesizes.portrait(pagesizes.letter)
    else:
        page_width, page_height = pagesizes.landscape(pagesizes.letter)
    colors = COLORS if color else [GREY]
    if no_weekends:
        week = WEEKDAYS_EN
    elif start_monday:
        week = FULL_WEEK_MON_EN
    else:
        week = FULL_WEEK_EN
    sched = Schedule(week)
    for ev in read_events(infile, colors=colors):
        sched.add_event(ev)
    if outfile is None:
        if infile is sys.stdin:
            outfile_name = '-'
        else:
            outfile_name = str(Path(infile.name).with_suffix('.pdf'))
        outfile = click.open_file(outfile_name, 'wb')
    c = Canvas(outfile, (page_width, page_height))
    c.setFont(font_name, font_size)
    if scale is not None:
        factor = 1 / scale
        c.translate(
            (1-factor) * page_width / 2,
            (1-factor) * page_height / 2,
        )
        c.scale(factor, factor)
    sched.render(
        c,
        x          = inch,
        y          = page_height - inch,
        width      = page_width - 2*inch,
        height     = page_height - 2*inch,
        font_size  = font_size,
        show_times = not no_times,
    )
    c.showPage()
    c.save()
Example #12
0
 def write(self):
     """Assembles the final PDF and writes to disk."""
     pdf_writer = pyPdf.PdfFileWriter()
     if self.front_matter is not None:
         front_matter = pyPdf.PdfFileReader(file(self.front_matter, "rb"))
         for page in range(front_matter.getNumPages()):
             pdf_writer.addPage(front_matter.getPage(page))
     working_file = tempfile.NamedTemporaryFile(suffix=".pdf", delete=False)
     doc = SimpleDocTemplate(working_file)
     doc.pagesize = portrait(letter)
     story = []
     styles = getSampleStyleSheet()
     for section in self.sections:
         heading_text = section.heading
         story.append(Paragraph(heading_text, styles["Heading1"]))
         for content in section.contents:
             if "figure" in content:
                 figure = content["figure"]
                 if os.path.exists(figure):
                     im = utils.ImageReader(figure)
                     img_width, img_height = im.getSize()
                     aspect = img_height / float(img_width)
                     story.append(Image(figure, width=img_width, height=(img_width * aspect)))
                 if content.get("caption", None) is not None:
                     caption_text = "<font size=10>{0}</font>".format(content["caption"].strip())
                     story.append(Paragraph(caption_text, styles["Italic"]))
                     story.append(Spacer(1, 10))
             if "table" in content:
                 _t = self.build_table(content["table"])
                 story.append(_t)
                 if content.get("caption", None) is not None:
                     caption_text = "<font size=10>{0}</font>".format(content["caption"].strip())
                     story.append(Paragraph(caption_text, styles["Italic"]))
                     story.append(Spacer(1, 10))
             if "text" in content:
                 for para in content["text"]:
                     story.append(Paragraph(para, styles["Normal"]))
                     story.append(Spacer(1, 12))
     doc.build(story)
     body_matter = pyPdf.PdfFileReader(working_file)
     for page in range(body_matter.getNumPages()):
         pdf_writer.addPage(body_matter.getPage(page))
     try:
         os.remove(working_file.name)
     except OSError:  # Windows reports file in use, other OS errors, etc.
         pass
     if self.end_matter is not None:
         end_matter = pyPdf.PdfFileReader(file(self.end_matter, "rb"))
         for page in range(end_matter.getNumPages()):
             pdf_writer.addPage(end_matter.getPage(page))
     output_stream = file(self.output_filename, "wb")
     pdf_writer.write(output_stream)
Example #13
0
def pdf(files, outfile, useportrait=True):
    print("Creating PDF...")
    pdf = Canvas(outfile)
    pagesize = portrait(A4) if useportrait else landscape(A4)
    for i in files:
        print("Creating PDF page for %s..." % i)
        pdf.setPageSize(pagesize)
        pdf.drawImage(i, 0, 0, *pagesize)
        pdf.showPage()
        print("Done!")
    print("Saving PDF...")
    pdf.save()
    print("Done!")
Example #14
0
 def __init__(self, title='', pretext='', two_column=False):
     self.story = ['', '']
     self.pagesize = portrait(letter)
     self.styles = getSampleStyleSheet()
     if title: 
         self.title = PDF.Item('TITLE', title)
     else: 
         self.title = PDF.Item('TITLE', timestamp())   
     self.pretext = PDF.Item('PRETEXT', pretext)
     self.set_title(self.title.value)
     self.set_pretext(self.pretext.value)
     self.two_column = two_column
     self.savedir = '%s\\Documents'%os.path.expanduser('~') 
Example #15
0
 def __init__(self, oIreport, pdfFileName):
     self.oPageFormat=page_Format(oIreport.get_ReportStru(), pdfFileName)
     if self.oPageFormat.orientamento=="Landscape":    
         x=landscape((self.oPageFormat.larghezza,self.oPageFormat.altezza))
     else:
         x=portrait((self.oPageFormat.larghezza,self.oPageFormat.altezza))
         
     self.set_row(self.oPageFormat.altezza-self.oPageFormat.topMargin)
     canvas.Canvas.__init__(self, self.oPageFormat.nomepdf,
                            pagesize=x,
                            bottomup =1,
                            pageCompression=0,
                            #encoding=rl_config.defaultEncoding,
                            verbosity=0)
     self.pageNumber=0
Example #16
0
def informesPdf(periode,grup):
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=informe.pdf'

    elements = []
    styles = getSampleStyleSheet()
    styles['Normal'].fontsize=8
    doc = SimpleDocTemplate(response, leftMargin=25, rightMargin=25, topMargin=25, bottomMargin=25)
    doc.pagesize = portrait(A4)

    today = datetime.date.today().strftime('%d/%m/%Y')
    periode = Periode.objects.get(id=periode)
    amonList = Amonestacio.objects.filter(dataHora__gt=periode.dt1).filter(dataHora__lt=periode.dt2)
    if grup != "-1":
        grup = Grup.objects.get(id=grup)
        amonList = amonList.filter(alumne__grup=grup)

    alumnes = set( [ a.alumne for a in amonList ] )

    for al in sorted(alumnes, key = lambda a: unicode(a)):
        par = Paragraph(u"<b>Es Liceu</b>. Carrer Cabana, 31. 07141, Pont d'Inca, Marratxí<br/>Telèfon: 971 60 09 86. E-MAIL: [email protected]<br/><br/>",
            styles['Normal'])
        elements.append(par)
        elements.append(Paragraph(unicode(periode.descripcio), styles['Normal']))
        elements.append(Paragraph(unicode(al), styles['Heading1']))

        elements.append(Paragraph("Data: " + today, styles['Normal']))
        elements.append(Paragraph("Curs: " + unicode(al.grup), styles['Normal']))
        elements.append(Paragraph("Tutor/a: " + unicode(al.grup.tutor) + "<br/>", styles['Normal']))

        elements.append(Paragraph(u"Informe d'incidències", styles['Heading2']))

        for a in amonList.filter(alumne=al).order_by('dataHora'):
            elements.append(Paragraph(u"<b>Data:</b> " + a.dataHora.strftime('%d/%m/%Y') + u'<br/>', styles['Normal']))
            elements.append(Paragraph(u"<b>Professor:</b> " + unicode(a.professor) + u'<br/>', styles['Normal']))
            elements.append(Paragraph(u"<b>Tipus d'incidència:</b> " + unicode(a.gravetat) + u'<br/>', styles['Normal']))
            elements.append(Paragraph(u"<b>Descripció:</b> " + a.descripcio + u'<br/><br/>', styles['Normal']))

        totalpunts = puntsAlumnePeriode(al,periode)
        elements.append(Paragraph(u"Total punts restants: " + unicode(totalpunts) + u'<br/><br/>', styles['Heading3']))
        elements.append(PageBreak())

    doc.build(elements)
    return response
Example #17
0
    def generator_file(self,D,d,m,b,bending_force,wear_force,velocity,Feff,FOS1,pdf_file_name):
        from reportlab.pdfgen import canvas
        from reportlab.lib.pagesizes import letter
        from reportlab.lib.pagesizes import portrait
        #from reportlab.platypus import image

        
        c=canvas.Canvas(pdf_file_name, pagesize=portrait(letter))
        c.setFont('Helvetica', 30 , leading=None)
        c.drawCentredString(320,750,'Final report generation')
        c.setFont('Helvetica', 25 , leading=None)
        c.drawString(10,700,"Unknown Parameters")
        c.drawString(500,700,"Values")
        c.setFont('Helvetica', 20 , leading=None)
        c.drawString(10,650,'Final Module =')
        c.drawString(500,650,str(m)+"mm")
        c.drawString(10,600,'Diameter of Gear=')
        c.drawString(500,600,str(D)+"mm")
        c.drawString(10,550,'Diameter of Pinion=')
        c.drawString(500,550,str(d)+"mm")
        c.drawString(10,500,'Deddendum=')
        c.drawString(500,500,str(m)+"mm")
        c.drawString(10,450,'Addendum=')
        c.drawString(500,450,str(1.25*m)+"mm")
        c.drawString(10,400,'Facewidth=')
        c.drawString(500,400,str(b)+"mm")
        c.drawString(10,350,'Permissible Bending force=')
        c.drawString(500,350,bending_force+"N")
        c.drawString(10,300,'Permissible Wear force=')
        c.drawString(500,300,wear_force+"N")
        c.drawString(10,250,'Velocity=')
        c.drawString(500,250,velocity+"m/s")
        c.drawString(10,200,'Available Factor of safty=')
        c.drawString(500,200,str(FOS1))
        c.drawString(10,150,'Maximum Effective force=')
        c.drawString(500,150,str(Feff))
        c.drawString(0,120,"------------------------------------------------------------------------------------------------")
        c.setFont('Helvetica', 30 , leading=None)
        c.drawString(200,75,"THANK YOU")
        self.count = self.count + 1

        c.showPage()
        c.save()
Example #18
0
def receipt(response, people, amount_per_person, total):
  doc = p.SimpleDocTemplate(response)
  doc.pagesize = portrait(letter)

  elements = [p.Spacer(1, 2.5*inch)]

  # Create the main table of people.
  data = [['Activity', 'Rate/Unit', 'Count', 'Amount (USD)']]
  for person in people:
    data.append([person.name, '%.2f' % amount_per_person, 1, '%.2f' % amount_per_person])
  data.append(['','','',''])

  # Add in random accounting to make it look official.
  accounting_rows = 3
  data.append(['Sum Fees','','','%.2f' % (len(people) * amount_per_person)])
  if total != len(people) * amount_per_person:
    discount = len(people) * amount_per_person - total
    accounting_rows = 4
    data.append(['Discount','','','-%.2f' % (discount)])
  data.append(['Total','','','%.2f' % (total)])
  data.append(['Paid','','','-%.2f' % (total)])
  data.append(['Final Total','','','0.00'])

  # Draw some lines for style.
  style = p.TableStyle([
    ('LINEBELOW', (0, 0), (-1, 0), 2, colors.black),
    ('LINEBELOW', (0, -accounting_rows-2), (-1, -accounting_rows-2), 1, colors.black),
    ('LINEBELOW', (0, -2), (-1, -2), 2, colors.black),
    ('ALIGNMENT', (1, 0), (-1, -1), 'RIGHT'),
    ])
  elements.append(p.Table(data, colWidths=[3*inch, 1*inch, 0.75*inch, 1*inch], style=style))

  elements.append(p.Spacer(1, 1*inch))
  elements.append(p.Paragraph('Thank you for your patronage.',
                              style=ParagraphStyle('centered',alignment=1)))

  doc.build(elements, onFirstPage=drawHeading)
Example #19
0
#
# You should have received a copy of the GNU General Public License
# along with django-placard  If not, see <http://www.gnu.org/licenses/>.

from django.http import HttpResponse
from django.template import defaultfilters

import datetime
from cStringIO import StringIO
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle
from reportlab.lib.pagesizes import A4, portrait
from reportlab.lib import colors

import placard.views

PAGE_WIDTH = portrait(A4)[0]


class PdfResponseMixin(placard.views.AccountList):
    response_class = HttpResponse

    def render_to_response(self, context, **response_kwargs):
        """
        Returns a JSON response, transforming 'context' to make the payload.
        """
        response_kwargs['content_type'] = 'application/pdf'
        #        response_kwargs = ['Content-Disposition'] = 'attachment; filename= ' + self.fname
        return self.response_class(self.convert_context_to_pdf(context),
                                   **response_kwargs)

Example #20
0
def generatorQrcode(inPath, outPath):
    try:
        BASE_DIR = os.path.dirname(__file__)
        IN_DIR = BASE_DIR + '/' + inPath
        OUT_DIR = BASE_DIR + '/' + outPath

        # 删除output文件夹, 并重新创建
        if os.path.exists(outPath):
            shutil.rmtree(outPath)
        os.mkdir(OUT_DIR)

        # 生成canvas画布
        (width, high) = portrait(A3)
        c = canvas.Canvas('./output.pdf', pagesize=portrait(A3))
        x = 0
        y = high - 130

        files = os.listdir(IN_DIR)
        region_resize = (150, 150)  # 重新定义二维码尺寸(width, height)
        # 如果需要base_img,则设置为True
        base_img = None
        box = (0, 0)
        need_base = True
        if need_base:
            base_img = Image.open('./base.png')
            left = int((base_img.size[0] - region_resize[0]) / 2)
            top = int((base_img.size[1] - region_resize[1]) / 2)
            box = (left, top
                   )  # left为二维码距离base_image左边的距离, top为上边距, 如果上下不居中 需要手动调整top的值
        for f in files:
            path = IN_DIR + '/' + f
            if os.path.isfile(path):
                # name = os.path.splitext(f)[0]
                with open(path, 'r') as open_file:
                    while True:
                        info = open_file.readline()
                        info = info.strip('\n')
                        if not info:
                            break
                        # 生成二维码
                        qr = qrcode.QRCode(
                            version=
                            None,  # 二维码的大小, int, 1-40(最小值是1,是个12×12的矩阵), 如果让程序自动生成,将值设置为None并使用fit=True参数
                            error_correction=qrcode.constants.
                            ERROR_CORRECT_H,  # 二维码的纠错范围,可以选择4个常量, 默认ERROR_CORRECT_M
                            box_size=10,  # 每个点(方块)中的像素个数
                            border=0  # 二维码距图像外围边框距离, 默认为4
                        )
                        qr.add_data(info)
                        qr.make(fit=True)
                        img = qr.make_image()

                        # 将二维码保存并重新设置大小
                        name = info.split('q=')[1]
                        img_path = OUT_DIR + '/' + name + '.png'  # 图片存储路径
                        img.save(img_path)
                        if need_base:
                            img = Image.open(img_path)
                            region = img
                            region = region.resize(region_resize)

                            # 将二维码附着在图片上
                            base_img.paste(region, box)
                            base_img.save(img_path)

                        # 图片写入PDF文件
                        x += 5
                        c.drawImage(img_path, x, y, 80, 130)
                        if x > 680:
                            x = 0
                            y -= 135
                        else:
                            x += 80

                        if y < 0:
                            c.showPage()
                            y = high - 130
                        os.remove(img_path)  # 图片写入完成后删除

                    c.save()
                    pdf_size = os.path.getsize(
                        './output.pdf') / 1024 / 1024  # 生成的PDF文件的大小,单位为MB
                    if pdf_size >= 500:  # 大于等于500M时,将文件压缩为zip压缩包
                        zip_pdf = ZipFile('./output.zip', 'w')
                        zip_pdf.write('./output.pdf',
                                      compress_type=zipfile.ZIP_DEFLATED)
                        zip_pdf.close()
    except Exception as exp:
        pass
def main(argv):

    # Set variables:
    # proxy_path = '.\\proxies\\LiPDs_20201130'
    # proxy_list = '_LiPD_List_Proxies.txt'
    # pdf_file = '.\\output\\dashboard_pdfs\\LiPD_Dashboards_20201130_Proxies.pdf'
    # ----------
    proxy_path = '.\\proxies\\LiPDs_20201214'
    proxy_list = '_LiPD_List.txt'
    pdf_file = '.\\output\\dashboard_pdfs\\LiPD_Dashboards_20201214.pdf'
    # ----------
    map_legend_flag = False
    #bbox_dx = 20.0  # Bounding box side in degrees
    #fig_dpi = 300  # Figure DPI setting for PNG

    # Define colours:
    source_ec = (0.00, 0.00, 1.00)  # Marker/polygon edge colour
    source_pc = (0.00, 0.00, 1.00, 0.15)  # Polygon face colour (transparant)
    source_fc = (0.85, 0.85, 1.00)  # Marker face colour (a=0.15)
    source_lc = (0.65, 0.65, 1.00)  # Line colour (a=0.35)
    # ----------
    target_ec = (1.00, 0.45, 0.00)  # Marker/polygon edge colour
    target_pc = (1.00, 0.45, 0.00, 0.15)  # Polygon face colour (transparant)
    target_fc = (1.00, 0.92, 0.85)  # Marker face colour (a=0.15)
    target_lc = (1.00, 0.75, 0.55)  # Line colour (a=0.45)
    
    # Get list of files from proxy_list:
    proxy_files = []
    f = open(proxy_path + '\\' + proxy_list, 'r')
    for i in f:
        if i.strip()[0] != '#':
            proxy_files.append(i.strip())
        # end if
    # end for
    f.close()

    # Print program details
    print ('\nCreate dashboard PDF from LiPD files:')
    print ('  proxy_path =', proxy_path)
    print ('  proxy_list =', proxy_list)
    print ('  pdf_file =', pdf_file)
    if DEBUG > 0:
        print ('  proxy_files:')
        for i in proxy_files:
            print('    "' + i + '"')
        # end for
    # end if

    # Open up a new PDF canvas:
    print('\nCreating pdf file')
    c = canvas.Canvas(pdf_file, pagesize=portrait(A4))
    c_width, c_height = portrait(A4)

    # Loop through LiPD files:
    num_pages = (len(proxy_files) - 1)// 2 + 1
    page = 0  # Page counter
    item_top = True  # True if is item top of page (two items per page)
    i_xloc = 1*cm
    i_width = c_width - 2*cm
    i_height = c_height/2 - 1.5*cm
    print('\nLooping through LiPD files:')
    for PF in proxy_files:
        print('  "' + PF + '"')

        # Deal with top or bottom page items:
        if item_top:
            page += 1
            if page > 1: c.showPage()
            i_yloc = c_height/2 + 0.5*cm
            # Write date:
            c.setFont('Helvetica-Oblique', 9)
            c.drawRightString(c_width - 1.0*cm, c_height - 0.6*cm,
                              'Created: ' + dt.datetime.now().strftime('%d-%b-%G')) 
            # Write page number:
            c.setFont('Helvetica', 9)
            c.drawCentredString(c_width / 2.0,  0.4*cm,
                                'Page ' + str(page) + ' of ' + str(num_pages))
        else:
            i_yloc = 1*cm
        # end if
        item_top = not item_top
        
        # Draw bounding rectangle:
        c.rect(i_xloc, i_yloc, i_width, i_height, stroke=1, fill=0)

        # Open LiPD metadata:
        LMeta = xlipd.Read_JSON(proxy_path + '\\' + PF)
        #print(LMeta.keys())

        # Get subsets:
        LPub = LMeta['pub']
        #print(LPub.keys())

        # Get measurment table #1:
        LTab = LMeta['paleoData'][0]['measurementTable'][0]
        LTab_columns = len(LTab['columns'])
        if DEBUG > 0:
            print('LTab_columns =', LTab_columns)

        # Find first "year" or "age" column:
        x_col_1 = None
        # ---Try to find "YEAR CE/BCE"---
        for i in range(LTab_columns):
            stmp = xlipd.extract_string1(LTab['columns'][i], 'variableName', False, 'NA')
            if stmp.split(' ')[0].upper() == 'YEAR':
                x_col_1 = i
                break
            # end if
        # end for
        # ---Else try to find "AGE"---
        if x_col_1 == None:
            for i in range(LTab_columns):
                stmp = xlipd.extract_string1(LTab['columns'][i], 'variableName', False, 'NA')
                if stmp.split(' ')[0].upper() == 'AGE':
                    x_col_1 = i
                    break
                # end if
            # end for
        # end if
        # ---Otherwise report error---
        if x_col_1 == None:
            print('Can\'t find year or age column')
            sys.exit()
        # end if

        # Find dataset column (first with "variableType" = PROXY or RECONSTRUCTION):
        x_col_2 = None
        # ---First "variableType" with PROXY or RECONSTRUCTION---
        # for i in range(LTab_columns):
        #     stmp = xlipd.extract_string1(LTab['columns'][i], 'variableType', False, 'NA')
        #     if stmp.upper() in ['PROXY', 'RECONSTRUCTION']: 
        #         x_col_2 = i
        #         break
        #     # end if
        # # end for
        # ---Use specific column---
        # x_col_2 = LTab_columns - 1  # Use last column
        x_col_2 = LTab_columns - 2  # Use 2nd last column (last is QC)
        # ---Otherwise report error---
        if x_col_2 == None:
            print('Can\'t find dataset column')
            sys.exit()
        # end if

        # Get table dataframe:
        x_file = LTab['filename']
        x_df = xlipd.Read_CSV2DF(proxy_path + '\\' + PF, x_file)
        x_df = x_df.sort_values(by=x_df.columns[x_col_1], ascending=True)
        if DEBUG > 0:
            print('x_file =', x_file)
            print('x_col_1 =', x_col_1)
            print('x_col_2 =', x_col_2)
            print('x_df:')
            print(x_df)
        # end if
        
        # Check if proxy or reconstruction:
        # x_type = xlipd.extract_string1(LTab['columns'][x_col_2], 'variableType', 'NA')  # OLD
        x_type = xlipd.extract_string1(LTab['columns'][x_col_2]['datasetType'], 'type', 'NA')
        x_type = x_type.strip().upper()
        # print('x_type = ', x_type)
 
        # If reconstruction check for "interpretation":
        stmp = xlipd.extract_string1(LTab['columns'][x_col_2]['interpretationFormat'], 
                                     'format', False, 'NA')
        x_interp = not (stmp.strip().upper() in ['NONE', 'NULL', 'NA'])
        #print('x_interp = ', x_interp)
 
    
        # ---Data Information--------------------------------------------------

        # Write dataset_name:
        stmp = 'Dataset Name: ' + LMeta['dataSetName']
        stmp = trim_string(stmp, 'Helvetica-Bold', 12, c_width - 3.0*cm)
        c.setFont('Helvetica-Bold', 12)
        c.drawString(i_xloc + 0.5*cm, i_yloc + i_height - 0.7*cm, stmp)

        # Write dataset_id and reference_id:
        c.setFont('Helvetica', 10)
        stmp1 = xlipd.extract_string1(LMeta, 'dataSetID', False, 'NA')
        stmp2 = xlipd.extract_string1(LMeta, 'referenceID', False, 'NA')
        c.drawString(i_xloc + 0.5*cm, i_yloc + i_height - 1.2*cm,
                     'Dataset ID: ' + stmp1 + '; Reference ID: ' + stmp2 )

        # Set up paragraph and table styles:
        pstyle = ParagraphStyle(name='Normal', fontName='Helvetica', fontSize=8,
                                leftIndent=20, firstLineIndent=-20, leading=12)
        twidth = (c_width - 3.5*cm) / 2.0
        theight = 5.0*cm
        tstyle = TableStyle([('VALIGN', (0,0), (0,0), 'TOP'),
                             #('BOX', (0,0), (0,0), 0.5, colors.red),
                             ('LEFTPADDING', (0,0), (0,0), 0),
                             ('RIGHTPADDING', (0,0), (0,0), 0),
                             ('TOPPADDING', (0,0), (0,0), 0),
                             ('BOTTOMPADDING', (0,0), (0,0), 0)])

        # Write metadata in column 1:
        tpara = []
        # ---LPub----------------------
        # ---Author--------------------
        # stmp = xlipd.extract_string1(LPub, 'author', False, 'NA')
        # stmp1 = xlipd.extract_string1(LPub, 'year', False, 'NA')
        # if is_number(stmp1): stmp1 = str(int(float(stmp1)))
        # tpara.append(Paragraph('Author: ' + stmp + ' <i>et al</i>. (' + stmp1 +')', pstyle))
        # ---Citation------------------
        stmp = xlipd.extract_string1(LPub, 'citation', False, 'NA')
        i = stmp.find('http')
        if i > 0: stmp = stmp[:i-1]
        if stmp[-1] == ',': stmp = stmp[:-1] + '.'
        tpara.append(Paragraph('Citation: ' + stmp, pstyle))
        # ---Citation DOI--------------
        # Also try to remove dataURL from citation if it exists.
        stmp = xlipd.extract_string1(LPub, 'doi', False, 'NA')
        stmp1 = None
        i = stmp.upper().find('DOI.ORG')
        if i >= 0:
            stmp = stmp[i+8:]
            stmp1 = 'https://doi.org/' + stmp
        # end if
        i = stmp.upper().find('DOI:')
        if i >= 0:
            stmp = stmp[i+4:].strip()
            stmp1 = 'https://doi.org/' + stmp
        # end if
        i = stmp.upper().find('HTTP')
        if i >= 0:
            stmp1 = stmp
        # end if
        stmp = trim_string('Citation DOI: ' + stmp, 'Helvetica', 8, twidth)
        stmp = stmp[14:]
        if not stmp1 is None:
            stmp = '<link href="' + stmp1 + '" color="blue"><u>' + stmp + '</u></link>'
        # end if
        tpara.append(Paragraph('Citation DOI: ' + stmp, pstyle))
        # ---Data Citation-------------
        # Also try to remove dataURL from citation if it exists.
        stmp = xlipd.extract_string1(LPub, 'dataCitation', False, 'NA')
        i = stmp.find('http')
        if i > 0:
            j = stmp[i:].find(' ')
            if j > 0:
                stmp = stmp[:i-1] + stmp[i+j:]
            else:
                stmp = stmp[:i-1]
            # end if
        # end if
        stmp = stmp.strip()
        if stmp[-1] == ',': stmp = stmp[:-1] + '.'
        if stmp[-1] != '.': stmp = stmp + '.'
        tpara.append(Paragraph('Data Citation: ' + stmp, pstyle))
        # ---Data URL------------------
        stmp = xlipd.extract_string1(LPub, 'dataUrl', False, 'NA')
        stmp1 = None
        i = stmp.upper().find('DOI:')
        if i >= 0:
            stmp = 'https://doi.org/' + stmp[i+4:].strip()
        # end if
        i = stmp.upper().find('HTTP')
        if i >= 0:
            stmp1 = stmp
        # end if
        stmp = trim_string('Data URL: ' + stmp, 'Helvetica', 8, twidth)
        stmp = stmp[10:]
        if not stmp1 is None:
            stmp = '<link href="' + stmp1 + '" color="blue"><u>' + stmp + '</u></link>'
        # end if
        tpara.append(Paragraph('Data URL: ' + stmp, pstyle))
        # ---Table---------------------
        tdata = [[tpara]]
        t = Table(tdata, colWidths=twidth, rowHeights=theight, style=tstyle)
        t.wrapOn(c, twidth, theight)
        t.drawOn(c, i_xloc + 0.5*cm, i_yloc + i_height - 1.7*cm - theight)

        # Write metadata in column 2:
        tpara = []
        # ---Data-------
        stmp = xlipd.extract_string1(LMeta['geo'], 'siteName', False, 'NA')
        tpara.append(Paragraph('Site Name: ' + stmp, pstyle))
        # ----------
        stmp = xlipd.extract_string1(LMeta, 'archiveType', False, 'NA')
        tpara.append(Paragraph('Archive Type: ' + stmp, pstyle))
        # ----------
        stmp = xlipd.extract_string1(LTab['columns'][x_col_2], 'variableType', False, 'NA')
        #stmp = 'Proxy'
        tpara.append(Paragraph('Variable Type: ' + stmp, pstyle))
        # ----------
        stmp = xlipd.extract_string1(LTab['columns'][x_col_2], 'variableName', False, 'NA')
        tpara.append(Paragraph('Variable Name: ' + stmp, pstyle))
        # ----------
        stmp = xlipd.extract_string1(LTab['columns'][x_col_2], 'units', False, 'NA')
        tpara.append(Paragraph('Variable Units: ' + stmp, pstyle))
        # ----------
        if x_type == 'PROXY':
            stmp = xlipd.extract_string1(LTab['columns'][x_col_2], 'climateParameter', False, 'NA')
            tpara.append(Paragraph('Climate Parameter: ' + stmp, pstyle))
        # end if
        # ----------
        stmp = xlipd.extract_string1(LTab['columns'][x_col_1], 'startYear', False, 'NA')
        if is_number(stmp): stmp = str(int(float(stmp)))
        tpara.append(Paragraph('Start Year: ' + stmp + ' CE', pstyle))
        # ----------
        stmp = xlipd.extract_string1(LTab['columns'][x_col_1], 'endYear', False, 'NA')
        if is_number(stmp): stmp = str(int(float(stmp)))
        tpara.append(Paragraph('End Year: ' + stmp + ' CE', pstyle))
        # ---Table-------
        tdata = [[tpara]]
        t = Table(tdata, colWidths=twidth, rowHeights=theight, style=tstyle)
        t.wrapOn(c, twidth, theight)
        t.drawOn(c, i_xloc + 1.0*cm + twidth, i_yloc + i_height - 1.7*cm - theight)


        # ---Time Series Graph-------------------------------------------------

        # Replace data values of "-999" within tolerance with NaN:
        x_df.loc[abs(x_df[x_col_2] + 999.0) < 0.001, x_col_2] = np.nan

        # Get axis labels:
        stmp = xlipd.extract_string1(LTab['columns'][x_col_1], 'variableName', False, 'NA')
        stmp1 = xlipd.extract_string1(LTab['columns'][x_col_1], 'units', False, 'NA')
        if stmp1.strip().upper() in ['UNITLESS', 'NA']: stmp1 = '-'
        x_label = stmp + ' (' + stmp1 + ')'
        # ----------
        stmp = xlipd.extract_string1(LTab['columns'][x_col_2], 'variableName', False, 'NA')
        if x_interp:
            stmp1 = xlipd.extract_string1(LTab['columns'][x_col_2]['interpretationFormat'], 'format', False, 'NA')
        else:
            stmp1 = xlipd.extract_string1(LTab['columns'][x_col_2], 'units', False, 'NA')
        # end if
        if stmp1.strip().upper() in ['UNITLESS', 'NA']: stmp1 = '-'
        y_label = stmp + ' (' + stmp1 + ')'
        y_label = textwrap.fill(y_label, 40)

        # Make graph:
        fig = plt.figure(figsize=(12, 6))
        plt.xlabel(x_label, fontsize=14, fontweight='bold', wrap=True)
        plt.ylabel(y_label, fontsize=14, fontweight='bold', wrap=True)
        if x_type == 'PROXY':
            if x_interp:
                ymin = min(-3.0, min(x_df.iloc[:,x_col_2])) * 1.05
                ymax = max( 3.0, max(x_df.iloc[:,x_col_2])) * 1.05
                plt.ylim([ymin, ymax])
                plt.axhline(0.0, color='grey', linewidth=0.5, zorder=1)
                plt.bar(x_df.iloc[:,x_col_1], x_df.iloc[:,x_col_2], 
                        width=1.0, color=source_fc, linewidth=0.5,
                        edgecolor=source_ec, zorder=2)
            else:
                plt.plot(x_df.iloc[:,x_col_1], x_df.iloc[:,x_col_2], 
                         color=source_lc, linewidth=0.5,
                         marker='o', markersize=5.0, markerfacecolor=source_fc,
                         markeredgecolor=source_ec, markeredgewidth=1.0)
            # end if
        else:
            if x_interp:
                ymin = min(-3.0, min(x_df.iloc[:,x_col_2])) * 1.05
                ymax = max( 3.0, max(x_df.iloc[:,x_col_2])) * 1.05
                plt.ylim([ymin, ymax])
                plt.axhline(0.0, color='grey', linewidth=0.5, zorder=1)
                plt.bar(x_df.iloc[:,x_col_1], x_df.iloc[:,x_col_2], 
                        width=1.0, color=target_fc, linewidth=0.5,
                        edgecolor=target_ec, zorder=2)
            else:
                plt.plot(x_df.iloc[:,x_col_1], x_df.iloc[:,x_col_2], 
                         color=target_lc, linewidth=0.5,
                         marker='o', markersize=5.0, markerfacecolor=target_fc,
                         markeredgecolor=target_ec, markeredgewidth=1.0)
            # end if
        # end if

        # Show graph:
        #plt.show()
     
        # Put graph on PDF as PNG:
        # imgdata = io.BytesIO()
        # fig.savefig(imgdata, dpi=fig_dpi, format='png', bbox_inches='tight')
        # imgdata.seek(0)  # rewind the data
        # imgreader = ImageReader(imgdata)
        # c.drawImage(imgreader, i_xloc+0.5*cm, i_yloc+0.5*cm, 12*cm, 6*cm)

        # Put graph on PDF as SVG:
        svg_file = io.BytesIO()
        fig.savefig(svg_file, format='svg', bbox_inches='tight')
        svg_file.seek(0)  # rewind the data
        drawing = svg2rlg(svg_file)
        scaled_drawing = resize_drawing(drawing, 'height', 6*cm)    
        renderPDF.draw(scaled_drawing, c, i_xloc+0.5*cm, i_yloc+0.5*cm)

        # Close graph:
        plt.close()

    
        # ---Locality Map------------------------------------------------------

        # Get coordinates:
        plon = LMeta['geo']['geometry']['coordinates'][0]
        plat = LMeta['geo']['geometry']['coordinates'][1]
        proj = ccrs.Orthographic(central_longitude=plon, central_latitude=plat)
        proj._threshold /= 100.0  # To make geodesic lines smoother

        # Create map:
        fig = plt.figure(figsize=(5, 5))
        ax = plt.axes(projection=proj)
    
        # Add coastlines and grid:
        ax.coastlines(resolution='110m', zorder=1)
        ax.gridlines(zorder=1)
        ax.set_global()
    
        # Add location point:
        # plt.scatter(plon, plat, s=50, c=(0.0,0.0,1.0,0.35), marker='o',
        #             edgecolors='blue', linewidths=1,
        #             transform=proj)
        #             #transform=ccrs.PlateCarree())
    
        # Add bounding box or circle with user-defined radius:
        # proj = ccrs.Orthographic(central_longitude=plon, central_latitude=plat)
        # r_ortho = compute_radius(plon, plat, proj, bbox_dx/2)
        # ax.add_patch(mpatches.Circle(xy=[plon, plat],
        #                                 radius=r_ortho,
        #                                 facecolor=(0.0,0.0,1.0,0.15),
        #                                 edgecolor='blue', linewidth=1,
        #                                 transform=proj))
        # ax.add_patch(mpatches.Rectangle(xy=[plon-r_ortho, plat-r_ortho],
        #                                 width=2*r_ortho, height=2*r_ortho,
        #                                 facecolor=(0.0,0.0,1.0,0.15), 
        #                                 edgecolor='blue', linewidth=1,
        #                                 transform=proj))

        # Add target bounding box or point:
        bbstr = LMeta['geo']['detailedCoordinates']['target']['values']
        if bbstr is None: bbstr = 'NA,NA,NA,NA,NA'
        bbstrs = [x for x in bbstr.split(',')]
        if is_number(bbstrs[0]):
            bblon1 = float(bbstrs[0])
            if is_number(bbstrs[1]):
                bblon2 = float(bbstrs[1])
            else:
                bblon2 = bblon1
            # end if
            bblat1 = float(bbstrs[2])
            if is_number(bbstrs[3]):
                bblat2 = float(bbstrs[3])
            else:
                bblat2 = bblat1
            # end if
            if (bblon1 < 0.0): bblon1 += 360.0  # Deal with +/-180 degrees
            if (bblon2 < 0.0): bblon2 += 360.0  # Deal with +/-180 degrees
            if abs(bblon2-bblon1) > 1.0 and abs(bblat2-bblat1) > 1.0:
                poly_corners = np.zeros((4, 2), np.float64)
                poly_corners[:,0] = [bblon1, bblon2, bblon2, bblon1]  # Anticlockwise from bottom left
                poly_corners[:,1] = [bblat1, bblat1, bblat2, bblat2]
                p = shapely.geometry.Polygon(poly_corners)
                if p.exterior.is_ccw == False:
                    poly_corners = np.flip(poly_corners, axis=0)  # Fix polygon orientation 
                ax.add_patch(mpatches.Polygon(poly_corners, closed=True, fill=True,
                                              fc=target_pc, ec=target_ec, lw=1.0,
                                              transform=ccrs.Geodetic()))
            else:
                plt.scatter(bblon1, bblat1, marker='D', s=50,
                            c=np.atleast_2d(target_pc), ec=target_ec, lw=1.0,
                            transform=ccrs.PlateCarree())
            # end if
        # end if

        # Add source bounding box or point:
        bbstr = LMeta['geo']['detailedCoordinates']['source']['values']
        if bbstr is None: bbstr = 'NA,NA,NA,NA,NA'
        bbstrs = [x for x in bbstr.split(',')]
        if is_number(bbstrs[0]):
            bblon1 = float(bbstrs[0])
            if is_number(bbstrs[1]):
                bblon2 = float(bbstrs[1])
            else:
                bblon2 = bblon1
            # end if
            bblat1 = float(bbstrs[2])
            if is_number(bbstrs[3]):
                bblat2 = float(bbstrs[3])
            else:
                bblat2 = bblat1
            # end if
            if (bblon1 < 0.0): bblon1 += 360.0  # Deal with +/-180 degrees
            if (bblon2 < 0.0): bblon2 += 360.0  # Deal with +/-180 degrees
            if abs(bblon2-bblon1) > 1.0 and abs(bblat2-bblat1) > 1.0:
                poly_corners = np.zeros((4, 2), np.float64)
                poly_corners[:,0] = [bblon1, bblon2, bblon2, bblon1]  # Anticlockwise from bottom left
                poly_corners[:,1] = [bblat1, bblat1, bblat2, bblat2]
                p = shapely.geometry.Polygon(poly_corners)
                if p.exterior.is_ccw == False:
                    poly_corners = np.flip(poly_corners, axis=0)  # Fix polygon orientation 
                ax.add_patch(mpatches.Polygon(poly_corners, closed=True, fill=True,
                                              fc=source_pc, ec=source_ec, lw=1.0, 
                                              transform=ccrs.Geodetic()))
            else:
                plt.scatter(bblon1, bblat1, marker='s', s=50, 
                            c=np.atleast_2d(source_pc), ec=source_ec, lw=1.0,
                            transform=ccrs.PlateCarree())
            # end if
        # end if

        # plt.scatter(plon, plat, marker='s', s=50, 
        #             c=np.atleast_2d(source_pc), ec=source_ec, lw=1.0,
        #             transform=ccrs.PlateCarree())


        # Add custom legend:
        if map_legend_flag:
            legend_elements = [Line2D([0], [0], marker='s', label='Source',
                                      c=source_ec, lw=1.0,
                                      mfc=source_fc, mec=source_ec, mew=1.0),
                               Line2D([0], [0], marker='D', label='Target',
                                      c=target_ec, lw=1.0,
                                      mfc=target_fc, mec=target_ec, mew=1.0)]
            ax.legend(handles=legend_elements, loc='upper right')
        # end if

        # Show graph:
        # plt.show()
    
        # Put map on PDF as PNG:
        # imgdata = io.BytesIO()
        # fig.savefig(imgdata, dpi=fig_dpi, format='png', bbox_inches='tight')
        # imgdata.seek(0)  # rewind the data
        # imgreader = ImageReader(imgdata)
        # c.drawImage(imgreader, i_xloc + 13.25*cm, i_yloc + 1.25*cm, 5*cm, 5*cm)

        # Put graph on PDF as SVG:
        svg_file = io.BytesIO()
        fig.savefig(svg_file, format='svg', bbox_inches='tight')
        svg_file.seek(0)  # rewind the data
        drawing = svg2rlg(svg_file)
        scaled_drawing = resize_drawing(drawing, 'height', 5*cm)    
        renderPDF.draw(scaled_drawing, c, i_xloc + 13.25*cm, i_yloc + 1.25*cm)

        # Close graph:
        plt.close()

        #----------------------------------------------------------------------
        
    # end for

    # Save pdf:
    c.save()
    
    # Clean up:
    del x_df
elements =[]
styleS = getSampleStyleSheet()
styleS.add(ParagraphStyle(name='Left', alignment=TA_LEFT,fontName='Times-Bold',fontSize=14,spaceAfter=10))
elements.append(Paragraph(title, styleS["Left"]))

MakeTable()

if Layout == "Landscape8x11":
    PDF = scratch + r"\LandscapeMap.pdf"
    doc = SimpleDocTemplate(PDF, rightMargin = 72,bottomMargin=10, topMargin=10)
    doc.pagesize = landscape(A4)
elif Layout == "Portrait8x11":
    PDF = scratch + r"\PortraitMap.pdf"
    doc = SimpleDocTemplate(PDF, rightMargin = 72,bottomMargin=10, topMargin=10)
    doc.pagesize = portrait(A4)

doc.build(elements)


if WebMap == '#' or not WebMap:
    finalPdf = PDF
    # Set output file
    arcpy.SetParameterAsText(1, PDF)
    arcpy.AddMessage("  Finished")

else:
    if Layout == "Portrait8x11":
        LayoutFormat = "A4 Portrait"
        arcpy.ExportWebMap_server(WebMap, MapPDF,"PDF", "", LayoutFormat)
    else:
Example #23
0
def form_02(request_data):
    """
    Согласие на обработку персональных данных
    """
    # mother_card = Card.objects.get(pk=203793)
    # ind_card = Card.objects.filter(pk=203729).update(mother=mother_card)

    ind_card = Card.objects.get(pk=request_data["card_pk"])

    agents = SettingManager.get("patient_agents")
    agents_dict = ast.literal_eval(agents)

    #сравнить переданное значение параметра с представителями у карты.
    agent_status = False
    for k, v in request_data.items():
        if k in agents_dict.keys() and getattr(ind_card, k):
            patient_agent = getattr(ind_card, k)
            if patient_agent.pk == int(v):
                agent_relate = k
                print(patient_agent.individual.fio())
                agent_status = True
                #Если в параметре агентов есть нужный параметр и в базе он соотносится с пациентом, то дальше поиск не нужен
                break
    ind = ind_card.individual
    individual_age = ind.age()

    #Если владельцу карты меньше 15 лет и не передан представитель, то вернуть ошибку
    is_child = False
    patient_disabled = False
    if individual_age < SettingManager.get("child_age") and not agent_status:
        return False
    elif individual_age < 15 and agent_status:
        is_child = True
    elif agent_status:
        patient_disabled = True


    ind_doc = Document.objects.filter(individual=ind, is_active=True)
    individual_fio = ind.fio()
    individual_date_born = ind.bd()

    is_child =''


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

    if ind_card.main_address:
        main_address = ind_card.main_address
    else:
        main_address = "______________________________________________________________________"

    if ind_card.fact_address:
        fact_address = ind_card.fact_address
    elif ind_card.main_address:
        fact_address = main_address
    else:
        fact_address = "______________________________________________________________________"

    person_agent = ''
    patient_agent = ''

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

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

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

    styleSign = deepcopy(style)
    styleSign.firstLineIndent = 0
    styleSign.alignment = TA_LEFT
    styleSign.leading = 13

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

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

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

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

    objs = []

    objs = [
        Paragraph('СОГЛАСИЕ <br/> на обработку персональных данных {}'.format(is_child),styleCenterBold),
    ]

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

    objs.append(Spacer(1, 3 * mm))
    objs.append(Paragraph('Я, нижеподписавшийся {}&nbsp; {} г. рождения'. format(individual_fio, date_individual_born), styleSign))

    styleLeft = deepcopy(style)
    styleLeft.alignment =TA_LEFT
    objs.append(Paragraph('Зарегистрированный по адресу: {}'.format(main_address), styleSign))
    objs.append(Paragraph('Проживающий по адресу: {}'.format(fact_address), styleSign))
    objs.append(Paragraph('Документ, удостоверяющий личность паспорт: серия <u> {}</u> номер: <u>{}</u>'.
        format(document_passport_serial, document_passport_num),styleSign))
    objs.append(Paragraph('Выдан: {} {}'.format(document_passport_date_start,document_passport_issued), styleSign))
    objs.append(Spacer(1, 3 * mm))
    hospital_name = SettingManager.get("rmis_orgname")
    hospital_address = SettingManager.get("org_address")
    objs.append(Paragraph(', в соответствии с требованиями федерального закона от 27.07.2006 г. "О персональных данных" '
                          '№ 152-ФЗ, даю согласие Оператору: {} (далее – Оператор), находящегося по адресу: '
                          '{} на обработку моих и/или лица предствителем, которого я являюсь персональных данных (далее - Персональные данные),'
                          ' включающих: фамилию, имя, отчество, пол, дату рождения, адрес места жительства, контактные '
                          'телефон(ы), реквизиты полиса (ОМС, ДМС), страховой номер индивидуального лицевого счета в '
                          'Пенсионном фонде России (СНИЛС), данные паспорта (свидетельства о рождении ребёнка) '
                          '(номер, серия, кем и когда выдан), место работы (учебы) и должность, социальный статус, '
                          'семейное положение; любые сведения о состоянии '
                          'моего здоровья, и/или лица представителем которого я являюсь, заболеваниях, случаях обращения за медицинской помощью в следующих целях: '
                          'медико-профилактических, установления медицинского диагноза и оказания медицинских и медико-социальных услуг, '
                          'ведения медицинской карты пациента (на бумажных и безбумажных носителях); '
                          'реализации электронной записи к врачу; ведения персонифицированного учета оказанния медицинских '
                          'услуг; для реализации телемедицинских консультаций, электронного документооборота; осуществления '
                          'взаиморасчетов за оказанную медицинскую помощь в системе медицинского страхования (ОМС, ДМС); '
                          'хранения результатов исследований для последующего использования в установлении медицинского диагноза.'.
                          format(hospital_name, hospital_address), style))
    objs.append(Paragraph('Я согласен (согласна) на осмотр с применением телемедицинских технологий, а также на фото - и видеосъемку '
                          'в процессе лечения в интересах моего, или лица, представителем которого я являюсь обследования и лечения.', style))
    objs.append(Paragraph('Предоставляю Оператору право осуществлять любое действие (операцию) или совокупность действий '
                          '(операций) с использованием средств автоматизации и/или без использования таких средств с '
                          'Персональными данными , включая сбор, запись, '
                          'систематизацию, накопление, хранение, уточнение (обновление, изменение), извлечение, использование, '
                          'передачу (распространение, предоставление, доступ), обезличивание, блокирование, удаление, уничтожение', style))
    objs.append(Paragraph('В процессе оказания Оператором медицинской помощи субъекту персональных данных я предоставляю '
                          'право медицинским работникам передавать персональные данные, содержащие сведения, составляющие врачебную тайну, '
                          'другим должностным лицам Оператора, в интересах обследования и лечения, обслуживания документации, '
                          'программного обеспечения и технических средств. Я согласен с тем, что доступ к Персональным данным '
                          'будут иметь сотрудники Оператора, осуществляющие техническое обслуживание информационной системы.', style))
    objs.append(Paragraph('Я согласен (согласна) с тем, что в соответствии с частью 3 статьи 6 федерального закона от 27.07.2006 г. '
                          '"О персональных данных" № 152-ФЗ обработка указанных в настоящем согласии персональных данных '
                          'может быть поручена другим лицам, на основании соглашения между оператором и лицом. Я согласен '
                          'с тем, что в медико-профилактических целях, в целях установления медицинского диагноза и оказания '
                          'медицинских и медико-социальных услуг, указанные в настоящем согласии персональные данные могут '
                          'быть переданы в другие лечебно-профилактические учреждения для обработки лицом, профессионально '
                          'занимающимся медицинской деятельностью и обязанным в соответствии с законодательством '
                          'Российской Федерации сохранять врачебную тайну. Я согласен (согласна) с тем, что в целях осуществления '
                          'медицинского страхования(обязательного/добровольного) персональные данные могут быть переданы в страховую медицинскую '
                          'организацию и территориальный фонд ОМС с использованием машинных носителей или по каналам связи, '
                          'с соблюдением мер, обеспечивающих их защиту от несанкционированного доступа. Я согласен (согласна) '
                          'с тем, что в научных целях указанные в настоящем согласии персональные данные могут быть переданы '
                          'в научные и образовательные организации, а также предоставляться доступ к ним обучающимся, '
                          'ординаторам и аспирантам медицинских учебных учреждений. Срок хранения персональных данных '
                          'соответствует сроку хранения первичных медицинских документов и составляет двадцать пять лет. '
                          'Настоящее согласие действует бессрочно. Я оставляю за собой право отозвать свое согласие посредством '
                          'составления соответствующего письменного документа, который может быть направлен мной в адрес '
                          'Оператора по почте заказным письмом с уведомлением о вручении либо вручен лично под расписку '
                          'представителю Оператора. В случае получения моего письменного заявления об отзыве настоящего '
                          'согласия на обработку персональных данных, Оператор обязан прекратить их обработку в течение '
                          'периода времени, необходимого для завершения взаиморасчетов по оплате оказанной до этого медицинской помощи.', style))
    date_year = datetime.datetime.now().strftime('%Y')
    objs.append(Spacer(1, 5 * mm))
    space_bottom = ' &nbsp;'

    styleSign = deepcopy(style)
    styleSign.firstLineIndent = 0
    objs.append(Paragraph('\"___\"____________{} {} _________________________'.format(date_year, 35*space_bottom), styleSign))
    objs.append(Paragraph('{} (подпись) '.format(61 * space_bottom), style))

    objs.append(Paragraph('', style))
    objs.append(Paragraph('', style))




    doc.build(objs)
    pdf = buffer.getvalue()
    buffer.close()
    return pdf
Example #24
0
def imgtopdf(input_paths, outputpath):
    (maxw, maxh) = Image.open(input_paths).size
    c = canvas.Canvas(outputpath, pagesize=portrait((maxw, maxh)))
    c.drawImage(input_paths, 0, 0, maxw, maxh)
    c.showPage()
    c.save()
Example #25
0
def birdcare_worksheet(request):

    try:

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

        today = datetime.date.today()

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

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

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

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

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

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

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

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

        for i in cage_list:

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

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

            header_string = cage.name

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

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

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

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

                    if couple_remove_nest:
                        header_string = header_string + 'remove nest '

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

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

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

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

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

            span_id = 4
            if days_since_data:
                span_id = 6

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

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

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

                table = Table(data, style=bst)

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

            elif not coupling:

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

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

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

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

            elif coupling:

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

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

                table = Table(data, style=bst)

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

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

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

        return pdf_close_and_return(doc, Story, buffer, response)

    except:
        return server_error(request)
Example #26
0
 def __init__(self, title=None, page_size=portrait(A4)):
     self.title = title or ''
     self.text_width = page_size[0] - 2 * self.MARGIN
Example #27
0
     'pagesize': None,
 }),
 ('a4_a6l', {
     'name': gettext_lazy('4 landscape A6 pages on one A4 page'),
     'cols': 2,
     'rows': 2,
     'margins': [0 * mm, 0 * mm, 0 * mm, 0 * mm],
     'offsets': [pagesizes.landscape(pagesizes.A4)[0] / 2, pagesizes.landscape(pagesizes.A4)[1] / 2],
     'pagesize': pagesizes.landscape(pagesizes.A4),
 }),
 ('a4_a6p', {
     'name': gettext_lazy('4 portrait A6 pages on one A4 page'),
     'cols': 2,
     'rows': 2,
     'margins': [0 * mm, 0 * mm, 0 * mm, 0 * mm],
     'offsets': [pagesizes.portrait(pagesizes.A4)[0] / 2, pagesizes.portrait(pagesizes.A4)[0] / 2],
     'pagesize': pagesizes.portrait(pagesizes.A4),
 }),
 ('a4_a7l', {
     'name': gettext_lazy('8 landscape A7 pages on one A4 page'),
     'cols': 2,
     'rows': 4,
     'margins': [0 * mm, 0 * mm, 0 * mm, 0 * mm],
     'offsets': [pagesizes.portrait(pagesizes.A4)[0] / 2, pagesizes.portrait(pagesizes.A4)[1] / 4],
     'pagesize': pagesizes.portrait(pagesizes.A4),
 }),
 ('a4_a7p', {
     'name': gettext_lazy('8 portrait A7 pages on one A4 page'),
     'cols': 4,
     'rows': 2,
     'margins': [0 * mm, 0 * mm, 0 * mm, 0 * mm],
Example #28
0
def bird_generate_pdf(request, bird_id):

    try:

        bird = get_object_or_404(Bird, id=bird_id)
        offspring = find_offspring(bird.id)
        activities = Activity.objects.filter(
            bird=bird).order_by('start_date').reverse()

        title = bird.name
        author = 'Andreas Kotowicz'

        Story, buffer, doc, response = pdf_header(page_size=portrait(A4),
                                                  filename="birdsheet.pdf",
                                                  title=title,
                                                  author=author)

        Story = add_title(title, Story, request, title_size=14)
        ''' INFO '''
        Story.append(Spacer(1, 15))
        ptext = '<font size=13>Info</font>'
        styles = getSampleStyleSheet()
        Story.append(Paragraph(ptext, styles["Heading1"]))

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

        tags = bird.tags
        if tags:
            tags = Paragraph(tags * 1, style)

        data = [[
            'Birthday:', bird.date_of_birth, 'Age Uncertainty:',
            bird.age_uncertainty
        ], ['Sex:', bird.get_sex_display(), 'Species:', bird.species],
                ['Father:',
                 bird.get_father(), 'Mother:',
                 bird.get_mother()],
                ['Cage:', bird.cage.name, 'Brood:', bird.brood],
                ['Missing since:', bird.date_of_birth, 'Tags:', tags],
                [
                    'Reserved until:', bird.reserved_until, 'Reserved by:',
                    bird.reserved_by
                ],
                [
                    'Exit Date:', bird.exit_date, 'Cause of exit:',
                    bird.get_cause_of_exit_display()
                ], [
                    'Comment:',
                    comment,
                ]]

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

        colwidths = (90, 170, 90, 200)
        table = Table(data, colwidths, style=ts, repeatRows=1)
        Story.append(table)
        ''' OFFSPRING '''
        Story.append(Spacer(1, 15))
        ptext = '<font size=13>Offspring</font>'
        styles = getSampleStyleSheet()
        Story.append(Paragraph(ptext, styles["Heading1"]))

        offspring_str = ''
        nbr_offspring = offspring.__len__()
        nbr_offspring = nbr_offspring - 1
        if nbr_offspring > 0:
            for i in enumerate(offspring):
                if i[0] == 0:
                    offspring_str = i[1].name
                elif i[0] == nbr_offspring:
                    offspring_str = offspring_str + ', ' + i[1].name + '.'
                else:
                    offspring_str = offspring_str + ', ' + i[1].name
        else:
            offspring_str = 'No offspring.'

        ptext = '<font size=10>%s</font>' % offspring_str
        styles = getSampleStyleSheet()
        Story.append(Paragraph(ptext, styles["Normal"]))
        ''' ACTIVITIES '''
        Story.append(Spacer(1, 15))
        ptext = '<font size=13>Activities</font>'
        styles = getSampleStyleSheet()
        Story.append(Paragraph(ptext, styles["Heading1"]))

        data = [['type', 'content', 'start date', 'end date', 'user']]

        for i in activities:
            content = i.activity_content
            if content:
                content = content.replace('&', '&amp;')
                content = Paragraph(content * 1, style)
            data.append([
                i.activity_type, content, i.start_date, i.end_date,
                i.originator
            ])

        ts = TableStyle([('LINEABOVE', (0, 0), (-1, 0), 2, colors.black),
                         ('LINEBELOW', (0, 0), (-1, 0), 2, colors.black),
                         ('LINEABOVE', (0, 1), (-1, -1), 0.25, colors.black),
                         ('LINEBELOW', (0, -1), (-1, -1), 2, colors.black),
                         ('INNERGRID', (0, 0), (-1, -1), 0.15, colors.black),
                         ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold', 10),
                         ('FONT', (0, 1), (-1, -1), 'Helvetica', 9),
                         ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                         ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                         ('ALIGN', (4, 1), (-1, -1), 'LEFT'),
                         ('ALIGN', (1, 1), (-1, -1), 'LEFT')])

        colwidths = (90, 270, 60, 60, 60)
        table = Table(data, colwidths, style=ts, repeatRows=1)
        Story.append(table)

        return pdf_close_and_return(doc, Story, buffer, response)

    except:
        return server_error(request)
Example #29
0
def reportGen(request):
    response = HttpResponse(content_type="application/pdf")
    # response['Content-Disposition'] = 'attachement; filename=acs.pdf'
    doc = SimpleDocTemplate(response, pagesize=A4, rightMargin=30, leftMargin=30, topMargin=30, bottomMargin=18)
    doc.pagesize = portrait(A4)

    h1 = PS(name="Heading1", fontSize=14, leading=30, leftIndent=170)

    h2 = PS(name="Heading1", fontSize=12, leading=20, leftIndent=30, spaceAfter=20)

    # Table Headers
    elements = []
    elements.append(Paragraph("<b>Damage Assessment Format</b>", h1))
    elements.append(
        Paragraph(
            "<i>[In-depth sectoral Assessment to have medium and long-term relief, rehabilitation and reconstruction assistance for critical sectors, assessment to be carried out by specialist]</i>",
            h2,
        )
    )

    context = {}
    context["Food"] = Food.objects.values_list()
    context["FoodData"] = {}

    for listItems in context["Food"]:
        if listItems[1] in context["FoodData"]:
            context["FoodData"][listItems[1]] = context["FoodData"][listItems[1]] + int(listItems[2])
        else:
            context["FoodData"][listItems[1]] = listItems[2]

    Data = [["<b>Food Type Requirement</b>", "<b>Information</b>"]]

    for key, values in context["FoodData"].iteritems():
        Data.append([key, str(values)])

    Data.append(["", ""])
    Data.append(["<b>Victim Affected</b>", "<b>Information</b>"])

    context = {}
    context["Victim"] = Victims.objects.values_list()
    context["VictimData"] = {}

    for listItems in context["Victim"]:
        if listItems[1] in context["VictimData"]:
            context["VictimData"][listItems[1]] = context["VictimData"][listItems[1]] + int(listItems[2])
        else:
            context["VictimData"][listItems[1]] = listItems[2]

    for key, values in context["VictimData"].iteritems():
        Data.append([key, str(values)])

    Data.append(["", ""])
    Data.append(["<b> Health Situation</b>", "<b>Information</b>"])

    context = {}
    context["Health"] = Health.objects.values_list()
    context["HealthData"] = {}

    for listItems in context["Health"]:
        if listItems[1] in context["HealthData"]:
            context["HealthData"][listItems[1]] = context["HealthData"][listItems[1]] + int(listItems[2])
        else:
            context["HealthData"][listItems[1]] = listItems[2]

    for key, values in context["HealthData"].iteritems():
        Data.append([key, str(values)])

    Data.append(["", ""])
    Data.append(["<b> Shelter Situation</b>", "<b>Information</b>"])

    context = {}
    context["Shelter"] = Shelter.objects.values_list()
    context["ShelterData"] = {}

    for listItems in context["Shelter"]:
        if listItems[1] in context["ShelterData"]:
            context["ShelterData"][listItems[1]] = context["ShelterData"][listItems[1]] + int(listItems[2])
        else:
            context["ShelterData"][listItems[1]] = listItems[2]

    for key, values in context["ShelterData"].iteritems():
        Data.append([key, str(values)])

    context["countIMG"] = Files.objects.filter(Type="IMG").count()
    context["countVID"] = Files.objects.filter(Type="VID").count()
    context["countSMS"] = Files.objects.filter(Type="SMS").count()
    context["countTXT"] = Files.objects.filter(Type="TXT").count()
    context["countAUD"] = Files.objects.filter(Type="AUD").count()

    Data.append(["", ""])
    Data.append(["<b>Types of Files in DropBox</b>", "<b>Information</b>"])
    Data.append(["Image Files", str(context["countIMG"])])
    Data.append(["Video Files", str(context["countVID"])])
    Data.append(["Audio Files", str(context["countAUD"])])
    Data.append(["Text Files", str(context["countTXT"])])
    Data.append(["SMS Files", str(context["countSMS"])])

    # TODO: Get this line right instead of just copying it from the docs
    style = TableStyle(
        [
            ("ALIGN", (1, 1), (-2, -2), "RIGHT"),
            ("TEXTCOLOR", (1, 1), (-2, -2), colors.red),
            ("VALIGN", (0, 0), (0, -1), "TOP"),
            ("TEXTCOLOR", (0, 0), (0, -1), colors.blue),
            ("FONTSIZE", (0, 1), (-1, 1), 18),
            ("TEXTFONT", (0, 1), (-1, 1), "Times-Bold"),
            ("ALIGN", (0, -1), (-1, -1), "CENTER"),
            ("VALIGN", (0, -1), (-1, -1), "MIDDLE"),
            ("TEXTCOLOR", (0, -1), (-1, -1), colors.green),
            ("INNERGRID", (0, 0), (-1, -1), 0.25, colors.black),
            ("BOX", (0, 0), (-1, -1), 0.25, colors.black),
        ]
    )

    # Configure style and word wrap
    s = getSampleStyleSheet()
    s = s["BodyText"]
    s.wordWrap = "CJK"
    Data2 = [[Paragraph(cell, s) for cell in row] for row in Data]

    t = Table(Data2)

    t.setStyle(style)

    # Send the data and build the file
    elements.append(t)

    doc.build(elements)
    return response
Example #30
0
def BillPrint(request):

	text_footer_stzef = "AppEm - Aplicacion para administracion de Empresas [email protected]"

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

	manageParameters = ManageParameters(request.db)
	data = request.GET

	cfac = data.get('cfac')

	factura = Fac.objects.using(request.db).get(cfac=cfac)
	factura_deta = Facdeta.objects.using(request.db).filter(cfac=factura)

	sucursal = factura.ccaja.csucur

	slug_company = manageParameters.get("slug_company")

	doc = SimpleDocTemplate(response, pagesize=A4, rightMargin=10,leftMargin=10, topMargin=0,bottomMargin=40)
	doc.pagesize = portrait((190, 1900))

	hr_linea = "___________________________________"

	elements = []
	MEDIA_ROOT = os.path.join('infa_web/static')
	url = MEDIA_ROOT + manageParameters.get("company_logo")
	image = Image(url, width=128, height=82)
	if slug_company == "fitness_juice":
		data_header = [
			[manageParameters.get("company_name")],
			[manageParameters.get("text_header_pos_bill")],
			[manageParameters.get("company_id_name") + " : " + manageParameters.get("company_id")],
			["I.V.I Serie 5205964"],
			[sucursal.nsucur],
			["Dir:" + sucursal.dirsucur],
			["Tel:" + sucursal.telsucur],
			["Cel:" + sucursal.celsucur],
		]
	elif slug_company == "roma_pizza":
		data_header = [
			[manageParameters.get("company_name")],
			[manageParameters.get("text_header_pos_bill")],
			[manageParameters.get("company_id_name") + " : " + manageParameters.get("company_id")],
			[sucursal.nsucur],
			[manageParameters.get("company_adress")],
			[manageParameters.get("company_telephone")+" - "+manageParameters.get("company_celphone")],
		]
	else:
		data_header = [
			[manageParameters.get("company_name")],
			[manageParameters.get("text_header_pos_bill")],
			[manageParameters.get("company_id_name") + " : " + manageParameters.get("company_id")],
			[sucursal.nsucur],
			["Dir:" + sucursal.dirsucur],
			["Tel:" + sucursal.telsucur],
			["Cel:" + sucursal.celsucur],
		]

	data = [
		["_______________ ", "________", "_____________"],
		["<br/><strong>Descripcion</strong>", "&nbsp;&nbsp;&nbsp;&nbsp;<strong>Cant</strong>", "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>Vr. Total</strong>"],
		["_______________ ", "________", "_____________"]
	]

	if slug_company == "fitness_juice":
		for facdeta in factura_deta:
			data.append([facdeta.carlos.ncorto[:10],str(int(facdeta.canti)),""])
			data.append(["IVI","",intcomma( int(facdeta.vtotal))])
	elif slug_company == "roma_pizza":
		for facdeta in factura_deta:
			data.append(["<br/>"+facdeta.carlos.ncorto,"&nbsp;&nbsp;&nbsp;&nbsp;"+str(int(facdeta.canti)),"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"+intcomma( int(facdeta.vtotal))])
	else:
		for facdeta in factura_deta:
			data.append([facdeta.carlos.ncorto[:10],str(int(facdeta.canti)),intcomma( int(facdeta.vtotal))])

	data.append(["_______________ ", "________", "_____________"])
	data.append(["<br/><strong>TOTAL</strong>","-------->","&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<strong>"+intcomma(int(factura.vttotal))+"</strong>"])
	data.append(["_______________ ", "________", "_____________"])

	style_table_header = TableStyle([
		('ALIGN',(1,1),(-2,-2),'RIGHT'),
		('TEXTCOLOR',(1,1),(-2,-2),colors.red),
		('VALIGN',(0,0),(0,-1),'TOP'),
		('TEXTCOLOR',(0,0),(0,-1),colors.blue),
		('ALIGN',(0,-1),(-1,-1),'LEFT'),
		('VALIGN',(0,-1),(-1,-1),'MIDDLE'),
		('TEXTCOLOR',(0,-1),(-1,-1),colors.green),

		('LEFTPADDING',(0,0),(-1,-1), 0),
		('RIGHTPADDING',(0,0),(-1,-1), 0),
		('TOPPADDING',(0,0),(-1,-1), 0),
		('BOTTOMPADDING',(0,0),(-1,-1), 0),
	    #('LINEABOVE', (0,0), (-1,0), 1, colors.black),
	    ('LINEBELOW', (0,-1), (-1,-1), 1, colors.black),
		#('BOX', (0,0), (-1,-1), 0.25, colors.black),
	])

	style_table_facdeta = TableStyle([
		('ALIGN',(1,1),(-2,-2),'RIGHT'),
		('TEXTCOLOR',(1,1),(-2,-2),colors.red),
		('VALIGN',(0,0),(0,-1),'TOP'),
		('TEXTCOLOR',(0,0),(0,-1),colors.blue),
		('ALIGN',(0,-1),(-1,-1),'LEFT'),
		('VALIGN',(0,-1),(-1,-1),'MIDDLE'),

		('LEFTPADDING',(0,0),(-1,-1), 0),
		('RIGHTPADDING',(0,0),(-1,-1), 0),
		('TOPPADDING',(0,0),(-1,-1), 0),
		('BOTTOMPADDING',(0,0),(-1,-1), 0),

		('TEXTCOLOR',(0,-1),(-1,-1),colors.green),
	])

	#Configure style and word wrap
	s = getSampleStyleSheet()

	s.add(ParagraphStyle(name='tirilla',fontSize=8,leading=12,rightMargin=0,leftMargin=0, topMargin=0,bottomMargin=0,alignment=TA_CENTER))
	s.add(ParagraphStyle(name='header',fontSize=8.5,leading=12,alignment=TA_CENTER))
	s.add(ParagraphStyle(name='body',fontSize=8,leading=12,alignment=TA_CENTER))

	bodytext = s["tirilla"]
	headertext = s["header"]
	#s.wordWrap = 'CJK'
	bodytext.wordWrap = 'LTR'
	data2 = [[Paragraph(cell, bodytext) for cell in row] for row in data]
	t=Table(data2)
	t.setStyle(style_table_facdeta)
	elements.append(image)
	data2_header = [[Paragraph(cell, headertext) for cell in row] for row in data_header]
	t_header=Table(data2_header)
	t_header.setStyle(style_table_header)

	elements.append(t_header)
	elements.append(Paragraph("<br/>Factura No. %s" % factura.cfac,s['tirilla']))

	elements.append(Paragraph("Fecha : %s " % timezone.localtime(factura.femi).strftime("%Y-%m-%d %H:%M:%S"),s['tirilla']))
	elements.append(Paragraph("Atendido por : %s <br/>" % factura.cvende.nvende,s['tirilla']))
	elements.append(t)
	elements.append(Paragraph(manageParameters.get("text_footer_pos_bill") ,s['body']))
	elements.append(Paragraph(hr_linea ,s['body']))
	elements.append(Paragraph(text_footer_stzef ,s['body']))
	elements.append(Paragraph(hr_linea ,s['body']))
	elements.append(Paragraph("." ,s['body']))
	doc.build(elements)

	return response
Example #31
0
def form_03(request_data):
    """
    Добровольное согласие на медицинское вмешательство
    --------------------------------------------------------------------------------------------------------------
    Приказ Министерства здравоохранения РФ от 20 декабря 2012 г. N 1177н
    "Об утверждении порядка дачи информированного добровольного согласия на медицинское вмешательство и
    отказа от медицинского вмешательства в отношении определенных видов медицинских вмешательств,
    форм информированного добровольного согласия на медицинское вмешательство и форм отказа
    от медицинского вмешательства" (с изменениями и дополнениями).

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

    objs = []

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

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

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

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

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

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



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

    styleFCenter = deepcopy(style)
    styleFCenter.alignment = TA_CENTER

    styleBottom = deepcopy(style)
    styleBottom.fontSize = 8

    space_symbol = '&nbsp;'

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

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

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

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

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


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



    doc.build(objs)
    pdf = buffer.getvalue()
    buffer.close()
    return pdf
Example #32
0
def make_report(infile, subdir='pdfs'):
    outdir = os.path.join(os.path.dirname(infile), subdir)
    try:
        os.makedirs(outdir)
    except OSError:
        pass

    basename = '.'.join(os.path.basename(infile).split('.')[:-1])
    outfile = os.path.join(outdir, basename + '.pdf')

    logger.info('Saving output to file ' + outfile)

    # Open the input FITS file and extract the HDUs.
    hdulist = pyfits.open(infile)
    kic_id = hdulist[0].header['kic_id']
    data_hdus = hdulist[1:-1]

    c = canvas.Canvas(outfile)
    page_width, page_height = portrait(letter)
    c.setPageSize((page_width,page_height))

    page_height /= inch
    page_width /= inch
    margin = 0.1
    bigmargin = 0.25
    fig_width = page_width - 2. * margin
    fig_height = 0.5 * page_height - 2. * margin
    color1 = 'CadetBlue'
    color2 = 'Chartreuse'
    alpha = 0.5
    edgecolor = 'black'
    markersize = 20

    count = len(data_hdus) / 2

    for i in xrange(0, len(data_hdus), 2):
        bls = data_hdus[i].data
        lc = data_hdus[i+1].data
        lchdr = data_hdus[i+1].header

        # Extract the light curve.
        time = lc['time']
        flux = lc['flux']
        yrng = np.ptp(flux)

        fig = plt.figure(figsize=(fig_width,fig_height), dpi=inch)

        try:
            period = lchdr['period']
            phase = lchdr['phase']
            duration = lchdr['duration']
            depth = lchdr['depth']

            pftime = np.mod(time, period)
            pftime2 = np.mod(time - phase + period / 2., period)
            signal_mask = ((pftime2 > 0.5 * period - 0.5 * duration) &
                (pftime2 < 0.5 * period + 0.5 * duration))

            plt.subplot(211)
            plt.scatter(time, flux, color=color1, edgecolor=edgecolor,
                alpha=alpha, s=markersize)
            plt.xlim(time[0], time[-1])
            plt.ylim(np.amin(flux) - 0.05 * yrng, np.amax(flux) + 0.05 * yrng)
            plt.xlabel(r'Time (BJD)')
            plt.ylabel(r'Flux')
            plt.title(r'KIC' + kic_id + r', pass #%d' % count)

            plt.subplot(212)
            plt.scatter(pftime[~signal_mask], flux[~signal_mask], color=color1,
                edgecolor=edgecolor, alpha=alpha, s=markersize)
            plt.scatter(pftime[signal_mask], flux[signal_mask],
                color=color2, edgecolor=edgecolor, alpha=alpha, s=markersize)
            plt.xlim(np.amin(pftime), np.amax(pftime))
            plt.ylim(np.amin(flux) - 0.05 * yrng, np.amax(flux) + 0.05 * yrng)
            plt.xlabel(r'Time (days)')
            plt.ylabel(r'Flux')
            plt.figtext(0.05, 0.02,
                r'P = %.4f, phi = %.2f, W = %.2f, delta = %.2g' % (period,
                phase / period, duration, depth))

            plt.tight_layout()
            plt.subplots_adjust(bottom=0.15)
        except KeyError:
            plt.subplot(111)
            plt.scatter(time, flux, color=color1, edgecolor=edgecolor,
                alpha=alpha, s=markersize)
            plt.xlim(time[0], time[-1])
            plt.ylim(np.amin(flux) - 0.05 * yrng, np.amax(flux) + 0.05 * yrng)
            plt.xlabel(r'Time (BJD)')
            plt.ylabel(r'Flux')
            plt.title(r'KIC' + kic_id + r', pass #%d' % count)

            plt.tight_layout()

        imgdata = cStringIO.StringIO()
        fig.savefig(imgdata, format='png')
        plt.close()
        imgdata.seek(0)
        img = ImageReader(imgdata)
        c.drawImage(img, margin * inch, 0.5 * page_height * inch,
            fig_width*inch, fig_height*inch)

        bls = np.array(bls, dtype=bls.dtype)

        ndx = np.argsort(-1. * bls['srsq_dip'])
        data = bls[ndx][0:15]
        data = data[['srsq_dip','duration_dip','depth_dip','midtime_dip']]
        data = data.tolist()
        data = map(lambda x: ('%.2e %.4f %.4f %.2f' % tuple(x)).split(), data)
        data.insert(0, ['Dip SR^2','Dip dur.','Dip depth','Dip mid.'])

        table = Table(data, colWidths=(inch,inch,inch,inch))
        w, h = table.wrapOn(c, page_width * inch, page_height * inch)
        table.drawOn(c, bigmargin * inch,
            0.5 * page_height * inch - h - bigmargin * inch)

        ndx = np.argsort(-1. * bls['srsq_blip'])
        data = bls[ndx][0:15]
        data = data[['srsq_blip','duration_blip','depth_blip','midtime_blip']]
        data = data.tolist()
        data = map(lambda x: ('%.2e %.4f %.4f %.2f' % tuple(x)).split(), data)
        data.insert(0, ['Blip SR^2','Blip dur.','Blip depth','Blip mid.'])

        table = Table(data, colWidths=(inch,inch,inch,inch))
        w, h = table.wrapOn(c, page_width * inch, page_height * inch)
        table.drawOn(c, page_width * inch - bigmargin * inch - w,
            0.5 * page_height * inch - h - bigmargin * inch)

        c.showPage()
        count -= 1

    c.save()
Example #33
0
if len(args) > 2:
    conf_file = './'+args[1]+'.conf'
    hkey = int(args[2])

#---- Configファイルロード ------
with open('./pdf_nouhin.conf','r',encoding="utf-8_sig") as f:
    conf = json.load(f)

#------ File Congig. --------
template_file = conf['file']['template']
output_file = conf['file']['output'] 
tmp_file = conf['file']['temporary']

#------ Make A4 size Canvas
w, h = portrait(A4)
cv = canvas.Canvas(tmp_file, pagesize=(w, h))

#--- Font Config 
font_size = 11
ttf_file = './ipaexg.ttf'
pdfmetrics.registerFont(TTFont('IPAexGothic', ttf_file))
#cv.setFont('IPAexGothic', font_size)
cv.setFont(conf['default']['font'],conf['default']['fontsize'])


#---- DB read ----

db = conf['DB']['database']
conn = sqlite3.connect(db)
Example #34
0
    def goSummaryPage(self, summaryfile, mainList):
        pagesize = portrait(letter)
        [PAGE_WIDTH, PAGE_HEIGHT] = pagesize[:2]
        PAGE_WIDTH = int(PAGE_WIDTH)
        PAGE_HEIGHT = int(PAGE_HEIGHT)
        styles = getSampleStyleSheet()

        doc = SimpleDocTemplate(summaryfile,
                                pagesize=letter,
                                topMargin=130,
                                bottomMargin=123)
        Story = []

        newdata = []
        newdata.append(['Date', 'City', 'State', 'Volume', 'Sheet Number(s)'])
        style = ParagraphStyle("cover",
                               parent=styles['Normal'],
                               fontName="Helvetica",
                               fontSize=9,
                               leading=9)

        years = mainList.keys()
        if self.is_aei == 'Y':
            years.sort(reverse=False)
        else:
            years.sort(reverse=True)

        for key in years:
            volumes = mainList[key]
            for v in volumes.values():
                [state, city, vol, year, sheets] = v[2:7]

                if vol == 'None':
                    vol = ""

                sheetnoText = ""
                sheets.sort()
                for sht in sheets:
                    sht = sht.lstrip("0").split('_')[0].split('-')[0].strip(
                        'A').strip('B').strip('C').strip('D').strip('E').strip(
                            'F')
                    sheetnoText = sheetnoText + sht + ', '
                sheetnoText = sheetnoText.rstrip(", ")

                newdata.append([
                    Paragraph(('<para alignment="left">%s</para>') % (_),
                              style)
                    for _ in [year, city, state, vol, sheetnoText]
                ])
        table = Table(newdata, colWidths=[80, 80, 80, 80, PAGE_WIDTH - 420])
        table.setStyle([
            ('FONT', (0, 0), (4, 0), 'Helvetica-Bold'),
            ('VALIGN', (0, 1), (-1, -1), 'TOP'),
            ('ALIGN', (0, 0), (4, 0), 'LEFT'),
            ('BOTTOMPADDING', [0, 0], [-1, -1], 5),
        ])
        Story.append(table)
        doc.build(Story,
                  onFirstPage=self.myFirstSummaryPage,
                  onLaterPages=self.myLaterSummaryPage)
        doc = None
Example #35
0
 def _create_pagesize(self,width,height):
     import reportlab.lib.pagesizes as ps
     return ps.portrait( (width * ps.inch, height * ps.inch))        
Example #36
0
def cages_with_occupancy_pdf(request):
    try:
        styles = getSampleStyleSheet()
        styleN = styles['Normal']
        styleH = styles['Heading3']
        styleH2 = styles['Heading4']

        ts = TableStyle([
            ('FONT', (0, 0), (-1, -1), 'Helvetica', 9),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ])

        cages = Cage.objects.filter(
            function__lte=Cage.FUNCTION_SOCIAL).order_by('room', 'name')
        rooms = cages.values_list('room',
                                  flat=True).order_by('room').distinct()
        title = "Cages and Occupancy"
        author = 'Andreas Kotowicz'

        Story, buffer, doc, response = pdf_header(page_size=portrait(A4),
                                                  filename="cages.pdf",
                                                  title=title,
                                                  author=author)
        Story = add_title(title, Story, request, title_size=14)

        Story.append(Spacer(1, 15))
        paragraph = Paragraph(
            'For each cage the (occupancy / capacity) are shown. Overcrowded cages are highlighted in bold face.',
            styleH2)
        Story.append(paragraph)
        Story.append(Spacer(1, 15))

        for i in rooms:
            cages_this_room = cages.filter(room__id=i)
            this_room = cages_this_room[0].room
            header_string = this_room.__str__()

            data = []

            counter = 0
            counter2 = 0
            nbr_cols = 4
            this_row = ['', '', '', '']
            nbr_cages_in_room = cages_this_room.__len__()
            for j in cages_this_room:
                counter = counter + 1
                counter2 = counter2 + 1

                this_cage = j.name + ' - (' + str(j.occupancy()) + '/' + str(
                    j.max_occupancy) + ')'
                if j.occupancy() > j.max_occupancy:
                    this_cage = '<b>' + this_cage + '</b>'

                this_cage = Paragraph(this_cage * 1, style)

                this_row[counter - 1] = this_cage
                if nbr_cols.__rmod__(
                        counter2) == 0 or nbr_cages_in_room == counter2:
                    data.append(this_row)
                    this_row = ['', '', '', '']
                    counter = 0

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

            colwidths = (140, 140, 140, 140)
            table = Table(data, colwidths, style=ts, repeatRows=1)
            Story.append(table)

        return pdf_close_and_return(doc, Story, buffer, response)
    except:
        return server_error(request)
Example #37
0
def generate_pdf(fname,lname,org):
	pWidth,pHeight = A4
	
	imgDoc = canvas.Canvas(temp_tag_pdf, pagesize=portrait(A4))
	imgDoc.setFillColor(grey)
	imgDoc.rect(0,0,pWidth,pHeight, fill=1) 
	imgPath = img1path
	imgDoc.drawImage(imgPath,1.5*inch,6*inch,5.5*inch,4*inch)   
	imgPath = img2path
	imgDoc.drawImage(imgPath,1.5*inch,1.5*inch,5.5*inch,4*inch)   
	imgDoc.save()

	c = canvas.Canvas(temp_name_pdf)
	c.setFont('Helvetica', 20)
	text = fname + ' '  + lname
	text_width = stringWidth(text, 'Helvetica', 20)
	y = 7.3*inch
	pdf_text_object = c.beginText((pWidth - text_width) / 2.0, y)
	pdf_text_object.textOut(text)
	c.drawText(pdf_text_object)

	c.setFont('Helvetica', 15)
	text = org
	text_width = stringWidth(text, 'Helvetica', 15)
	y = 7*inch
	c.setFillColorRGB(0.5,0.5,0.5)
	pdf_text_object = c.beginText((pWidth - text_width) / 2.0, y)
	pdf_text_object.textOut(text)
	c.drawText(pdf_text_object)

	c.setFont('Helvetica', 45)
	text = fname
	text_width = stringWidth(text, 'Helvetica', 45)
	y = 3*inch
	c.setFillColorRGB(1,1,1)
	pdf_text_object = c.beginText(1.7*inch, y)
	pdf_text_object.textOut(text)
	c.drawText(pdf_text_object)

	c.setFont('Helvetica', 35)
	text = lname
	text_width = stringWidth(text, 'Helvetica', 35)
	y = 2.5*inch
	c.setFillColorRGB(1,1,1)
	pdf_text_object = c.beginText(1.7*inch, y)
	pdf_text_object.textOut(text)
	c.drawText(pdf_text_object)

	c.setFont('Helvetica', 15)
	text = org
	text_width = stringWidth(text, 'Helvetica', 15)
	y = 2*inch
	c.setFillColorRGB(0.5,0.5,0.5)
	pdf_text_object = c.beginText(1.7*inch, y)
	pdf_text_object.textOut(text)
	c.drawText(pdf_text_object)

	c.save()

	# Use PyPDF to merge the image-PDF into the template
	overlay = PdfFileReader(file(temp_name_pdf,"rb")).getPage(0)
	page = PdfFileReader(file(temp_tag_pdf,"rb")).getPage(0)
	page.mergePage(overlay)

	#Save the result
	output = PdfFileWriter()
	output.addPage(page)
	output.write(file(final_folder + fname.replace(" ","_") +'_' + lname.replace(" ","_") +".pdf","w"))
Example #38
0
def main(
    infile,
    outfile,
    color,
    font,
    font_size,
    portrait,
    scale,
    no_times,
    no_weekends,
    start_monday,
):
    """
    Weekly schedule typesetter

    Visit <https://github.com/jwodder/schedule> for more information.
    """
    if font in available_fonts():
        font_name = font
    else:
        # Assume we've been given a path to a .ttf file
        font_name = "CustomFont"
        ### TODO: Use the basename of the filename as the font name?  (Could
        ### that ever cause problems?)
        pdfmetrics.registerFont(TTFont(font_name, font))
    if portrait:
        page_width, page_height = pagesizes.portrait(pagesizes.letter)
    else:
        page_width, page_height = pagesizes.landscape(pagesizes.letter)
    colors = COLORS if color else [GREY]
    if no_weekends:
        week = WEEKDAYS_EN
    elif start_monday:
        week = FULL_WEEK_MON_EN
    else:
        week = FULL_WEEK_EN
    sched = Schedule(week)
    for ev in read_events(infile, colors=colors):
        sched.add_event(ev)
    if outfile is None:
        if infile is sys.stdin:
            outfile_name = "-"
        else:
            outfile_name = str(Path(infile.name).with_suffix(".pdf"))
        outfile = click.open_file(outfile_name, "wb")
    c = Canvas(outfile, (page_width, page_height))
    c.setFont(font_name, font_size)
    if scale is not None:
        factor = 1 / scale
        c.translate(
            (1 - factor) * page_width / 2,
            (1 - factor) * page_height / 2,
        )
        c.scale(factor, factor)
    sched.render(
        c,
        x=inch,
        y=page_height - inch,
        width=page_width - 2 * inch,
        height=page_height - 2 * inch,
        font_size=font_size,
        show_times=not no_times,
    )
    c.showPage()
    c.save()
Example #39
0
def birds_for_breeding_pdf(request, exact_method=False):
    try:
        styles = getSampleStyleSheet()
        styleN = styles['Normal']
        styleH = styles['Heading3']
        styleH2 = styles['Heading4']

        ts = TableStyle([
            ('FONT', (0, 0), (-1, -1), 'Helvetica', 9),
            ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold', 10),
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ])

        ts2 = TableStyle([
            ('FONT', (0, 0), (-1, -1), 'Helvetica', 7),
            ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold', 9),
            ('FONT', (6, 0), (6, 0), 'Helvetica-Bold', 6),
            ('FONT', (7, 0), (7, 0), 'Helvetica-Bold', 8),
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ])

        style = ParagraphStyle(
            name='Normal',
            fontName='Helvetica',
            fontSize=7,
        )
        ''' get list of animals '''
        from birdlist.utils.breeding import sort_birds_for_breeding, get_birds_for_breeding
        couples, males, females, males_id, females_id = get_birds_for_breeding(
            request.session, exact_method)
        couples, males, females, sort_by = sort_birds_for_breeding(
            couples, males, females, request.GET)
        ''' start document '''
        title = "Birds for breeding"
        author = 'Andreas Kotowicz'

        Story, buffer, doc, response = pdf_header(
            page_size=portrait(A4),
            filename="birds_for_breeding.pdf",
            title=title,
            author=author)
        Story = add_title(title, Story, request, title_size=14)

        Story.append(Spacer(1, 15))
        paragraph = Paragraph(
            'Please do not use birds that have been separated (previous breeding couple) less than 60 days ago!',
            styleH2)
        Story.append(paragraph)
        Story.append(Spacer(1, 15))

        colwidth0 = 40
        colwidth = 65
        colwidth2 = 80
        colwidth3 = 130
        ''' previous couples '''
        paragraph = Paragraph(
            "Previously successful couples - available today (%s)" %
            couples.__len__(), styleH)
        paragraph.keepWithNext = True
        Story.append(paragraph)
        data = [[
            'male', 'cage', 'age', 'female', 'cage', 'age', 'avg # broods',
            'avg # juveniles', '# days separated (m/f)'
        ]]
        for c in couples:
            data.append([c['male'], c['male_cage'], c['male_age'], c['female'], \
            c['female_cage'], c['female_age'], str(round(c['AvgNoBroods'], 1)), str(round(c['AvgNoJuvs'], 1)), \
            str(c['male_last_separation']) + ' / ' + str(c['female_last_separation'])])

        colwidths = (colwidth0, colwidth0, colwidth0, colwidth0, colwidth0,
                     colwidth0, colwidth2, colwidth2, colwidth3)
        table = Table(data, colwidths, style=ts, repeatRows=1)
        # table.keepWithNext = True
        Story.append(table)
        Story.append(Spacer(1, 15))
        ''' males '''
        paragraph = Paragraph(
            "Males for breeding - %s found" % males.__len__(), styleH)
        paragraph.keepWithNext = True
        Story.append(paragraph)
        data = [[
            'name', 'cage', 'age (+-)', 'father', 'mother', 'prev. mates',
            '# days\n separated', 'reserv.', 'comment'
        ]]
        for b in males:
            bird = b['bird']
            bird_name = bird.name
            if bird_name:
                bird_name = Paragraph(bird_name * 1, style)

            reserved = bird.reserved_until
            if reserved:
                reserved = 'Yes'

            mates = b['mates']
            if mates:
                mates = Paragraph(mates * 1, style)

            comment = bird.comment
            if comment:
                comment = Paragraph(comment * 1, style)

            father = b['father']
            if father:
                father = Paragraph(father.name * 1, style)

            mother = b['mother']
            if mother:
                mother = Paragraph(mother.name * 1, style)


            data.append([bird_name, bird.cage.name, \
            str(b['age']) + ' (' + str(bird.age_uncertainty) +' )', \
            father, mother, mates, b['last_separation'], \
            reserved, comment  ])

        colwidths = (47, 35, 45, 47, 47, \
                     colwidth3, colwidth0, colwidth0, colwidth3)
        table = Table(data, colwidths, style=ts2, repeatRows=1)
        table.keepWithNext = True
        Story.append(table)
        ''' space between '''

        spacer = Spacer(1, 15)
        spacer.keepWithNext = True
        Story.append(spacer)
        ''' females '''
        paragraph = Paragraph(
            "females for breeding - %s found" % females.__len__(), styleH)
        paragraph.keepWithNext = True
        Story.append(paragraph)
        data = [[
            'name', 'cage', 'age (+-)', 'father', 'mother', 'prev. mates',
            '# days\n separated', 'reserv.', 'comment'
        ]]
        for b in females:
            bird = b['bird']
            bird_name = bird.name
            if bird_name:
                bird_name = Paragraph(bird_name * 1, style)

            reserved = bird.reserved_until
            if reserved:
                reserved = 'Yes'

            mates = b['mates']
            if mates:
                mates = Paragraph(mates * 1, style)

            comment = bird.comment
            if comment:
                comment = Paragraph(comment * 1, style)

            father = b['father']
            if father:
                father = Paragraph(father.name * 1, style)

            mother = b['mother']
            if mother:
                mother = Paragraph(mother.name * 1, style)


            data.append([bird_name, bird.cage.name, \
            bird.get_phd() + ' (' + str(bird.age_uncertainty) +' )', \
            father, mother, mates, b['last_separation'], \
            reserved, comment  ])

        colwidths = (47, 35, 45, 47, 47, \
                     colwidth3, colwidth0, colwidth0, colwidth3)
        table = Table(data, colwidths, style=ts2, repeatRows=1)
        Story.append(table)

        return pdf_close_and_return(doc, Story, buffer, response)

    except:
        return server_error(request)
Example #40
0
         pagesizes.landscape(pagesizes.A4)[0] / 2,
         pagesizes.landscape(pagesizes.A4)[1] / 2
     ],
     'pagesize':
     pagesizes.landscape(pagesizes.A4),
 }),
 ('a4_a6p', {
     'name':
     gettext_lazy('4 portrait A6 pages on one A4 page'),
     'cols':
     2,
     'rows':
     2,
     'margins': [0 * mm, 0 * mm, 0 * mm, 0 * mm],
     'offsets': [
         pagesizes.portrait(pagesizes.A4)[0] / 2,
         pagesizes.portrait(pagesizes.A4)[0] / 2
     ],
     'pagesize':
     pagesizes.portrait(pagesizes.A4),
 }),
 ('a4_a7l', {
     'name':
     gettext_lazy('8 landscape A7 pages on one A4 page'),
     'cols':
     2,
     'rows':
     4,
     'margins': [0 * mm, 0 * mm, 0 * mm, 0 * mm],
     'offsets': [
         pagesizes.portrait(pagesizes.A4)[0] / 2,
Example #41
0
def form_02(request_data):
    """
    Форма 025/у - титульный лист амбулаторной карты
    Приказ Минздрава России от 15.12.2014 N 834н (ред. от 09.01.2018)
    """
    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 = SettingManager.get("org_title")
    hospital_address = SettingManager.get("org_address")
    hospital_kod_ogrn = SettingManager.get("org_ogrn", "<TODO:OGRN>")
    hospital_okpo = SettingManager.get("org_ogrn", "<TODO:OKPO>")

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

    document_passport = "Паспорт РФ"

    documents = forms_func.get_all_doc(ind_doc)
    document_passport_num = documents['passport']['num']
    document_passport_serial = documents['passport']['serial']
    document_passport_date_start = documents['passport']['date_start']
    document_passport_issued = documents['passport']['issued']
    document_polis = documents['polis']['num']
    document_snils = documents['snils']['num']

    indivudual_insurance_org = documents['polis']['issued']
    individual_benefit_code = "_________"

    ind_card_num = ind_card.number_with_type()
    ind_card_address = ind_card.main_address
    ind_card_phone = ", ".join(ind_card.get_phones())

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

    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()
    individual_fio = ind.fio()
    individual_date_born = ind.bd()

    doc = SimpleDocTemplate(buffer,
                            pagesize=A4,
                            leftMargin=25 * mm,
                            rightMargin=5 * mm,
                            topMargin=6 * mm,
                            bottomMargin=6 * mm,
                            allowSplitting=1,
                            title="Форма {}".format("025/у"))
    width, height = portrait(A4)
    styleSheet = getSampleStyleSheet()
    style = styleSheet["Normal"]
    style.fontName = "PTAstraSerifReg"
    style.fontSize = 10
    style.leading = 12
    style.spaceAfter = 0.5 * mm
    styleBold = deepcopy(style)
    styleBold.fontName = "PTAstraSerifBold"
    styleCenter = deepcopy(style)
    styleCenter.alignment = TA_CENTER
    styleCenter.fontSize = 12
    styleCenter.leading = 15
    styleCenter.spaceAfter = 1 * mm
    styleCenterBold = deepcopy(styleBold)
    styleCenterBold.alignment = TA_CENTER
    styleCenterBold.fontSize = 12
    styleCenterBold.leading = 15
    styleCenterBold.face = 'PTAstraSerifBold'
    styleJustified = deepcopy(style)
    styleJustified.alignment = TA_JUSTIFY
    styleJustified.spaceAfter = 4.5 * mm
    styleJustified.fontSize = 12
    styleJustified.leading = 4.5 * mm

    objs = []

    styleT = deepcopy(style)
    styleT.alignment = TA_LEFT
    styleT.fontSize = 10
    styleT.leading = 4.5 * mm
    styleT.face = 'PTAstraSerifReg'

    opinion = [
        [
            Paragraph(
                '<font size=11>{}<br/>Адрес: {}<br/>ОГРН: {} </font>'.format(
                    hospital_name, hospital_address, hospital_kod_ogrn),
                styleT),
            Paragraph(
                '<font size=9 >Код формы по ОКУД:<br/>Код организации по ОКПО: 31348613<br/>'
                'Медицинская документация<br/>Учетная форма № 025/у</font>',
                styleT)
        ],
    ]

    tbl = Table(opinion, 2 * [90 * mm])

    tbl.setStyle(
        TableStyle([
            ('GRID', (0, 0), (-1, -1), 0.75, colors.white),
            ('LEFTPADDING', (1, 0), (-1, -1), 80),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ]))

    objs.append(tbl)
    space_symbol = '&nbsp;'
    content_title = [
        Indenter(left=0 * mm),
        Spacer(1, 4 * mm),
        Paragraph(
            'МЕДИЦИНСКАЯ КАРТА ПАЦИЕНТА, <br/> ПОЛУЧАЮЩЕГО МЕДИЦИНСКУЮ ПОМОЩЬ В АМБУЛАТОРНЫХ УСЛОВИЯХ',
            styleCenter),
        Paragraph('{}№&nbsp;{}'.format(3 * space_symbol, ind_card_num),
                  styleCenterBold),
        Spacer(1, 2 * mm),
        Paragraph(
            '1.Дата заполнения медицинской карты: {}'.format(
                pytils.dt.ru_strftime(u"%d %B %Y",
                                      inflected=True,
                                      date=datetime.datetime.now())), style),
        Paragraph(
            "2. Фамилия, имя, отчество:<b> {} </b> ".format(individual_fio),
            style),
        Paragraph(
            '3. Пол: {} {} 4. Дата рождения: {}'.format(
                individual_sex, 3 * space_symbol, individual_date_born),
            style),
        Paragraph('5. Место регистрации: {}'.format(ind_card_address), style),
        Paragraph('тел. {}'.format(ind_card_phone), style),
        Paragraph('6. Местность: городская — 1, сельская — 2', style),
        Paragraph(
            '7. Полис ОМС: серия______№: {} {}'
            '8. СНИЛС: {}'.format(document_polis, 13 * space_symbol,
                                  document_snils), style),
        Paragraph(
            '9. Наименование страховой медицинской организации: {}'.format(
                indivudual_insurance_org), style),
        Paragraph(
            '10. Код категории льготы: {} {} 11. Документ: {} &nbsp; серия: {} &nbsp;&nbsp; №: {}'
            .format(individual_benefit_code, 35 * space_symbol,
                    document_passport, document_passport_serial,
                    document_passport_num), style),
        Paragraph(
            '12. Заболевания, по поводу которых осуществляется диспансерное наблюдение:',
            style),
        Spacer(1, 2 * mm),
    ]

    objs.extend(content_title)

    styleTCenter = deepcopy(styleT)
    styleTCenter.alignment = TA_CENTER
    styleTCenter.leading = 3.5 * mm

    opinion = [
        [
            Paragraph(
                '<font size=9>Дата начала диспансерного наблюдения </font>',
                styleTCenter),
            Paragraph(
                '<font size=9 >Дата прекращения диспансерного наблюдения</font>',
                styleTCenter),
            Paragraph('<font size=9 >Диагноз</font>', styleTCenter),
            Paragraph('<font size=9 >Код по МКБ-10</font>', styleTCenter),
            Paragraph('<font size=9 >Врач</font>', styleTCenter),
        ],
    ]
    for i in range(0, 5):
        para = ['', '', '', '', '']
        opinion.append(para)

    row_height = []
    for i in opinion:
        row_height.append(6 * mm)

    row_height[0] = None

    tbl = Table(opinion,
                colWidths=(27 * mm, 30 * mm, 75 * mm, 20 * mm, 27 * mm),
                rowHeights=row_height)

    tbl.setStyle(
        TableStyle([
            ('GRID', (0, 0), (-1, -1), 1.0, colors.black),
            ('VALIGN', (0, 0), (-1, 0), 'MIDDLE'),
        ]))

    objs.append(tbl)
    doc.build(objs)
    pdf = buffer.getvalue()
    buffer.close()
    return pdf
Example #42
0
    def __init__(self, aDocInfo, aStyleSheet):
        self.docInfo = aDocInfo
        self.style = aStyleSheet

        if "pageOrientation" in self.docInfo:
            self.orientation = self.docInfo["pageOrientation"]
        else:
            self.orientation = "portrait"

        if "pageSize" in self.docInfo:
            self.pageSize = self.docInfo["pageSize"]
        else:
            self.pageSize = A4

        if isinstance(self.pageSize, list):
            if len(self.pageSize) > 1:
                self.pageRect = [self.pageSize[0], self.pageSize[1]]
        else:
            self.pageRect = \
                landscape(self.pageSize) \
                if self.orientation == "landscape" \
                else portrait(self.pageSize)

        self.doc = DocTemplateWithToc('',
                                      outputfilepagesize=self.pageRect,
                                      leftMargin=self.style["marginL"],
                                      rightMargin=self.style["marginR"],
                                      topMargin=self.style["marginT"],
                                      bottomMargin=self.style["marginB"])

        portraitTempl = PageTemplate(id="portrait",
                                     frames=Frame(
                                         0,
                                         0,
                                         self.pageRect[0],
                                         self.pageRect[1],
                                         leftPadding=self.style["marginL"],
                                         bottomPadding=self.style["marginB"],
                                         rightPadding=self.style["marginR"],
                                         topPadding=self.style["marginT"]),
                                     onPageEnd=self.drawDecoration,
                                     pagesize=self.pageRect)
        self.doc.addPageTemplates(portraitTempl)

        landscapeTempl = PageTemplate(id="landscape",
                                      frames=Frame(
                                          0,
                                          0,
                                          self.pageRect[0],
                                          self.pageRect[1],
                                          leftPadding=self.style["marginL"],
                                          bottomPadding=self.style["marginB"],
                                          rightPadding=self.style["marginR"],
                                          topPadding=self.style["marginT"]),
                                      onPageEnd=self.drawDecoration,
                                      pagesize=self.pageRect)
        self.doc.addPageTemplates(landscapeTempl)

        self.doc.setDefaultTemplate(self.orientation)

        self.decorationItems = []
Example #43
0
    def generate_page(self,testNo):
        _pdfFile = 'Report ' + testNo + '.pdf'
        self.canvas = canvas.Canvas(_pdfFile,pagesize=portrait(A4))
        #width, height = A4
        _line = 0
    # header Text
        self.canvas.translate(mm,mm)
        self.canvas.setFont('Helvetica',32,leading=None)
        self.canvas.drawString(self.leftMargin*mm,260*mm,"Report")
        self.canvas.setFont('Helvetica',24,leading=None)
        self.canvas.drawRightString(190*mm,260*mm,"BS-EAY0A")
        self.canvas.line(self.leftMargin*mm,255*mm,190*mm,255*mm)

        self.canvas.setFont('Helvetica', 12, leading=None)
        self.setTextLine("EUT:", _line)
        self.setTextLine(self.currentTest.eut, _line, self.leftOffset2)
        _line += 1
        self.setTextLine("Serial-No.:", _line)
        self.setTextLine(self.currentTest.serial_no, _line, self.leftOffset2)
        _line += 1
        self.setTextLine("Model-No.:", _line)
        self.setTextLine(self.currentTest.model_no, _line, self.leftOffset2)
        _line += 1
        self.setTextLine("Model-Name.:", _line)
        self.setTextLine(self.currentTest.model_name, _line, self.leftOffset2)
        _line += 1

        self.setTextLine("EUT Environment:", _line)
        _line += 1

        _enList = self.currentTest.environment.split(',')
        for x in range (0,len(_enList)-1,2):
                self.setTextLine(_enList[x],_line, self.leftOffset1)
                self.setTextLine(_enList[x+1],_line, self.leftOffset2)
                _line += 1

        self.setTextLine("Company:", _line)
        self.setTextLine(self.currentTest.company, _line, self.leftOffset2)
        _line += 1
        self.setTextLine("Group:", _line)
        self.setTextLine(self.currentTest.lab, _line, self.leftOffset2)
        _line += 1
        self.setTextLine("Technician:", _line)
        self.setTextLine(self.currentTest.technician, _line, self.leftOffset2)
        _line += 1
        self.setTextLine("Test Procedure:", _line)
        self.setTextLine(self.currentTest.procedure, _line, self.leftOffset2)
        _line += 1
        self.setTextLine("Test Setup:", _line)
        self.setTextLine(self.currentTest.setup, _line, self.leftOffset2)
        _line += 1
        self.setTextLine("Test Result:", _line)
        self.setTextLine(self.currentTest.result, _line, self.leftOffset2)
        _line += 1
        self.setTextLine("TEMPEST Z-No.:", _line)
        self.setTextLine(self.currentTest.tempest_z_no, _line, self.leftOffset2)
        _line += 1
        self.setTextLine("Date:", _line)
        self.setTextLine(self.currentTest.date_time, _line, self.leftOffset2)
        _line += 1
        self.setTextLine("Label-No.:", _line)
        self.setTextLine(self.currentTest.label_no, _line, self.leftOffset2)
        _line += 1
        self.setTextLine("Comment:", _line)
        self.setTextLine(self.currentTest.comment, _line, self.leftOffset2)
        _line += 1

        self.canvas.setFont('Helvetica',12,leading=None)
        self.canvas.drawRightString(190*mm,16*mm,"2015.11.12 16:30")
        self.canvas.line(self.leftMargin*mm,15*mm,190*mm,15*mm)
        self.canvas.showPage()
        self.canvas.save()
        try:
            os.startfile(_pdfFile)
        except AttributeError:
            subprocess.call(['open', _pdfFile])
Example #44
0
def make_pdf(head, items, foot):
    output = BytesIO()
    psize = portrait(A4)
    xmargin = 15.0*mm
    p = canvas.Canvas(output, pagesize=psize, bottomup=True)
    # Title
    name = Option.get('office_name',  '')
    colw = (45.5*mm, 20.5*mm, 24.5*mm, 22.5*mm, 30.5*mm, 27.5*mm)
    data = [[head['ym'],'出勤簿','氏名:',head['name'],'所属:',name]]
    table = Table(data, colWidths=colw, rowHeights=8.0*mm)
    table.setStyle([
        ('FONT',   ( 0, 0), ( 1,-1), 'Gothic', 16),
        ('FONT',   ( 2, 0), (-1,-1), 'Gothic', 12),
        ('ALIGN',  ( 0, 0), (-1,-1), 'CENTER'),
        ('ALIGN',  ( 2, 0), ( 2,-1), 'RIGHT'),
        ('ALIGN',  ( 3, 0), ( 3,-1), 'LEFT'),
        ('ALIGN',  ( 4, 0), ( 4,-1), 'RIGHT'),
        ('ALIGN',  ( 5, 0), ( 5,-1), 'LEFT'),
    ])
    table.wrapOn(p, xmargin, 272.0*mm)
    table.drawOn(p, xmargin, 272.0*mm)
    # Detail
    colw = (10.0*mm, 10.0*mm, 16.5*mm, 16.5*mm, 16.5*mm, 20.5*mm, 16.5*mm, 10.5*mm, 10.5*mm, 10.5*mm, 47.0*mm)
    data =[
        ['日','曜日','始業','終業','休憩','時間','残業', '欠勤', '遅刻', '早退', '備考']
    ]
    for item in items:
        row = []
        if item  is not None:
            row.append(item['dd'])
            row.append(item['ww'])
            row.append(item['work_in'])
            row.append(item['work_out'])
            row.append(item['break_t'])
            row.append(item['value'])
            row.append(item['over_t'])
            row.append(item['absence'])
            row.append(item['late'])
            row.append(item['leave'])
            row.append(item['remarks'])
        data.append(row)
    table = Table(data, colWidths=colw, rowHeights=8.0*mm)
    table.setStyle([
        ('FONT',   ( 0, 0), (-1,-1), 'Gothic', 12),
        ('GRID',   ( 0, 0), (-1,-1), 0.5, colors.black),
        ('BOX',    ( 0, 0), (-1,-1), 1.8, colors.black),
        ('VALIGN', ( 0, 0), (-1,-1), 'MIDDLE'),
        ('ALIGN',  ( 0, 0), (-1,-1), 'CENTER'),
        ('ALIGN',  (10, 1), (10,-1), 'LEFT')
    ])
    table.wrapOn(p, xmargin, 16.0*mm)
    table.drawOn(p, xmargin, 16.0*mm)
    # Foot
    colw = (20.0*mm, 33.0*mm, 16.5*mm, 20.5*mm, 16.5*mm, 10.5*mm, 10.5*mm, 10.5*mm, 47.0*mm)
    data =[
        [
            '合計',
            '{}日'.format(foot['count']),
            foot['break_t'],
            foot['value'],
            foot['over_t'], 
            foot['absence'], 
            foot['late'], 
            foot['leave'],
            ''
        ]
    ]
    table = Table(data, colWidths=colw, rowHeights=8.0*mm)
    table.setStyle([
        ('FONT',   ( 0, 0), (-1,-1), 'Gothic', 12),
        ('GRID',   ( 0, 0), (-1,-1), 0.5, colors.black),
        ('BOX',    ( 0, 0), (-1,-1), 1.8, colors.black),
        ('VALIGN', ( 0, 0), (-1,-1), 'MIDDLE'),
        ('ALIGN',  ( 0, 0), (-1,-1), 'CENTER'),
    ])
    table.wrapOn(p, xmargin, 7.0*mm)
    table.drawOn(p, xmargin, 7.0*mm)
    # Print
    p.showPage()
    p.save()
    result = output.getvalue()
    output.close()
    return result
Example #45
0
def render_to_reportlab(context):
    """
        In context dictionary we could have a 'fattura'
        or a list of fatture in 'fatture'.

        Everything will be appended to a pdf returned as Django response.

        To reset page counter between different invoices, we'll use
        2 "Normale" templates, one for even and one for odds, so every times
        the template changes we'll reset the NumberedCanvas
    """
    if "fattura" in context and "fatture" in context:
        raise Exception(
            "Please create PDF choosing between a fattura or multiple fatture")
    if "fattura" in context:
        fatture = [context.get('fattura')]
    else:
        fatture = context.get('fatture')

    response = http.HttpResponse(content_type='application/pdf')
    NormalTemplates = ['Normale0', 'Normale1']

    fatture_rimanenti = len(fatture)
    story = []

    pageTemplates = [
        PageTemplate(id='Normale0', onPage=onPageNormal),
        PageTemplate(id='Normale1', onPage=onPageNormal),
        PageTemplate(id='ConducenteConsorzio',
                     onPage=onPageConducenteConsorzio),
        PageTemplate(id='ConsorzioConducente',
                     onPage=onPageConsorzioConducente),
    ]
    # scelgo il template della prima pagina come primo della lista
    if fatture[0].is_ricevuta_sdoppiata():
        lastTemplateID = 'ConducenteConsorzio'
        pageTemplates = pageTemplates[2:] + pageTemplates[:2]
    else:
        lastTemplateID = 'Normale0'

    width, height = portrait(A4)
    doc = BaseDocTemplate(
        response,
        pagesize=(width, height),
        leftMargin=1 * cm,
        rightMargin=1 * cm,
        bottomMargin=1.5 * cm,
        topMargin=1 * cm,
        showBoundary=test,
        pageTemplates=pageTemplates,
    )
    doc.fatture = fatture
    doc.lastTemplateID = lastTemplateID
    doc.fattura_corrente = 0

    for fattura in fatture:
        ricevutaMultipla = fattura.is_ricevuta_sdoppiata()
        story_fattura = []
        fatturazione = FATTURE_PER_TIPO[fattura.tipo]

        righeFattura = [
            ('Descrizione', 'Q.tà', 'Prezzo', 'IVA %', 'Importo'),
        ]

        righe = fattura.righe.all()

        raggruppa_barbatrucco = False
        if fatturazione.codice == "5":
            totale = sum([r.val_totale() for r in righe])
            conducente = righe[0].conducente if righe else None
            if "Imposta di bollo" not in [r.descrizione for r in righe]:
                if not (totale < settings.MIN_PRICE_FOR_TAXSTAMP and
                        (conducente is None or conducente.emette_ricevute)):
                    raggruppa_barbatrucco = True

        if raggruppa_barbatrucco:
            # print "5 esente iva con barbatrucco"

            netto = totale / Decimal(1.1)

            class RigaTotaleIvata(object
                                  ):  # una riga che fa corrispondere il totale
                descrizione = "Servizi per consorzio."
                note = None
                qta = 1
                prezzo = netto
                iva = 10

                def val_imponibile(self):
                    return self.prezzo

                def val_iva(self):
                    return totale - netto

                def val_totale(self):
                    return totale

            riga = RigaTotaleIvata()
            # la fattura ha totale pari al totale di tutte le righe
            # l'iva è fissa al 10% e il netto è calcolato di conseguenza
            imponibile = netto
            iva = totale - netto
            righe = [riga]

        else:
            imponibile = fattura.val_imponibile()
            iva = fattura.val_iva()

        for riga in righe:
            descrizione = riga.descrizione
            if riga.note: descrizione += " (%s)" % riga.note
            righeFattura.append(
                (Paragraph(descrizione,
                           normalStyle), Paragraph("%s" % riga.qta,
                                                   normalStyle),
                 moneyfmt(riga.prezzo), riga.iva, moneyfmt(riga.val_totale())))
        righeTotali = []
        righeTotali.append(('Imponibile', moneyfmt(imponibile)))
        righeTotali.append(('IVA', moneyfmt(iva)))
        righeTotali.append(('TOTALE', moneyfmt(fattura.val_totale())))
        righeStyle = TableStyle([
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ('ALIGN', (0, 0), (-1, -1),
             'RIGHT'),  # globalmente allineato a destra...
            ('ALIGN', (0, 0), (1, -1),
             'LEFT'),  # tranne la prima colonna (con la descrizione)
            ('GRID', (0, 1), (-1, -1), 0.1, colors.grey),
            ('FACE', (0, 0), (-1, -1), 'Helvetica'),
            ('FACE', (0, 0), (-1, 0), 'Helvetica-Bold'),  # header
            ('SIZE', (0, 0), (-1, -1), 8),

            # ('SPAN', (0, -1), (3, -1)),	# anziché mettere lo span qui aggiungo in coda una tabella diversa
        ])
        totaliStyle = TableStyle([
            ('ALIGN', (0, 0), (-1, -1), 'RIGHT'),
            ('GRID', (-1, 0), (-1, -1), 0.1, colors.grey),
            ('FACE', (0, 0), (-1, -1), 'Helvetica'),  # header
            ('FACE', (0, -1), (-1, -1), 'Helvetica-Bold'),  # Totale
            ('SIZE', (0, 0), (-1, -1), 8),
        ])

        colWidths = ((width - doc.leftMargin - doc.rightMargin) -
                     (1.6 * 4) * cm, ) + (1.6 * cm, ) * 4
        story_fattura = [
            Table(righeFattura,
                  style=righeStyle,
                  repeatRows=1,
                  colWidths=colWidths)
        ]
        story_fattura.append(
            KeepTogether(
                Table(righeTotali,
                      style=totaliStyle,
                      colWidths=(width - doc.leftMargin - doc.rightMargin -
                                 1.6 * cm, 1.6 * cm))))

        if ricevutaMultipla:  # le ricevute si raddoppiano con 2 template diversi
            # raddoppio lo story di questa fattura cambiando template
            story_fattura = story_fattura + [
                NextPageTemplate("ConsorzioConducente"),
                PageBreak()
            ] + story_fattura
        fatture_rimanenti -= 1
        if fatture_rimanenti:
            story_fattura += [
                NextPageTemplate(NormalTemplates[-1]),
                PageBreak()
            ]

        NormalTemplates.reverse()  # reverse current, next normal template

        story = story + story_fattura

    doc.build(story, canvasmaker=NumberedCanvas)
    return response
Example #46
0
def form_01(request_data):
    """
    Форма Лист на оплату по созданным направлениям на услуги
    """
    form_name = "Лист на оплату"

    ind_card = Card.objects.get(pk=request_data["card_pk"])
    ind = ind_card.individual
    ind_doc = Document.objects.filter(individual=ind, is_active=True)
    ind_dir = json.loads(request_data["dir"])

    # Получить данные с клиента физлицо-ФИО, пол, дата рождения
    individual_fio = ind.fio()
    individual_sex = ind.sex
    individual_date_born = ind.bd()

    # Получить все источники, у которых title-ПЛАТНО
    ist_f = []
    ist_f = list(
        IstochnikiFinansirovaniya.objects.values_list('id').filter(
            title__exact='Платно'))
    ist_f_list = []
    ist_f_list = ([int(x[0]) for x in ist_f])

    napr = Napravleniya.objects.filter(id__in=ind_dir)
    dir_temp = []

    #Проверить, что все направления принадлежат к одной карте и имеют ист. финансирования "Платно"
    for n in napr:
        if (n.istochnik_f_id in ist_f_list) and (n.client == ind_card):
            dir_temp.append(n.pk)

    # Получить объект прайс по источнику "платно" из всех видов источников имеющих title платно, берется первое значение
    price_modifier_obj = PriceName.get_price(ist_f_list[0])

    # получить УСЛУГИ по направлениям(отфильтрованы по "платно" и нет сохраненных исследований) в Issledovaniya
    research_direction = forms_func.get_research_by_dir(dir_temp)

    # получить по направлению-услугам цену из Issledovaniya
    # research_price = forms_func.get_coast(research_direction, price_modifier_obj)
    research_price = forms_func.get_coast_from_issledovanie(research_direction)

    result_data = forms_func.get_final_data(research_price)

    hospital_name = "ОГАУЗ \"Иркутская медикосанитарная часть № 2\""
    hospital_address = "г. Иркутс, ул. Байкальская 201"
    hospital_kod_ogrn = "1033801542576"
    hospital_okpo = "31348613"

    # Получить данные физлицо-документы: паспорт, полис, снилс
    document_passport = "Паспорт РФ"
    documents = forms_func.get_all_doc(ind_doc)
    document_passport_num = documents['passport']['num']
    document_passport_serial = documents['passport']['serial']
    document_passport_date_start = documents['passport']['date_start']
    document_passport_issued = documents['passport']['issued']
    document_polis = documents['polis']['num']
    document_snils = documents['snils']['num']

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

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

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

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

    objs = []

    date_now = datetime.strftime(datetime.now(), "%d.%m.%Y")
    objs = [
        Paragraph('{}'.format(hospital_name), styleCenter),
        Spacer(1, 1 * mm),
        Paragraph('({} тел. 28-61-00)'.format(hospital_address), styleCenter),
        Spacer(1, 3 * mm),
        Paragraph('{}'.format(form_name), styleCenterBold),
        Spacer(1, 4 * mm),
        Paragraph('<font size = 11> <u> {}</u> </font>'.format(date_now),
                  styleCenter),
        Paragraph('<font size = 8> дата оформления </font>', styleCenter),
    ]

    styleTCenter = deepcopy(styleCenter)
    styleTCenter.alignment = TA_CENTER
    styleTCenter.leading = 3.5 * mm

    styleTBold = deepcopy(styleCenterBold)
    styleTBold.fontSize = 14
    styleTBold.alignment = TA_LEFT

    num = ind_card.number
    num_type = ind_card.full_type_card()
    barcode128 = code128.Code128(num, barHeight=9 * mm, barWidth=1.25)
    date_now = datetime.strftime(datetime.now(), "%d.%m.%Y")

    opinion = [
        [
            Paragraph('№ карты:', style),
            Paragraph(num + "-" + "(" + num_type + ")", styleTBold), barcode128
        ],
    ]

    tbl = Table(opinion, colWidths=(23 * mm, 75 * mm, 100 * mm))

    tbl.setStyle(
        TableStyle([
            ('GRID', (0, 0), (-1, -1), 1.0, colors.white),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 1.0 * mm),
            ('BOTTOMPADDING', (1, 0), (1, 0), 1.0 * mm),
            ('ALIGN', (-1, 0), (-1, -1), 'RIGHT'),
        ]))

    objs.append(Spacer(1, 4.5 * mm))
    objs.append(tbl)

    opinion = [
        [
            Paragraph('', style),
            Paragraph('', style),
        ],
        [
            Paragraph('Пациент:', style),
            Paragraph(individual_fio, style),
        ],
        [
            Paragraph('Паспорт:', style),
            Paragraph(
                'серия: {} &nbsp;&nbsp;&nbsp;&nbsp; номер: {} &nbsp;&nbsp;&nbsp;&nbsp; дата выдачи: {}'
                .format(document_passport_serial, document_passport_num,
                        document_passport_issued), style),
        ],
        [
            Paragraph('Д/р:', style),
            Paragraph(individual_date_born, style),
        ],
    ]

    tbl = Table(opinion, colWidths=(23 * mm, 175 * mm))

    tbl.setStyle(
        TableStyle([
            ('GRID', (0, 0), (-1, -1), 1.0, colors.white),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 1.1 * mm),
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ]))

    objs.append(Spacer(1, 2 * mm))
    objs.append(tbl)

    objs.append(Spacer(1, 2 * mm))
    objs.append(
        Paragraph('<font size=13><b>На водительскую справку</b></font>',
                  style))

    styleTB = deepcopy(style)
    styleTB.fontSize = 11.5
    styleTB.alignment = TA_CENTER
    styleTB.fontName = "PTAstraSerifBold"

    styleTC = deepcopy(style)
    styleTC.fontSize = 10.5
    styleTC.alignment = TA_LEFT

    styleTCright = deepcopy(styleTC)
    styleTCright.alignment = TA_RIGHT

    styleTCcenter = deepcopy(styleTC)
    styleTCcenter.alignment = TA_CENTER

    if result_data[2] == 'no_discount':
        opinion = [
            [
                Paragraph('Код услуги', styleTB),
                Paragraph('Направление', styleTB),
                Paragraph('Услуга', styleTB),
                Paragraph('Цена,<br/>руб.', styleTB),
                Paragraph('Кол-во, усл.', styleTB),
                Paragraph('Сумма, руб.', styleTB),
            ],
        ]
    else:
        opinion = [
            [
                Paragraph('Код услуги', styleTB),
                Paragraph('Направление', styleTB),
                Paragraph('Услуга', styleTB),
                Paragraph('Цена,<br/>руб.', styleTB),
                Paragraph('Скидка<br/>Наценка<br/>%', styleTB),
                Paragraph('Цена со<br/> скидкой,<br/>руб.', styleTB),
                Paragraph('Кол-во, усл.', styleTB),
                Paragraph('Сумма, руб.', styleTB),
            ],
        ]

    # example_template = [
    #     ['1.2.3','4856397','Полный гематологический анализ','1000.00','0','1000.00','1','1000.00'],
    #     ['1.2.3','','РМП','2500.45','0','2500.45','1','2500.45'],
    #     ['1.2.3', '4856398', 'УЗИ брюшной полости', '3500.49', '0', '3500.49', '1', '3500.49'],
    #     ['1.2.3','4856398','Эзофагогастродуоденоскопия','5700.99','0','5700.99','1','5700.99']
    # ]
    # #

    example_template = result_data[0]

    list_g = []
    #используется range(len()) - к определенной колонке (по номеру) применяется свое свойство
    for i in range(len(example_template)):
        list_t = []
        for j in range(len(example_template[i])):
            if j in (3, 5, 7):
                s = styleTCright
            elif j in (4, 6):
                s = styleTCcenter
            else:
                s = styleTC
            list_t.append(Paragraph(example_template[i][j], s))
        list_g.append(list_t)

    sum_research = result_data[1]

    opinion.extend(list_g)

    if result_data[2] == 'is_discount':
        tbl = Table(opinion,
                    colWidths=(18 * mm, 19 * mm, 52 * mm, 22 * mm, 21 * mm,
                               22 * mm, 13 * mm, 25 * mm))
    else:
        tbl = Table(opinion,
                    colWidths=(23 * mm, 34 * mm, 62 * mm, 22 * mm, 23 * mm,
                               25 * mm))

    tbl.setStyle(
        TableStyle([
            ('GRID', (0, 0), (-1, -1), 1.0, colors.black),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 1.5 * mm),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))

    objs.append(Spacer(1, 2 * mm))
    objs.append(tbl)
    objs.append(Spacer(1, 2 * mm))
    objs.append(Spacer(1, 2 * mm))
    objs.append(
        Paragraph('<font size=16> Итого: {}</font>'.format(sum_research),
                  styleTCright))

    objs.append(Spacer(1, 2 * mm))
    # start_day = datetime.today()
    end_date = (date.today() + relativedelta(days=+10))
    end_date1 = datetime.strftime(end_date, "%d.%m.%Y")

    objs.append(Spacer(1, 7 * mm))
    objs.append(Paragraph('<font size=16> Внимание:</font>', styleTBold))
    objs.append(Spacer(1, 1 * mm))
    objs.append(
        Paragraph(
            '<font size=16> 1) Лист на оплату действителен в течение 10 (десяти) дней – до {}.'
            '</font>'.format(end_date1), style))
    objs.append(Spacer(1, 2 * mm))
    objs.append(
        Paragraph('<font size=16> 2) Проверяйте услуги с направлениями</font>',
                  style))

    doc.build(objs)
    pdf = buffer.getvalue()
    buffer.close()
    return pdf
Example #47
0
def render_keyterm():
    """
    Renders the keyterm image, with text, etc
    """
    from reportlab.pdfgen import canvas
    from reportlab.lib.pagesizes import A4, portrait
    from reportlab.lib.units import cm
    from reportlab.platypus import Paragraph

    image = KeyTerm_Definition.objects.all()[0]

    imagefile = image.image_raw.file.name

    # Thumbnail
    from PIL import Image, ImageDraw
    size = (256, 256)
    imagefile = '/Users/kevindunn/Desktop/Screen Shot 2017-07-16 at 10.31.37.png'
    im = Image.open(imagefile)
    im.thumbnail(size)
    im.save(imagefile + ".jpg", "JPEG")

    # Puts an X over the image
    imagefile = '/var/www/yint.org/static/flipped-mooc/LTS-talk/assets/AE3B29B8-5801-483E-A563-AB8193484613/assets/12303DA0D10FEF5E36D814059432DFAB.png.jpg'
    from PIL import Image, ImageDraw
    im = Image.open(imagefile)
    draw = ImageDraw.Draw(im)
    draw.line((0, 0) + im.size, fill=128)
    draw.line((0, im.size[1], im.size[0], 0), fill=128)
    del draw

    # write to stdout
    im.save(imagefile, "JPEG")

    # Create PNG and add text to it
    from PIL import Image, ImageDraw, ImageFont
    # get a font
    fnt = ImageFont.truetype('Verdana.ttf', 40)
    imagefile = '/var/www/yint.org/static/flipped-mooc/LTS-talk/assets/AE3B29B8-5801-483E-A563-AB8193484613/assets/12303DA0D10FEF5E36D814059432DFAB.png'
    base = Image.open(imagefile).convert('RGBA')

    # make a blank image for the text, initialized to transparent text color
    txt = Image.new('RGBA', base.size, (255, 255, 255, 0))

    # get a drawing context
    d = ImageDraw.Draw(txt)

    # draw text, half opacity
    d.text((10, 10), "Hello", font=fnt, fill=(255, 255, 255, 128))
    # draw text, full opacity
    d.text((10, 60), "World", font=fnt, fill=(255, 255, 255, 255))

    out = Image.alpha_composite(base, txt)

    out.save(imagefile + 'new.png', "PNG")

    full_path = '/Users/kevindunn/Voorwaarden-2016-Basis-Budget-Zeker-Exclusief-90482-1601.pdf'
    extension = 'pdf'
    try:
        c = canvas.Canvas(
            full_path,
            pagesize=A4,
        )
        c.setPageSize(portrait(A4))

        c.setFont("Helvetica", 36)

        p = Paragraph(ptext, self.styles["Normal"])
        p.wrapOn(self.c, self.width - 70, self.height)
        p.drawOn(self.c, *self.coord(20, voffset + 48, mm))

        styles = getSampleStyleSheet()
        doc = FourBySixNotecard("phello2.pdf", "Test Title", "Andrew Frink")
        Story = []
        p = Paragraph("Title", styles["title"])

        drawString(1 * cm, (29.7 - 2) * cm, 'Third Culture Kids')
        c.drawImage(imagefile,
                    x=cm * 0,
                    y=10 * cm,
                    width=cm * (21.0 - 2),
                    height=cm * (29.7 - 2 - 17.0),
                    mask=None,
                    preserveAspectRatio=True,
                    anchor='c')
        c.showPage()
        c.save()
    except IOError as exp:
        logger.error('Exception: ' + str(exp))
        # TODO: raise error message

    from wand.image import Image
    imageFromPdf = Image(filename=full_path)
    image = Image(width=imageFromPdf.width, height=imageFromPdf.height)
    image.composite(imageFromPdf.sequence[0], top=0, left=0)
    image.format = "png"
    thumbnail_full_name = full_path.replace('.' + extension, '.png')
    image.save(filename=thumbnail_full_name)

    return 'Success'
Example #48
0
    def convert_context_to_pdf(self, context):
        account_list = context['account_list']

        today = datetime.date.today()

        def myFirstPage(canvas, doc):
            # Header
            canvas.saveState()
            canvas.setFont("Helvetica", 8)
            canvas.drawCentredString(PAGE_WIDTH / 2, 30, "VPAC")
            canvas.drawString(540, 30, "Page %d" % doc.page)
            canvas.drawString(50, 30, defaultfilters.date(today, "j, F Y"))
            canvas.restoreState()

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

            # Footer
            canvas.setFont('Times-Roman', 8)
            canvas.drawCentredString(PAGE_WIDTH / 2, 30, "VPAC")
            canvas.drawString(540, 30, "Page %d" % doc.page)
            canvas.drawString(50, 30, defaultfilters.date(today, "j, F Y"))
            canvas.restoreState()

        data_dic = [[
            str(x.cn),
            str(getattr(x, 'telephoneNumber', '')),
            str(getattr(x, 'mobile', '')),
            str(getattr(x, 'mail', '')),
            str(getattr(x, 'l', ''))
        ] for x in account_list]

        data_list = list(data_dic)

        buffer = StringIO()
        doc = SimpleDocTemplate(buffer)
        doc.pagesize = portrait(A4)
        doc.topMargin = 40
        story = []

        table_style = TableStyle([
            ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('LINEABOVE', (0, 0), (-1, 0), 1, colors.black),
            ('LINEBELOW', (0, 0), (-1, 0), 1, colors.black),
            ('LINEBELOW', (0, -1), (-1, -1), 1, colors.black),
            ('LINEBEFORE', (0, 0), (0, -1), 1, colors.black),
            ('LINEAFTER', (-1, 0), (-1, -1), 1, colors.black),
        ])

        # build the tables per unit
        # table
        item_list = [['Name', 'Telephone', 'Mobile', 'Email', 'Location']]
        item_list.extend(data_list)
        t = Table(item_list)
        t.hAlign = 'LEFT'
        t.setStyle(table_style)
        story.append(t)
        doc.build(story, onFirstPage=myFirstPage, onLaterPages=myLaterPages)

        # Close the PDF object cleanly.
        pdf = buffer.getvalue()
        buffer.close()
        # Get the value of the StringIO buffer and write it to the response.
        return pdf
Example #49
0
File: util.py Project: tpetr/schedr
def generate_course_pdf(term, title, sections, footer=''):
    buffer = StringIO()

    size = pagesizes.portrait(pagesizes.letter)
    p = canvas.Canvas(buffer, size)
    p.setFont("Helvetica", 12)

    p.setTitle("%s" % term)

    width, height = size
    xmargin = width / 50
    ymargin = height / 50

    # Draw term (Spring 2009) on the top left
    p.setFontSize(20)
    p.drawString(xmargin, height - ymargin - 15, "%s" % term)

    # Draw title on top right
    p.setFontSize(16)
    p.drawRightString(width - xmargin, height - ymargin - 15, title)

    p.setFontSize(12)

    # Compute the minimum and maximum hours
    min_hour, max_hour = 11, 15
    courses = set()
    for section in sections:
        courses.add(section.course)
        for day, start, end in section.day_times():
            if start.hour < min_hour:
                min_hour = start.hour

            if end.minute == 0 and end.hour > max_hour:
                max_hour = end.hour
            elif end.minute > 0 and end.hour >= max_hour:
                max_hour = end.hour + 1

    # Compute colors for courses
    if len(courses) > 0:
        h_inc = 1.0 / float(len(courses))
        color_map = {}
        i = 0
        for course in courses:
            color_map[course] = colorsys.hsv_to_rgb(h_inc * i, 0.25, 1)
            i = i + 1

    cal_rect = Rect(xmargin, height - ymargin - 35, width - xmargin,
                    ymargin + 15)
    cal_rect2 = Rect(xmargin, height - ymargin - 35, width - xmargin - 35,
                     ymargin + 15)

    # Draw weekdays
    for offset, day in ((0, 'Mon'), (1, 'Tue'), (2, 'Wed'), (3, 'Thu'),
                        (4, 'Fri')):
        p.drawCentredString(
            cal_rect2.left + (cal_rect2.width / 10) +
            ((cal_rect2.width / 5) * offset), height - ymargin - 33, day)

    # Compute height of one hour on the pdf
    hour_height = cal_rect.height / (max_hour - min_hour)

    # Draw the hour markers
    for hour in xrange(max_hour - min_hour):
        p.line(cal_rect.left, cal_rect.top - (hour * hour_height),
               cal_rect.right, cal_rect.top - (hour * hour_height))
        p.setFontSize(18)
        h = hour + min_hour
        if h > 12:
            h = h - 12
        p.drawRightString(cal_rect.right - 15,
                          cal_rect.top - 15 - (hour * hour_height), "%i" % h)
        p.setFontSize(10)
        p.drawRightString(cal_rect.right,
                          cal_rect.top - 15 - (hour * hour_height), "AM" if
                          (hour + min_hour) < 12 else "PM")
    p.line(cal_rect.left, cal_rect.bottom, cal_rect.right, cal_rect.bottom)
    p.setFontSize(12)

    # Draw the sections
    for section in sections:
        index = 0
        for index, start, end, loc, room in section.day_times_with_locs():
            mstart = ((start.hour - min_hour) * 60) + start.minute
            mend = ((end.hour - min_hour) * 60) + end.minute
            xstart = mstart * hour_height / 60
            xend = mend * hour_height / 60
            p.setFillColorRGB(*color_map[section.course])
            p.roundRect(cal_rect2.left + (index * (cal_rect2.width / 5)) + 1,
                        cal_rect2.top - xend, (cal_rect2.width / 5) - 2,
                        xend - xstart,
                        10,
                        fill=1)
            p.setFillColorRGB(0, 0, 0)
            h = (xend - xstart - 12) / 4
            p.setFontSize(10)
            p.drawCentredString(
                cal_rect2.left + (cal_rect2.width / 10) +
                (index * (cal_rect2.width / 5)), cal_rect2.top - xstart - 10,
                start.strftime("%I:%M %p"))
            p.setFont(
                "Helvetica-Bold",
                calc_font_size(p, "%s" % section.course,
                               (cal_rect2.width / 5) - 2, 'Helvetica-Bold'))
            p.drawCentredString(
                cal_rect2.left + (cal_rect2.width / 10) +
                (index * (cal_rect2.width / 5)),
                cal_rect2.top - xstart - 10 - h, "%s" % section.course)
            p.setFont(
                "Helvetica-Bold",
                calc_font_size(p, section.get_type_long(),
                               (cal_rect2.width / 5) - 2, 'Helvetica-Bold'))
            p.drawCentredString(
                cal_rect2.left + (cal_rect2.width / 10) +
                (index * (cal_rect2.width / 5)),
                cal_rect2.top - xstart - 10 - (h * 2), section.get_type_long())
            if loc is None:
                loc_str = 'TBA'
            else:
                loc_str = "%s %s" % (loc.name, room)
            p.setFont(
                "Helvetica",
                calc_font_size(p, loc_str, (cal_rect2.width / 5) - 2,
                               'Helvetica'))
            p.drawCentredString(
                cal_rect2.left + (cal_rect2.width / 10) +
                (index * (cal_rect2.width / 5)),
                cal_rect2.top - xstart - 10 - (h * 3), loc_str)
            p.setFontSize(10)
            p.drawCentredString(
                cal_rect2.left + (cal_rect2.width / 10) +
                (index * (cal_rect2.width / 5)),
                cal_rect2.top - xstart - 10 - (h * 4),
                end.strftime("%I:%M %p"))
            p.setFontSize(12)

    if footer != '':
        p.drawCentredString(width / 2, ymargin, footer)

    p.showPage()
    p.save()
    return buffer
Example #50
0
def convertImageToPDF(_fileName, _swfslides, isDocin):
    print "convecting files to pdf..."
    pdfCanvas = canvas.Canvas('%s.pdf' % _fileName, pagesize=portrait(A4))
    pdfCanvas.drawString(150, 700, "Welcome to flash slides downloader")
    pdfCanvas.drawString(180, 680, "contact: [email protected]")
    pdfCanvas.showPage()
    numberOfSlides = 1
    for iswf in _swfslides:
        doc = gfx.open("swf", iswf)
        print iswf
        if doc:
            if isDocin == False:
                for pagenr in range(1, doc.pages + 1):
                    page1 = doc.getPage(pagenr)
                    print "Page", pagenr, "has dimensions", page1.width, "x", page1.height
                    pdfCanvas.setPageSize((page1.width * 2, page1.height * 2))
                    imageName = 'image-%s-%s.png' % (numberOfSlides, pagenr)
                    imgRGBBuf = page1.asImage(page1.width * 2,
                                              page1.height * 2)
                    im = Image.fromstring("RGB",
                                          (page1.width * 2, page1.height * 2),
                                          imgRGBBuf)  # convert to PIL Object
                    # img = gfx.ImageList()
                    # 				img.setparameter("antialise", "4") # turn on antialisin
                    # img.setparameter("zoom", "100")
                    # img.startpage(page1.width,page1.height)
                    # 				page1.render(img)
                    # 				img.endpage()
                    # pageNumOfThisSwf+=1"thumbnail%s.png" % pagenr
                    # img.save(imageName)
                    # pdfCanvas.drawImage(imageName,0,0,width= page1.width,height= page1.height,mask='auto')
                    pdfCanvas.drawImage(ImageReader(im),
                                        0,
                                        0,
                                        width=page1.width * 2,
                                        height=page1.height * 2,
                                        mask='auto')
                    pdfCanvas.showPage()
                    # os.remove(imageName) # delete temp image
            else:
                # damn docins bad header.
                page1 = doc.getPage(1)
                print "Page %d" % numberOfSlides, "has dimensions", page1.width, "x", page1.height
                pdfCanvas.setPageSize((page1.width * 2, page1.height * 2))
                imageName = 'image-%s-%s.png' % (numberOfSlides, 1)
                imgRGBBuf = page1.asImage(page1.width * 2, page1.height * 2)
                im = Image.fromstring("RGB",
                                      (page1.width * 2, page1.height * 2),
                                      imgRGBBuf)  # convert to PIL Object
                # img = gfx.ImageList()
                # img.setparameter("antialise", "4") # turn on antialisin
                # img.setparameter("zoom", "100")
                # img.startpage(page1.width,page1.height)
                # page1.render(img)
                # img.endpage()
                # pageNumOfThisSwf+=1"thumbnail%s.png" % pagenr
                # img.save(imageName)
                # pdfCanvas.drawImage(imageName,0,0,width= page1.width,height= page1.height,mask='auto')
                pdfCanvas.drawImage(ImageReader(im),
                                    0,
                                    0,
                                    width=page1.width * 2,
                                    height=page1.height * 2,
                                    mask='auto')
                pdfCanvas.showPage()
                # os.remove(imageName) # delete temp image
        numberOfSlides += 1
        os.remove(iswf)  # delete temp swf
    pdfCanvas.save()
styleH = styles['Heading1']
styleH.alignment = TA_CENTER
styleF = styles['Heading2']
styleF.alignment = TA_RIGHT
styleU = styles['Heading3']
styleU.alignment = TA_RIGHT

doc = SimpleDocTemplate("cpp.pdf",
                        pagesize=A4,
                        rightMargin=20,
                        leftMargin=20,
                        topMargin=20,
                        bottomMargin=8)

# doc.pagesize = landscape(A4)
doc.pagesize = portrait(A4)

elements = []
logo = "sadc_title.gif"
im = Image(logo, 0 * inch, 0 * inch)
elements.append(im)
elements.append(Paragraph("Certification Report", styleH))
elements.append(Paragraph("Meeting Date: January 28, 2016", styleH))
elements.append(Paragraph("County PIG Program", styleH))
elements.append(Spacer(1, 0.4 * inch))

# ..................................................................................................
style_l = ParagraphStyle(
    name='Normal',
    fontName='Helvetica-Bold',
    fontSize=12,
Example #52
0
def form_01(request_data):
    """
    Договор, включающий услуги на оплату и необходимые реквизиты
    """
    form_name = "Договор"

    ind_card = Card.objects.get(pk=request_data["card_pk"])
    ind = ind_card.individual
    ind_doc = Document.objects.filter(individual=ind, is_active=True)
    ind_dir = json.loads(request_data["dir"])
    #exec_person = print(request_data.user.doctorprofile.fio)
    exec_person = 'Иванов Иван Иванович'

    # Получить данные с клиента физлицо-ФИО, пол, дата рождения
    individual_fio = ind.fio()
    individual_date_born = ind.bd()

    # Получить все источники, у которых title-ПЛАТНО
    ist_f = []
    ist_f = list(
        IstochnikiFinansirovaniya.objects.values_list('id').filter(
            title__exact='Платно'))
    ist_f_list = []
    ist_f_list = ([int(x[0]) for x in ist_f])

    napr = Napravleniya.objects.filter(id__in=ind_dir)
    dir_temp = []

    #Проверить, что все направления принадлежат к одной карте и имеют ист. финансирования "Платно"
    num_contract_set = set()
    for n in napr:
        if (n.istochnik_f_id in ist_f_list) and (n.client == ind_card):
            num_contract_set.add(n.num_contract)
            dir_temp.append(n.pk)

    # получить УСЛУГИ по направлениям(отфильтрованы по "платно" и нет сохраненных исследований) в Issledovaniya
    research_direction = forms_func.get_research_by_dir(dir_temp)

    # получить по направлению-услугам цену из Issledovaniya
    research_price = forms_func.get_coast_from_issledovanie(research_direction)

    #Получить Итоговую стр-ру данных
    result_data = forms_func.get_final_data(research_price)

    today = datetime.datetime.now()
    date_now1 = datetime.datetime.strftime(today, "%y%m%d%H%M%S%f")[:-3]
    date_now_str = str(ind_card.pk) + str(date_now1)

    # Проверить записан ли номер контракта в направлениях
    # ПереЗаписать номер контракта Если в наборе направлений значение None
    num_contract_set = set()
    napr_end = []
    napr_end = Napravleniya.objects.filter(id__in=result_data[3])
    for n in napr_end:
        num_contract_set.add(n.num_contract)

    if (len(num_contract_set) == 1) and (None in num_contract_set):
        print('Перезаписано т.к. было NONE')
        Napravleniya.objects.filter(id__in=result_data[3]).update(
            num_contract=date_now_str)
    # ПереЗаписать номер контракта Если в наборе направлении значение разные значения
    if len(num_contract_set) > 1:
        print('Перезаписано т.к. были разные контракты в направлениях')
        Napravleniya.objects.filter(id__in=result_data[3]).update(
            num_contract=date_now_str)

    if (len(num_contract_set) == 1) and (not None in num_contract_set):
        print('No-No-No-No не надо создавать номер контракта он есть')
        print()
        date_now_str = num_contract_set.pop()

# Получить данные физлицо-документы: паспорт, полис, снилс
    document_passport = "Паспорт РФ"
    documents = forms_func.get_all_doc(ind_doc)
    document_passport_num = documents['passport']['num']
    document_passport_serial = documents['passport']['serial']
    document_passport_date_start = documents['passport']['date_start']
    document_passport_issued = documents['passport']['issued']

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

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

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

    objs = []
    barcode128 = code128.Code128(date_now_str, barHeight=6 * mm, barWidth=1.25)

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

    # head = [
    #     Paragraph('ДОГОВОР &nbsp;&nbsp; № <u>{}</u>'.format(date_now_str),styleCenter),
    #     Spacer(1, 1 * mm),
    #     Paragraph('НА ОКАЗАНИЕ ПЛАТНЫХ МЕДИЦИНСКИХ УСЛУГ НАСЕЛЕНИЮ', styleCenter),
    #     ]
    objs.append(
        Paragraph('ДОГОВОР &nbsp;&nbsp; № <u>{}</u>'.format(date_now_str),
                  styleCenter))
    objs.append(Spacer(1, 1 * mm))
    objs.append(
        Paragraph('НА ОКАЗАНИЕ ПЛАТНЫХ МЕДИЦИНСКИХ УСЛУГ НАСЕЛЕНИЮ',
                  styleCenter))
    styleTCenter = deepcopy(styleCenter)
    styleTCenter.alignment = TA_CENTER
    styleTCenter.leading = 3.5 * mm

    styleTBold = deepcopy(styleCenterBold)
    styleTBold.fontSize = 10
    styleTBold.alignment = TA_LEFT

    # barcode128 = code128.Code128(date_now_str,barHeight= 4 * mm, barWidth = 1.25)

    date_now = pytils.dt.ru_strftime(u"%d %B %Y",
                                     inflected=True,
                                     date=datetime.datetime.now())

    styleTR = deepcopy(style)
    styleTR.alignment = TA_RIGHT

    opinion = [
        [
            Paragraph('г. Иркутск', style),
            Paragraph('{} года'.format(date_now), styleTR)
        ],
    ]

    tbl = Table(opinion, colWidths=(95 * mm, 95 * mm))

    tbl.setStyle(
        TableStyle([
            ('GRID', (0, 0), (-1, -1), 1.0, colors.white),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 1.5 * mm),
        ]))

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

    objs.append(Spacer(1, 4.5 * mm))
    hospital_name = SettingManager.get("rmis_orgname")
    hospital_short_name = SettingManager.get("org_title")
    hospital_address = SettingManager.get("org_address")

    post_contract = SettingManager.get("post_contract")
    document_base = SettingManager.get("document_base")

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

    if ind_card.main_address:
        main_address = ind_card.main_address
    else:
        main_address = "______________________________________________________________________"

    if ind_card.fact_address:
        fact_address = ind_card.fact_address
    elif main_address:
        fact_address = main_address
    else:
        fact_address = "______________________________________________________________________"

    objs.append(
        Paragraph(
            '{}, именуемая в дальнейшем "Исполнитель", в лице {} {}, действующего(ей) на основании {} с '
            'одной стороны, и <u>{}</u>, именуемый(ая) в дальнейшем "Пациент", дата рождения {} г., '
            'паспорт: {}-{} '
            'выдан {} г. '
            'кем: {} '
            'зарегистрирован по адресу: {}, '
            'адрес проживания: {} '
            'с другой стороны, вместе также именуемые "Стороны", заключили настоящий договор (далее - "Договор") о нижеследующем:'
            .format(hospital_name, post_contract, exec_person, document_base,
                    individual_fio, individual_date_born,
                    document_passport_serial, document_passport_num,
                    document_passport_date_start, passport_who_give,
                    main_address, fact_address), style))

    objs.append(Spacer(1, 2 * mm))
    objs.append(Paragraph('1. ПРЕДМЕТ ДОГОВОРА', styleCenter))
    objs.append(
        Paragraph(
            '1.1. Исполнитель на основании обращения Пациента обязуется оказать ему медицинские услуги в соответствие с лицензией:',
            style))

    #Касьяненко начало шаблон услуг только для водителей, на работу
    template_research = "Перечень услуг"
    # Касьяненко конец

    tr = ""
    if template_research:
        tr = template_research
    objs.append(Spacer(1, 2 * mm))
    objs.append(Paragraph('{}'.format(tr), style))

    styleTB = deepcopy(style)
    styleTB.firstLineIndent = 0
    styleTB.fontSize = 8.5
    styleTB.alignment = TA_CENTER
    styleTB.fontName = "PTAstraSerifBold"

    styleTC = deepcopy(style)
    styleTC.firstLineIndent = 0
    styleTC.fontSize = 8.5
    styleTC.alignment = TA_LEFT

    styleTCright = deepcopy(styleTC)
    styleTCright.alignment = TA_RIGHT

    styleTCcenter = deepcopy(styleTC)
    styleTCcenter.alignment = TA_CENTER

    opinion = []
    if result_data[2] == 'no_discount':
        opinion = [
            [
                Paragraph('Код услуги', styleTB),
                Paragraph('Направление', styleTB),
                Paragraph('Услуга', styleTB),
                Paragraph('Цена,<br/>руб.', styleTB),
                Paragraph('Кол-во, усл.', styleTB),
                Paragraph('Сумма, руб.', styleTB),
            ],
        ]
    else:
        opinion = [
            [
                Paragraph('Код услуги', styleTB),
                Paragraph('Направление', styleTB),
                Paragraph('Услуга', styleTB),
                Paragraph('Цена,<br/>руб.', styleTB),
                Paragraph('Скидка<br/>Наценка<br/>%', styleTB),
                Paragraph('Цена со<br/> скидкой,<br/>руб.', styleTB),
                Paragraph('Кол-во, усл.', styleTB),
                Paragraph('Сумма, руб.', styleTB),
            ],
        ]

    # example_template = [
    #     ['1.2.3','4856397','Полный гематологический анализ','1000.00','0','1000.00','1','1000.00'],
    #     ['1.2.3','','РМП','2500.45','0','2500.45','1','2500.45'],
    #     ['1.2.3', '4856398', 'УЗИ брюшной полости', '3500.49', '0', '3500.49', '1', '3500.49'],
    #     ['1.2.3','4856398','Эзофагогастродуоденоскопия','5700.99','0','5700.99','1','5700.99']
    # ]
    # #

    example_template = result_data[0]

    list_g = []

    #используется range(len()) - к определенной колонке (по номеру) применяется свое свойство
    for i in range(len(example_template)):
        list_t = []
        for j in range(len(example_template[i])):
            if j in (3, 5, 7):
                s = styleTCright
            elif j in (4, 6):
                s = styleTCcenter
            else:
                s = styleTC
            list_t.append(Paragraph(example_template[i][j], s))
        list_g.append(list_t)

    sum_research = result_data[1]

    sum_research_decimal = sum_research.replace(' ', '')

    opinion.extend(list_g)

    if result_data[2] == 'is_discount':
        tbl = Table(opinion,
                    colWidths=(18 * mm, 19 * mm, 52 * mm, 22 * mm, 21 * mm,
                               22 * mm, 13 * mm, 25 * mm))
    else:
        tbl = Table(opinion,
                    colWidths=(23 * mm, 34 * mm, 62 * mm, 22 * mm, 23 * mm,
                               25 * mm))

    tbl.setStyle(
        TableStyle([
            ('GRID', (0, 0), (-1, -1), 1.0, colors.black),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 1.5 * mm),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
        ]))

    objs.append(tbl)
    objs.append(Spacer(1, 1 * mm))
    objs.append(
        Paragraph('<font size=12> Итого: {}</font>'.format(sum_research),
                  styleTCright))
    objs.append(Spacer(1, 2 * mm))

    objs.append(Spacer(1, 3 * mm))
    objs.append(
        Paragraph(
            '(далее - "медицинские услуги"), а Пациент уплачивает Исполнителю вознаграждение в размере, '
            'порядке и сроки, которые установлены настоящим Договором.',
            style))
    objs.append(
        Paragraph(
            '1.2.	Исполнитель оказывает услуги по месту своего нахождения по адресу: '
            'г. Иркутск, Байкальская, 201, в соответствии с установленными Правилами предоставления платных медицинских услуг.',
            style))
    objs.append(Spacer(1, 2 * mm))
    objs.append(Paragraph('2. ПРАВА И ОБЯЗАННОСТИ СТОРОН', styleCenter))
    objs.append(Paragraph('<u>2.1. Исполнитель обязуется:</u>', style))
    objs.append(
        Paragraph(
            '2.1.1. Обеспечить Пациента бесплатной, доступной и достоверной информацией о платных медицинских услугах, '
            'содержащей следующие сведения о:', style))
    objs.append(
        Paragraph(
            'а) порядках оказания медицинской помощи и стандартах медицинской помощи, применяемых при предоставлении платных медицинских услуг;',
            style))
    objs.append(
        Paragraph(
            'б) данных о конкретном медицинском работнике, предоставляющем соответствующую платную медицинскую услугу (его профессиональном образовании и квалификации);',
            style))
    objs.append(
        Paragraph(
            'в) данных о методах оказания медицинской помощи, связанных с ними рисках, возможных видах медицинского вмешательства, их последствиях и ожидаемых результатах оказания медицинской помощи;',
            style))
    objs.append(
        Paragraph(
            'г) других сведениях, относящихся к предмету настоящего Договора.',
            style))
    objs.append(
        Paragraph(
            '2.1.2.Оказывать Пациенту услуги, предусмотренные п. 1.1 настоящего Договора, а при необходимости и дополнительные услуги.',
            style))
    objs.append(
        Paragraph(
            '2.1.3.Давать при необходимости по просьбе Пациента разъяснения о ходе оказания услуг ему и '
            'предоставлять по требованию Пациента необходимую медицинскую документацию.',
            style))
    objs.append(
        Paragraph(
            '2.1.4.Предоставить в доступной форме информацию о возможности получения соответствующих видов '
            'и объемов медицинской помощи без взимания платы в рамках Программы государственных гарантий '
            'бесплатного оказания гражданам медицинской помощи и территориальной программы государственных гарантий '
            'бесплатного оказания гражданам медицинской помощи.', style))
    objs.append(
        Paragraph(
            '2.15. Соблюдать порядки оказания медицинской помощи, утвержденные Министерством здравоохранения '
            'Российской Федерации.', style))
    objs.append(Paragraph('<u>2.2. Пациент обязуется:</u>', style))
    objs.append(
        Paragraph('2.2.1. Соблюдать назначение и рекомендации лечащих врачей.',
                  style))
    objs.append(
        Paragraph(
            '2.2.3. Оплачивать услуги Исполнителя в порядке, сроки и на условиях, которые установлены настоящим Договором.',
            style))
    objs.append(
        Paragraph(
            '2.2.4. Подписывать своевременно акты об оказании услуг Исполнителем.',
            style))
    objs.append(Paragraph('2.2.5. Кроме того Пациент обязан:', style))
    objs.append(
        Paragraph(
            '- информировать врача о перенесенных заболеваниях, известных ему аллергических реакциях, противопоказаниях;',
            style))
    objs.append(
        Paragraph(
            '- соблюдать правила поведения пациентов в медицинском учреждении, режим работы медицинского учреждения;',
            style))
    objs.append(
        Paragraph(
            '- выполнять все рекомендации медицинского персонала и третьих лиц, оказывающих ему по настоящему Договору'
            'медицинские услуги, по лечению, в том числе соблюдать указания медицинского учреждения, предписанные на период после оказания услуг.',
            style))
    objs.append(
        Paragraph(
            '2.3.	Предоставление Исполнителем дополнительных услуг оформляется дополнительным соглашением Сторон и оплачивается дополнительно.',
            style))
    objs.append(
        Paragraph(
            '2.4.	Стороны обязуются хранить в тайне лечебную, финансовую и иную конфиденциальную информацию, '
            'полученную от другой Стороны при исполнении настоящего Договора.',
            style))
    objs.append(Paragraph('3. ПОРЯДОК ИСПОЛНЕНИЯ ДОГОВОРА', styleCenter))
    objs.append(
        Paragraph(
            '3.1.	Условия получения Пациентом медицинских услуг: (вне медицинской организации; амбулаторно; '
            'в дневном стационаре; стационарно; указать,организационные моменты, связанные с оказанием медицинских услуг)',
            style))
    objs.append(
        Paragraph(
            '3.2.	В случае если при предоставлении платных медицинских услуг требуется предоставление '
            'на возмездной основе дополнительных медицинских услуг, не предусмотренных настоящим Договором, '
            'Исполнитель обязан предупредить об этом Пациента.', style))
    objs.append(
        Paragraph(
            'Без согласия Пациента Исполнитель не вправе предоставлять дополнительные медицинские услуги на возмездной основе.',
            style))
    objs.append(
        Paragraph(
            '3.3.	В случае, если при предоставлении платных медицинских услуг потребуется предоставление '
            'дополнительных медицинских услуг по экстренным показаниям для устранения угрозы жизни Пациента'
            ' при внезапных острых заболеваниях, состояниях, обострениях хронических заболеваний, такие '
            'медицинские услуги оказываются без взимания платы в соответствии с Федеральным загоном '
            'от 21.11.2011N 323-ФЗ "Об основах охраны здоровья граждан в Российской Федерации".',
            style))
    objs.append(
        Paragraph(
            '3.4.	В случае отказа Пациента после заключения Договора от получения медицинских услуг Договор '
            'расторгается. При этом Пациент оплачивает Исполнителю фактически понесенные Исполнителем расходы,'
            'связанные с исполнением обязательств по Договору. ', style))
    objs.append(
        Paragraph(
            '3.5. К отношениям, связанным с исполнением настоящего Договора, применяются положения Закона '
            'Российской Федерации от 7 февраля 1992 г. N 2300-1 "О защите прав потребителей".',
            style))
    objs.append(Paragraph('4. ПОРЯДОК ОПЛАТЫ', styleCenter))

    s = pytils.numeral.rubles(float(sum_research_decimal))
    objs.append(
        Paragraph(
            '4.1.	Стоимость медицинских услуг составляет: <u>{}</u> '.format(
                s.capitalize()), style))
    objs.append(Paragraph('Сроки оплаты:', style))
    objs.append(
        Paragraph(
            'Предоплата________________________________________ , оставшаяся сумма______________________________ рублей',
            style))
    objs.append(Paragraph('Сроки оплаты: _________________________', style))
    objs.append(
        Paragraph(
            '4.2.	Компенсируемые расходы Исполнителя на _________________________________________________',
            style))
    objs.append(Paragraph('составляют_____________________ рублей', style))
    objs.append(
        Paragraph(
            '4.3.	Оплата услуг производится путем перечисления суммы на расчетный счет Исполнителя или путем внесения в кассу Исполнителя.',
            style))
    objs.append(
        Paragraph(
            'Пациенту в соответствии с законодательством Российской Федерации выдается документ; '
            'подтверждающий произведенную оплату предоставленных медицинских услуг (кассовый чек, квитанция '
            'или иные документы).', style))
    objs.append(
        Paragraph(
            '4.4.	Дополнительные услуги оплачиваются на основании акта об оказанных услугах, подписанного Сторонами.',
            style))
    objs.append(Paragraph('5. ОТВЕТСТВЕННОСТЬ СТОРОН', styleCenter))
    objs.append(
        Paragraph(
            '5.1.	Исполнитель несет ответственность перед Пациентом за неисполнение или ненадлежащее '
            'исполнение условий настоящего Договора, несоблюдение требований, предъявляемых к методам '
            'диагностики, профилактики и лечения, разрешенным на территории Российской Федерации, а также '
            'в случае причинения вреда здоровью и жизни Пациента.', style))
    objs.append(
        Paragraph(
            '5.2.	При несоблюдении Исполнителем обязательств по срокам исполнения услуг Пациент вправе по своему выбору:',
            style))
    objs.append(Paragraph('- назначить новый срок оказания услуги;', style))
    objs.append(
        Paragraph('- потребовать уменьшения стоимости предоставленной услуги;',
                  style))
    objs.append(
        Paragraph('- потребовать исполнения услуги другим специалистом;',
                  style))
    objs.append(
        Paragraph(
            '- расторгнуть настоящий Договор и потребовать возмещения убытков.',
            style))
    objs.append(
        Paragraph(
            '5.3.	Ни одна из Сторон не будет нести ответственности за полное или частичное неисполнение другой '
            'Стороной своих обязанностей, если, неисполнение будет являться следствием обстоятельств непреодолимой '
            'силы, таких как, пожар, наводнение, землетрясение, забастовки и другие стихийные бедствия; '
            'война и военные действия или другие обстоятельства, находящиеся вне контроля Сторон, '
            'препятствующие выполнению настоящего Договора, возникшие после заключения Договора, а также по '
            'иным основаниям, предусмотренным законом', style))
    objs.append(
        Paragraph(
            'Если любое из таких обстоятельств непосредственно повлияло на неисполнение обязательства в '
            'срок, указанный в Договоре, то этот срок соразмерно отодвигается на время действия соответствующего '
            'обстоятельства.', style))
    objs.append(
        Paragraph(
            '5.4.	Вред, причиненный жизни или здоровью Пациента в результате предоставления некачественной '
            'платной медицинской услуги, подлежит возмещению Исполнителем в соответствии с законодательством '
            'Российской Федерации.', style))
    objs.append(Paragraph('6. ПОРЯДОК РАССМОТРЕНИЯ СПОРОВ', styleCenter))
    objs.append(
        Paragraph(
            '6.1.	Все споры, претензии и разногласия, которые могут возникнуть между Сторонами, будут '
            'разрешаться путем переговоров.', style))
    objs.append(
        Paragraph(
            '6.2.	При не урегулировании в процессе переговоров спорных вопросов споры подлежат рассмотрению '
            'в судебном порядке.', style))
    objs.append(Paragraph('7. СРОК ДЕЙСТВИЯ ДОГОВОРА', styleCenter))
    objs.append(
        Paragraph(
            '7.1.	Срок действия настоящего Договора: с «	»	201	г. по «	»	201	г.',
            style))
    objs.append(
        Paragraph(
            '7.2.	Настоящий Договор, может быть, расторгнут по обоюдному согласию Сторон или в порядке, '
            'предусмотренном действующим законодательством.', style))
    objs.append(
        Paragraph(
            '7.3.	Все изменения и дополнения к настоящему Договору, а также его расторжение считаются '
            'действительными при условии, если они совершены в письменной форме и подписаны уполномоченными'
            ' на то представителями обеих Сторон.', style))
    objs.append(Paragraph('8. ИНЫЕ УСЛОВИЯ', styleCenter))
    objs.append(
        Paragraph(
            '8.1.	Все дополнительные соглашения Сторон, акты и иные приложения к настоящему Договору, '
            'подписываемые Сторонами при исполнении настоящего Договора, являются его неотъемлемой частью.',
            style))
    objs.append(
        Paragraph(
            '8.2.	Настоящий Договор составлен в 2 (двух) экземплярах, имеющих одинаковую юридическую силу, '
            'по одному для каждой из Сторон', style))
    # objs.append(Paragraph('9. АДРЕСА И РЕКВИЗИТЫ СТОРОН', styleCenter))

    styleAtr = deepcopy(style)
    styleAtr.firstLineIndent = 0
    f = ind.family
    n = ind.name[0:1]
    p = ind.patronymic[0:1]
    npf = n + '.' + ' ' + p + '.' + ' ' + f
    fio_director_list = exec_person.split(' ')
    print(fio_director_list)
    dir_f = fio_director_list[0]
    dir_n = fio_director_list[1]
    dir_p = fio_director_list[2]
    dir_npf = dir_n[0:1] + '.' + ' ' + dir_p[0:1] + '.' + ' ' + dir_f

    styleAtrEndStr = deepcopy(styleAtr)

    # styleAtrEndStr.spaceBefor = 5

    space_symbol = '&nbsp;'
    opinion = [
        [
            Paragraph('Исполнитель', styleAtr),
            Paragraph('', styleAtr),
            Paragraph('Пациент/Плательщик:', styleAtr)
        ],
        [
            Paragraph('{} <br/>{}'.format(hospital_name, hospital_address),
                      styleAtr),
            Paragraph('', styleAtr),
            Paragraph(
                '{}<br/>Паспорт: {}-{}<br/>Адрес:{}'.format(
                    individual_fio, document_passport_serial,
                    document_passport_num, ind_card.main_address), styleAtr)
        ],
        [
            Paragraph('', styleAtr),
            Paragraph('', style),
            Paragraph('', styleAtr)
        ],
        [
            Paragraph('Сотрудник {}'.format(hospital_short_name), styleAtr),
            Paragraph('', styleAtr),
            Paragraph('', styleAtr)
        ],
        [
            Paragraph('________________________/{}/'.format(dir_npf),
                      styleAtr),
            Paragraph('', styleAtr),
            Paragraph(
                '/{}/________________________ <font face="Symbola" size=18>\u2713</font>'
                .format(npf), styleAtr)
        ],
    ]

    rowHeights = 5 * [None]
    rowHeights[4] = 35
    tbl = Table(opinion,
                colWidths=(90 * mm, 10 * mm, 90 * mm),
                rowHeights=rowHeights)

    tbl.setStyle(
        TableStyle([
            ('GRID', (0, 0), (-1, -1), 1.0, colors.white),
            ('TOPPADDING', (0, 0), (-1, -1), 1.5 * mm),
            ('VALIGN', (0, 0), (-1, -2), 'TOP'),
            ('VALIGN', (0, -1), (-1, -1), 'BOTTOM'),
            ('BOTTOMPADDING', (0, -1), (-1, -1), 4.2 * mm),
            ('BOTTOMPADDING', (0, -1), (0, -1), 1 * mm),
        ]))

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

    objs.append(
        KeepTogether(
            [Paragraph('9. АДРЕСА И РЕКВИЗИТЫ СТОРОН', styleCenter), tbl]))

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

    styleRight = deepcopy(style)
    styleRight.alignment = TA_RIGHT

    space_symbol = ' '

    qr_napr = ','.join([str(elem) for elem in result_data[3]])
    protect_val = SettingManager.get('protect_val')
    bstr = (qr_napr + protect_val).encode()
    protect_code = str(zlib.crc32(bstr))

    left_size_str = hospital_short_name + 15 * space_symbol + protect_code + 15 * space_symbol

    qr_value = npf + '(' + qr_napr + '),' + protect_code

    def first_pages(canvas, document):
        canvas.saveState()
        canvas.setFont("PTAstraSerifReg", 9)
        # вывести интерактивную форму "текст"
        form = canvas.acroForm
        # canvas.drawString(25, 780, '')
        form.textfield(name='comment',
                       tooltip='comment',
                       fontName='Times-Roman',
                       fontSize=10,
                       x=57,
                       y=750,
                       borderStyle='underlined',
                       borderColor=black,
                       fillColor=white,
                       width=515,
                       height=13,
                       textColor=black,
                       forceBorder=False)

        # Вывести на первой странице код-номер договора
        barcode128.drawOn(canvas, 120 * mm, 283 * mm)

        #вывести внизу QR-code (ФИО, (номера направлений))
        qr_code = qr.QrCodeWidget(qr_value)
        qr_code.barWidth = 70
        qr_code.barHeight = 70
        qr_code.qrVersion = 1
        bounds = qr_code.getBounds()
        width = bounds[2] - bounds[0]
        height = bounds[3] - bounds[1]
        d = Drawing()
        d.add(qr_code)
        renderPDF.draw(d, canvas, 90 * mm, 7)
        #вывести атрибуты для подписей
        canvas.setFont('PTAstraSerifReg', 10)
        canvas.drawString(40 * mm, 10 * mm, '____________________________')
        canvas.drawString(115 * mm, 10 * mm,
                          '/{}/____________________________'.format(npf))
        canvas.setFont('Symbola', 18)
        canvas.drawString(195 * mm, 10 * mm, '\u2713')

        canvas.setFont('PTAstraSerifReg', 8)
        canvas.drawString(50 * mm, 7 * mm, '(подпись сотрудника)')
        canvas.drawString(160 * mm, 7 * mm, '(подпись плательщика)')

        #вывестии защитны вертикальный мелкий текст
        canvas.rotate(90)
        canvas.setFillColor(HexColor(0x4f4b4b))
        canvas.setFont('PTAstraSerifReg', 5.2)
        canvas.drawString(10 * mm, -12 * mm, '{}'.format(6 * left_size_str))

        canvas.restoreState()

    def later_pages(canvas, document):
        canvas.saveState()
        #вывести внизу QR-code (ФИО, (номера направлений))
        qr_code = qr.QrCodeWidget(qr_value)
        qr_code.barWidth = 70
        qr_code.barHeight = 70
        qr_code.qrVersion = 1
        bounds = qr_code.getBounds()
        width = bounds[2] - bounds[0]
        height = bounds[3] - bounds[1]
        d = Drawing()
        d.add(qr_code)
        renderPDF.draw(d, canvas, 90 * mm, 7)
        #вывести атрибуты для подписей
        canvas.setFont('PTAstraSerifReg', 10)
        canvas.drawString(40 * mm, 10 * mm, '____________________________')
        canvas.drawString(115 * mm, 10 * mm,
                          '/{}/____________________________'.format(npf))

        canvas.setFont('Symbola', 18)
        canvas.drawString(195 * mm, 10 * mm, '\u2713')

        canvas.setFont('PTAstraSerifReg', 8)
        canvas.drawString(50 * mm, 7 * mm, '(подпись сотрудника)')
        canvas.drawString(160 * mm, 7 * mm, '(подпись плательщика)')

        canvas.rotate(90)
        canvas.setFillColor(HexColor(0x4f4b4b))
        canvas.setFont('PTAstraSerifReg', 5.2)
        canvas.drawString(10 * mm, -12 * mm, '{}'.format(6 * left_size_str))
        canvas.restoreState()

    doc.build(objs,
              onFirstPage=first_pages,
              onLaterPages=later_pages,
              canvasmaker=PageNumCanvas)

    pdf = buffer.getvalue()

    buffer.close()
    return pdf
Example #53
0
    def generate_pdf(self, filename_with_path, line_chart_data_list):

        elements = []
        # doc = SimpleDocTemplate(filename_with_path, pagesize=LETTER, rightMargin=25, leftMargin=25, topMargin=10,
        #                         bottomMargin=10)
        doc = SimpleDocTemplate(filename_with_path,
                                pagesize=LETTER,
                                rightMargin=25,
                                leftMargin=25,
                                topMargin=10,
                                bottomMargin=10)
        doc.pagesize = portrait(LETTER)

        # document title
        elements.append(self.report_title)
        elements.append(self.spacer_half_inch)

        elements.append(self.add_page_break())

        # update standings style to vertically justify all rows
        standings_style = copy.deepcopy(self.style)
        standings_style.add("VALIGN", (0, 0), (-1, -1), "MIDDLE")

        # standings
        self.create_section(elements, "League Standings",
                            self.standings_headers,
                            self.current_standings_data, standings_style,
                            standings_style, self.standings_col_widths)
        elements.append(self.spacer_tenth_inch)

        # update playoff probabilities style to make playoff teams green
        playoff_probs_style = copy.deepcopy(self.style)
        playoff_probs_style.add("TEXTCOLOR", (0, 1), (-1, self.playoff_slots),
                                colors.green)
        playoff_probs_style.add("FONT", (0, 1), (-1, -1), "Helvetica")

        team_num = 1
        if self.playoff_probs_data:
            for team in self.playoff_probs_data:
                if float(team[3].split("%")[0]) == 100.00 and int(
                        team[4].split(" ")[0]) == 0:
                    playoff_probs_style.add("TEXTCOLOR", (0, team_num),
                                            (-1, team_num), colors.darkgreen)
                    playoff_probs_style.add("FONT", (0, team_num),
                                            (-1, team_num),
                                            "Helvetica-BoldOblique")

                if (int(team[4].split(" ")[0]) +
                        int(self.week)) > self.num_regular_season_weeks:
                    playoff_probs_style.add("TEXTCOLOR", (4, team_num),
                                            (4, team_num), colors.red)

                    if float(team[3].split("%")[0]) == 0.00:
                        playoff_probs_style.add("TEXTCOLOR", (0, team_num),
                                                (-1, team_num), colors.darkred)
                        playoff_probs_style.add("FONT", (0, team_num),
                                                (-1, team_num),
                                                "Helvetica-BoldOblique")

                team_num += 1

        # playoff probabilities
        if self.playoff_probs_data:
            self.create_section(
                elements,
                "Playoff Probabilities",
                self.playoff_probs_headers,
                self.playoff_probs_data,
                playoff_probs_style,
                playoff_probs_style,
                self.playoff_probs_col_widths,
                subtitle_text=
                "Playoff probabilities were calculated using %s Monte Carlo simulations to predict "
                "team performances through the end of the regular fantasy season."
                % "{0:,}".format(
                    self.config.getint("Fantasy_Football_Report_Settings",
                                       "num_playoff_simulations")))
        elements.append(self.add_page_break())

        # power ranking
        self.create_section(
            elements,
            "Team Power Rankings",
            self.power_ranking_headers,
            self.power_ranking_results_data,
            self.style,
            self.style_tied_power_rankings,
            self.power_ranking_col_widths,
            tied_metric_bool=self.tied_power_rankings_bool,
            metric_type="power_rank",
            subtitle_text=
            "Average of weekly score, coaching efficiency and luck ranks.")
        elements.append(self.spacer_twentieth_inch)

        # z-scores (if week 3 or later, once meaningful z-scores can be calculated)
        if self.zscore_results_data[0][3] != "N/A":
            self.create_section(
                elements,
                "Team Z-Score Rankings",
                self.zscores_headers,
                self.zscore_results_data,
                self.style,
                self.style_tied_power_rankings,
                self.metrics_4_col_widths,
                tied_metric_bool=False,
                metric_type="zscore",
                subtitle_text=[
                    "Measure of standard deviations away from mean for a score. Shows teams performing ",
                    "above or below their normal scores for the current week.  See <a href = "
                    "'https://en.wikipedia.org/wiki/Standard_score' color='blue'>Standard Score</a>."
                ])
        elements.append(self.add_page_break())

        # scores
        self.create_section(elements,
                            "Team Score Rankings",
                            self.scores_headers,
                            self.score_results_data,
                            self.style,
                            self.style,
                            self.metrics_5_col_widths,
                            tied_metric_bool=self.tied_scores_bool,
                            metric_type="scores")
        elements.append(self.spacer_twentieth_inch)

        # coaching efficiency
        self.create_section(
            elements,
            "Team Coaching Efficiency Rankings",
            self.efficiency_headers,
            self.coaching_efficiency_results_data,
            self.style,
            self.style_tied_efficiencies,
            self.metrics_5_col_widths,
            tied_metric_bool=self.tied_coaching_efficiencies_bool,
            metric_type="coaching_efficiency")
        elements.append(self.spacer_twentieth_inch)

        # luck
        self.create_section(elements,
                            "Team Luck Rankings",
                            self.luck_headers,
                            self.luck_results_data,
                            self.style,
                            self.style_tied_luck,
                            self.metrics_5_col_widths,
                            tied_metric_bool=self.tied_lucks_bool,
                            metric_type="luck")
        elements.append(self.add_page_break())

        # weekly top scorers
        self.create_section(elements,
                            "Weekly Top Scorers",
                            self.weekly_top_scorer_headers,
                            self.weekly_top_scorers,
                            self.style_no_highlight,
                            self.style_no_highlight,
                            self.metrics_4_col_widths,
                            tied_metric_bool=self.tied_scores_bool,
                            metric_type="top_scorers")
        elements.append(self.spacer_twentieth_inch)

        # weekly highest coaching efficiency
        self.create_section(
            elements,
            "Weekly Highest Coaching Efficiency",
            self.weekly_highest_ce_headers,
            self.weekly_highest_ce,
            self.style_no_highlight,
            self.style_no_highlight,
            self.metrics_4_col_widths,
            tied_metric_bool=self.tied_coaching_efficiencies_bool,
            metric_type="highest_ce")

        elements.append(self.add_page_break())

        # bad boy rankings
        self.create_section(elements,
                            "Bad Boy Rankings",
                            self.bad_boy_headers,
                            self.bad_boy_results_data,
                            self.style,
                            self.style_tied_bad_boy,
                            self.bad_boy_col_widths,
                            tied_metric_bool=self.tied_bad_boy_bool,
                            metric_type="bad_boy")
        elements.append(self.spacer_twentieth_inch)

        # beef rankings
        self.create_section(
            elements,
            "Beef Rankings",
            self.beef_headers,
            self.beef_results_data,
            self.style_left_alighn_right_col,
            self.style_tied_beef,
            self.metrics_4_col_widths_wide_right,
            tied_metric_bool=self.tied_beef_bool,
            metric_type="beef",
            subtitle_text=[
                "Team Beef Ranking is measured in TABBUs (Trimmed And Boneless Beef Units). "
                "One TABBU is currently established as 500 lbs.",
                "TABBU derivation stems from academic research done for the beef industry found <a href = "
                "'https://extension.tennessee.edu/publications/Documents/PB1822.pdf' color='blue'>here</a>."
            ])

        elements.append(self.add_page_break())

        series_names = line_chart_data_list[0]
        points_data = line_chart_data_list[2]
        efficiency_data = line_chart_data_list[3]
        luck_data = line_chart_data_list[4]
        zscore_data = line_chart_data_list[5]

        # Remove any zeros from coaching efficiency to make table prettier
        for team in efficiency_data:
            week_index = 0
            for week in team:
                if len(team) > 1:
                    if week[1] == 0.0:
                        del team[week_index]
                week_index += 1

        # create line charts for points, coaching efficiency, and luck
        elements.append(
            self.create_line_chart(points_data, len(points_data[0]),
                                   series_names, "Weekly Points", "Weeks",
                                   "Fantasy Points", 10.00))
        elements.append(self.spacer_twentieth_inch)
        elements.append(
            self.create_line_chart(efficiency_data, len(points_data[0]),
                                   series_names, "Weekly Coaching Efficiency",
                                   "Weeks", "Coaching Efficiency (%)", 5.00))
        elements.append(self.spacer_twentieth_inch)
        elements.append(
            self.create_line_chart(luck_data, len(points_data[0]),
                                   series_names, "Weekly Luck", "Weeks",
                                   "Luck (%)", 20.00))
        elements.append(self.spacer_tenth_inch)
        elements.append(self.add_page_break())

        # # Exclude z-score time series data unless it is determined to be relevant
        # elements.append(self.create_line_chart(zscore_data, len(points_data[0]), series_names, "Weekly Z-Score",
        #                                        "Weeks", "Z-Score", 5.00))
        # elements.append(self.spacer_tenth_inch)
        # elements.append(self.page_break)

        # dynamically build additional pages for individual team stats
        self.create_team_stats_pages(
            elements, self.weekly_points_by_position_data,
            self.season_average_team_points_by_position)

        # insert table of contents after report title and spacer
        elements.insert(2, self.toc.get_toc())

        elements.append(self.report_footer)

        # build pdf
        logger.info("generating PDF ({})...".format(
            filename_with_path.split("/")[-1]))
        doc.build(elements,
                  onFirstPage=self.add_page_number,
                  onLaterPages=self.add_page_number)

        return doc.filename
Example #54
0
        ],
        style=[
            ('FONTNAME', (0, 0), (-1, -1), 'Helvetica-Bold'),
            ('FONTSIZE', (0, 0), (-1, -1), 10),
            ('TOPPADDING', (0, 0), (-1, -1), 0.1 * inch),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 0.1 * inch),
            ('ALIGN', (0, 0), (0, -1), 'RIGHT'),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
        ]
    ))

    return story


_generators = {
    'm': (generate_match_sheets, 'match sheets', 'match_sheets', portrait(A4)),
    'j': (generate_jury_sheets, 'jury sheets', 'jury_sheets', portrait(A4)),
    'a': (generate_approval_sheets, 'approval sheets', 'approval_sheets', portrait(A4)),
    's': (generate_stand_labels, 'stand labels', 'stand_labels', portrait(A4)),
    'p': (generate_planning, 'planning', 'planning', landscape(A4)),
    'l': (generate_teams_list, 'teams list', 'teams_list', portrait(A4)),
    'x': (generate_signs, 'signs', 'signs', landscape(A4)),
}


class FormsDocTemplate(SimpleDocTemplate):
    # declare these attributes for Lint not to complain
    timestamp = text_x = text_y = pagesize = rightMargin = bottomMargin = None

    def handle_documentBegin(self):
        SimpleDocTemplate.handle_documentBegin(self)
Example #55
0
 def __call__(self, output):
     psize = portrait(A4)
     super().__call__(output, psize)
Example #56
0
# BGlog.py
# Derek Johnson
# 01 Apr 2013
#
# Description: Read Exported Glucose Buddy log and print table of BG values.
import sys
import csv
import datetime
from pprint import pprint

from reportlab.pdfgen.canvas import Canvas
from reportlab.lib import colors
from reportlab.lib.units import cm, mm, inch, pica
from reportlab.lib.pagesizes import letter, A4, landscape, portrait

width, height = portrait(A4)

logfile = "/Users/derekjohnson/Dropbox/Diabetes/MyExportedGlucoseBuddyLogs.csv"

class BGreading(object):
    def __init__(self, reading):
        self.value = float(reading['Value'])
        self.datetime = reading['Date Time'] 
        self.event = reading['Event']
    def toString(self):
        return "%s: %2.1f" % (self.event, self.value)
    def getValue(self):
        return self.value
    def getDate(self):
        return self.datetime.date()
    def getEvent(self):
Example #57
0
File: pdf.py Project: dariosky/tam
def render_to_reportlab(context):
    """
        In context dictionary we could have a 'fattura'
        or a list of fatture in 'fatture'.

        Everything will be appended to a pdf returned as Django response.

        To reset page counter between different invoices, we'll use
        2 "Normale" templates, one for even and one for odds, so every times
        the template changes we'll reset the NumberedCanvas
    """
    if "fattura" in context and "fatture" in context:
        raise Exception("Please create PDF choosing between a fattura or multiple fatture")
    if "fattura" in context:
        fatture = [context.get('fattura')]
    else:
        fatture = context.get('fatture')

    response = http.HttpResponse(content_type='application/pdf')
    NormalTemplates = ['Normale0', 'Normale1']

    fatture_rimanenti = len(fatture)
    story = []

    pageTemplates = [
        PageTemplate(id='Normale0', onPage=onPageNormal),
        PageTemplate(id='Normale1', onPage=onPageNormal),
        PageTemplate(id='ConducenteConsorzio', onPage=onPageConducenteConsorzio),
        PageTemplate(id='ConsorzioConducente', onPage=onPageConsorzioConducente),
    ]
    # scelgo il template della prima pagina come primo della lista
    if fatture[0].is_ricevuta_sdoppiata():
        lastTemplateID = 'ConducenteConsorzio'
        pageTemplates = pageTemplates[2:] + pageTemplates[:2]
    else:
        lastTemplateID = 'Normale0'

    width, height = portrait(A4)
    doc = BaseDocTemplate(
        response,
        pagesize=(width, height),
        leftMargin=1 * cm,
        rightMargin=1 * cm,
        bottomMargin=1.5 * cm,
        topMargin=1 * cm,
        showBoundary=test,
        pageTemplates=pageTemplates,
    )
    doc.fatture = fatture
    doc.lastTemplateID = lastTemplateID
    doc.fattura_corrente = 0

    for fattura in fatture:
        ricevutaMultipla = fattura.is_ricevuta_sdoppiata()
        story_fattura = []
        fatturazione = FATTURE_PER_TIPO[fattura.tipo]

        righeFattura = [
            ('Descrizione', 'Q.tà',) +
            (('Prezzo', 'IVA %') if FATTURE_SHOW_VAT_COLUMN else tuple()) +
            ('Importo',),
        ]

        righe = fattura.righe.all()

        raggruppa_barbatrucco = False
        if fatturazione.codice == "5":
            totale = sum([r.val_totale() for r in righe])
            conducente = righe[0].conducente if righe else None
            if "Imposta di bollo" not in [r.descrizione for r in righe]:
                if not (totale < settings.MIN_PRICE_FOR_TAXSTAMP
                        and (conducente is None or conducente.emette_ricevute)
                ):
                    raggruppa_barbatrucco = True

        if raggruppa_barbatrucco:
            # print "5 esente iva con barbatrucco"

            netto = totale / Decimal(1.1)

            class RigaTotaleIvata(object):  # una riga che fa corrispondere il totale
                descrizione = "Servizi per consorzio."
                note = None
                qta = 1
                prezzo = netto
                iva = 10

                def val_imponibile(self):
                    return self.prezzo

                def val_iva(self):
                    return totale - netto

                def val_totale(self):
                    return totale

            riga = RigaTotaleIvata()
            # la fattura ha totale pari al totale di tutte le righe
            # l'iva è fissa al 10% e il netto è calcolato di conseguenza
            imponibile = netto
            iva = totale - netto
            righe = [riga]

        else:
            imponibile = fattura.val_imponibile()
            iva = fattura.val_iva()

        for riga in righe:
            descrizione = riga.descrizione
            if riga.note: descrizione += " (%s)" % riga.note
            row_values = (
                (
                    Paragraph(descrizione, normalStyle),
                    Paragraph("%s" % riga.qta, normalStyle)
                ) +
                (
                    (
                        moneyfmt(riga.prezzo),
                        riga.iva,
                    ) if FATTURE_SHOW_VAT_COLUMN else tuple()) +
                (
                    moneyfmt(riga.val_totale()),
                )
            )
            righeFattura.append(row_values)
        righeTotali = []
        if FATTURE_SHOW_VAT_COLUMN:
            righeTotali.append((
                'Imponibile', moneyfmt(imponibile)
            ))
            righeTotali.append((
                'IVA', moneyfmt(iva)
            ))
        righeTotali.append((
            'TOTALE', moneyfmt(fattura.val_totale())
        ))
        righeStyle = TableStyle([
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ('ALIGN', (0, 0), (-1, -1), 'RIGHT'),  # globalmente allineato a destra...
            ('ALIGN', (0, 0), (1, -1), 'LEFT'),  # tranne la prima colonna (con la descrizione)
            ('GRID', (0, 1), (-1, -1), 0.1, colors.grey),
            ('FACE', (0, 0), (-1, -1), 'Helvetica'),

            ('FACE', (0, 0), (-1, 0), 'Helvetica-Bold'),  # header
            ('SIZE', (0, 0), (-1, -1), 8),

            # ('SPAN', (0, -1), (3, -1)),	# anziché mettere lo span qui aggiungo in coda una tabella diversa
        ])
        totaliStyle = TableStyle([
            ('ALIGN', (0, 0), (-1, -1), 'RIGHT'),
            ('GRID', (-1, 0), (-1, -1), 0.1, colors.grey),

            ('FACE', (0, 0), (-1, -1), 'Helvetica'),  # header
            ('FACE', (0, -1), (-1, -1), 'Helvetica-Bold'),  # Totale
            ('SIZE', (0, 0), (-1, -1), 8),

        ])

        price_columns = 4 if FATTURE_SHOW_VAT_COLUMN else 2
        colWidths = (
            ((width - doc.leftMargin - doc.rightMargin) - (1.6 * cm * price_columns),) +
            (1.6 * cm,) * price_columns
        )
        story_fattura = [Table(righeFattura, style=righeStyle, repeatRows=1, colWidths=colWidths)]
        story_fattura.append(KeepTogether(Table(righeTotali, style=totaliStyle,
                                                colWidths=(
                                                    width - doc.leftMargin - doc.rightMargin - 1.6 * cm,
                                                    1.6 * cm))))

        if ricevutaMultipla:  # le ricevute si raddoppiano con 2 template diversi
            # raddoppio lo story di questa fattura cambiando template
            story_fattura = story_fattura + [NextPageTemplate("ConsorzioConducente"),
                                             PageBreak()] + story_fattura
        fatture_rimanenti -= 1
        if fatture_rimanenti:
            story_fattura += [NextPageTemplate(NormalTemplates[-1]), PageBreak()]

        NormalTemplates.reverse()  # reverse current, next normal template

        story = story + story_fattura

    doc.build(story, canvasmaker=NumberedCanvas)
    return response
Example #58
0
    def pagesize(self):
        from reportlab.lib import pagesizes

        return pagesizes.portrait(pagesizes.A4)
Example #59
0
def main():
    """
    Función que genera los mapas de temperatura mínima
    """

    startProcess = strftime("%Y-%m-%d %H:%M:%S")
    # #%% fecha del pronostico
    # # fechaPronostico = strftime("%Y-%m-%d")
    fechaPronostico = "2018-04-25"
    variables = ["Rain", "Tmax", "Tmin", "Tpro", "Hr", "Hrmin", "Hrmax"]

    LAT_MAX = 33.5791
    LAT_MIN = 12.3782

    LONG_MAX = -86.101
    LONG_MIN = -118.236

    #%% generate arrayFechas
    # Generate Days
    arrayFechas = []
    tanio, tmes, tdia = fechaPronostico.split('-')
    anio = int(tanio)
    mes = int(tmes)
    dia = int(tdia)

    dirAnio = anio
    dirMes = mes
    dirDia = dia

    #%% generate arrayFechas

    for i in range(0, 5, 1):
        if i == 0:
            newDiaString = '{}'.format(dia)
            if len(newDiaString) == 1:
                newDiaString = '0' + newDiaString
            newMesString = '{}'.format(mes)
            if len(newMesString) == 1:
                newMesString = '0' + newMesString
            fecha = '{}'.format(anio) + "-" + newMesString + "-" + newDiaString
            arrayFechas.append(fecha)
        if i > 0:
            dia = dia + 1
            if mes == 2 and anio % 4 == 0:
                diaEnElMes = 29
            elif mes == 2 and anio % 4 != 0:
                diaEnElMes = 28
            elif mes == 1 or mes == 3 or mes == 5 or mes == 7 or mes == 8 or mes == 10 or mes == 12:
                diaEnElMes = 31
            elif mes == 4 or mes == 6 or mes == 9 or mes == 11:
                diaEnElMes = 30
            if dia > diaEnElMes:
                mes = mes + 1
                dia = 1
            if mes > 12:
                anio = anio + 1
                mes = 1
            newDiaString = '{}'.format(dia)
            if len(newDiaString) == 1:
                newDiaString = '0' + newDiaString
            newMesString = '{}'.format(mes)
            if len(newMesString) == 1:
                newMesString = '0' + newMesString
            fecha = '{}'.format(anio) + "-" + newMesString + "-" + newDiaString
            arrayFechas.append(fecha)

    # path server
    path = "/home/jorge/Documents/Research/generar_boletin"
    # os.chdir("/home/jorge/Documents/work/autoPronosticoSonora")
    os.chdir(path)

    #%% read csvs
    pathFile1 = '{}/data/{}/d1.txt'.format(path, fechaPronostico)
    pathFile2 = '{}/data/{}/d2.txt'.format(path, fechaPronostico)
    pathFile3 = '{}/data/{}/d3.txt'.format(path, fechaPronostico)
    pathFile4 = '{}/data/{}/d4.txt'.format(path, fechaPronostico)
    pathFile5 = '{}/data/{}/d5.txt'.format(path, fechaPronostico)

    data1 = pd.read_table(pathFile1, sep=',')
    data2 = pd.read_table(pathFile2, sep=',')
    data3 = pd.read_table(pathFile3, sep=',')
    data4 = pd.read_table(pathFile4, sep=',')
    data5 = pd.read_table(pathFile5, sep=',')

    cols = [
        "Long", "Lat", "Graupel", "Hail", "Rain", "Tmax", "Tmin", "Tpro",
        "Dpoint", "Hr", "Windpro", "WindDir", "Hrmin", "Hrmax", "TprSoil0_10",
        "TprSoil10_40", "WprSoil0_10", "WprSoil10_40"
    ]

    data1.columns = cols
    data2.columns = cols
    data3.columns = cols
    data4.columns = cols
    data5.columns = cols

    # ciclo para generar los mapas de cada una de las variables
    for variable in variables:
        #%% make one dataFrame
        data = data1.filter(items=['Long', 'Lat', variable])
        data['{}1'.format(variable)] = data1[variable]
        data['{}2'.format(variable)] = data2[variable]
        data['{}3'.format(variable)] = data3[variable]
        data['{}4'.format(variable)] = data4[variable]
        data['{}5'.format(variable)] = data5[variable]

        #%% get values from Ags
        data = data.loc[data['Lat'] >= LAT_MIN]
        data = data.loc[data['Lat'] <= LAT_MAX]
        data = data.loc[data['Long'] >= LONG_MIN]
        data = data.loc[data['Long'] <= LONG_MAX]

        print(data.head())

        #%% get x and y values
        lons = np.array(data['Long'])
        lats = np.array(data['Lat'])

        #%% loop diarios

        counterFecha = 0

        for i in range(1, 6, 1):
            #%% set up plot
            plt.clf()
            #fig = plt.figure(figsize=(48,24))
            m = Basemap(projection='mill',
                        llcrnrlat=LAT_MIN,
                        urcrnrlat=LAT_MAX,
                        llcrnrlon=LONG_MIN,
                        urcrnrlon=LONG_MAX,
                        resolution='h')

            #%% generate lats, lons
            x, y = m(lons, lats)

            #%% number of cols and rows
            numcols = len(x)
            numrows = len(y)

            #%% generate xi, yi
            xi = np.linspace(x.min(), x.max(), 1000)
            yi = np.linspace(y.min(), y.max(), 1000)

            #%% generate meshgrid
            xi, yi = np.meshgrid(xi, yi)

            #%% genate zi
            tempTitleColumn = "{}{}".format(variable, i)
            z = np.array(data[tempTitleColumn])
            zi = gd((x, y), z, (xi, yi), method='cubic')

            #%% generate clevs
            #generate clevs
            step = (z.max() - z.min()) / 15

            if variable == "Rain":
                clevs = [
                    1, 5, 10, 20, 30, 50, 70, 100, 150, 200, 250, 300, 350,
                    400, 500
                ]
            else:
                clevs = np.linspace(z.min(), z.max(), 15)

            cmap_variable = colores_por_variable(variable)

            #%% contour plot
            cs = m.contourf(xi,
                            yi,
                            zi,
                            clevs,
                            zorder=4,
                            alpha=0.5,
                            cmap=cmap_variable)
            #%% draw map details
            # m.drawcoastlines()
            # m.drawstates(linewidth=0.7)
            # m.drawcountries()

            #%% read municipios shape file
            m.readshapefile('shapes/Estados', 'Estados')
            #m.drawmapscale(22, -103, 23, -102, 100, units='km', fontsize=14, yoffset=None, barstyle='fancy', labelstyle='simple', fillcolor1='w', fillcolor2='#000000',fontcolor='#000000', zorder=5)

            #%% colorbar
            cbar = m.colorbar(cs, location='right', pad="5%")

            # simbología colorbar
            # simbologia = generar_simbologia(variable)
            # cbar.set_label(simbologia)
            titulo_mapa = generarTexto(variable, arrayFechas[counterFecha])
            plt.title(titulo_mapa)
            titulo_archivo = "{}/data/{}/{}_{}.png".format(
                path, fechaPronostico, variable, i)
            plt.annotate('@2018 INIFAP',
                         xy=(-102, 22),
                         xycoords='figure fraction',
                         xytext=(0.45, 0.45),
                         color='g')
            plt.savefig(titulo_archivo, dpi=300, bbox_inches='tight')
            counterFecha += 1
            print('****** Genereate: {}'.format(titulo_archivo))

        # generar pdf
        """
        GENERAR GRÁFICA

        y1 = []
        y2 = []

        for k in range(1,6):
            y1.append(data["{}{}".format(variable, k)].max())
            y2.append(data["{}{}".format(variable, k)].min())

        ind = np.arange(5)

        fig, ax = plt.subplots()
        width = 0.35
        rects1 = ax.bar(ind, y1, width, color='darkred')
        rects2 = ax.bar(ind + width, y2, width, color='darkblue')

        # add some text for labels, title and axes ticks
        # ax.set_ylabel(simbologia)
        # ax.set_title(variable)
        ax.set_xticks(ind + width / 2)
        ax.set_xticklabels(arrayFechas)

        # ax.legend((rects1[0], rects2[0]), ('Máximo', 'Mínimo'), loc=3)

        def autolabel(rects):
            # Attach a text label above each bar displaying its height
            for rect in rects:
                height = rect.get_height()
                ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,
                        '%d' % int(height),
                        ha='center', va='bottom')

        autolabel(rects1)
        autolabel(rects2)

        titulo_grafica = "{}/data/{}/{}_grafica.png".format(path, fechaPronostico, variable)

        plt.savefig(titulo_grafica, dpi=600, bbox_inches='tight' )
        """

        nombre_archivo_pdf = "{}/data/{}/{}.pdf".format(
            path, fechaPronostico, variable)
        c = canvas.Canvas(nombre_archivo_pdf, pagesize=portrait(letter))

        # logo inifap
        logo_inifap = "{}/images/inifap.jpg".format(path)
        c.drawImage(logo_inifap, 20, 700, width=100, height=100)

        # encabezado
        c.setFont("Helvetica", 20, leading=None)
        titulo_pdf = generar_titulo_pdf(variable)
        c.drawCentredString(350, 750, titulo_pdf)

        # imagen anuales
        imagen_1 = "{}/data/{}/{}_1.png".format(path, fechaPronostico,
                                                variable)
        imagen_2 = "{}/data/{}/{}_2.png".format(path, fechaPronostico,
                                                variable)
        imagen_3 = "{}/data/{}/{}_3.png".format(path, fechaPronostico,
                                                variable)
        imagen_4 = "{}/data/{}/{}_4.png".format(path, fechaPronostico,
                                                variable)
        imagen_5 = "{}/data/{}/{}_5.png".format(path, fechaPronostico,
                                                variable)
        imagen_6 = "{}/images/info_wrf.png".format(path)

        # draw images
        c.drawImage(imagen_1, 20, 475, width=260, height=172)
        c.drawImage(imagen_2, 325, 475, width=260, height=172)
        c.drawImage(imagen_3, 20, 250, width=260, height=172)
        c.drawImage(imagen_4, 325, 250, width=260, height=172)
        c.drawImage(imagen_5, 20, 25, width=260, height=172)
        c.drawImage(imagen_6, 325, 25, width=260, height=172)

        c.showPage()
        c.save()

        print(titulo_pdf)

    # generar boletin
    ruta_pdf = "{}/data/{}/".format(path, fechaPronostico)
    os.chdir(ruta_pdf)
    os.system(
        "pdftk Rain.pdf Tmax.pdf Tmin.pdf Tpro.pdf Hrmax.pdf Hrmin.pdf Hr.pdf cat output boletin.pdf"
    )
    endProcess = strftime("%Y-%m-%d %H:%M:%S")
    print(startProcess)
    print(endProcess)

    access = claves()

    ftp = ftplib.FTP(access.ip)
    ftp.login(access.usr, access.pwd)
    #%% cambiar a directorio
    ftp.cwd('Content/documentos')

    # subir archivo
    fileName = "boletin.pdf"
    file = open(fileName, 'rb')
    comandoFTP = 'STOR boletin.pdf'  # file to send
    ftp.storbinary(comandoFTP, file)

    # cerrar conexión
    file.close()  # close file and FTP
    ftp.quit()