Пример #1
0
      def addTable(self,ndata,nkeys=None):
          data = []
          if not nkeys:
             keys = self.hlib.getKeys(ndata)
             data.append(keys)
          else:
             keys = nkeys 
             data.append(nkeys)
          for x in ndata:
              lister = [] 
              for b in range(len(keys)):
                  if keys[b] not in x:
                     outb = None
                  else:
                     outb = x[keys[b]]
                  t = Paragraph(str(outb),self.styles["Normal"])
                  lister.append(t)
              data.append(lister)

          tblStyle = TableStyle([('TEXTCOLOR',(0,0),(-1,-1),black),
                                 ('VALIGN',(0,0),(-1,-1),'TOP'),
                                 ('BOX',(0,0),(-1,-1),1,black),
                                 ('INNERGRID',(0,0),(-1,-1),1,black),
                                 ('BACKGROUND',(0,0),(-1,0),lightblue)])

          t = LongTable(data,repeatRows=1)
          t.setStyle(tblStyle)
          self.story.append(t)
          self.story.append(CondPageBreak(6))
Пример #2
0
def footer(canvas, doc):
    canvas.saveState()
    P = Paragraph("ReadyMade Report",
                  styleN)
    w, h = P.wrap(doc.width, doc.bottomMargin)
    P.drawOn(canvas, doc.leftMargin, h)
    canvas.restoreState()
Пример #3
0
 def createParagraph(self, ptext, x, y, style=None):
     """"""
     if not style:
         style = self.styles["Normal"]
     p = Paragraph(ptext, style=style)
     p.wrapOn(self.c, self.width, self.height)
     p.drawOn(self.c, *self.coord(x, y))
Пример #4
0
def hello(c, link):
	c.translate(ORIGIN_X, ORIGIN_Y)

	# Draw paragraph
	stylesheet = getSampleStyleSheet()
	style = stylesheet['BodyText']
	style.fontName = 'LeagueGothic'
	style.fontSize = 42
	style.leading = 44

	p = Paragraph('<b>print</b><br/>your<br/><b>badge</b><br/>here', style)
	qr_left = 30*mm
	p_w, p_h = p.wrap(qr_left, HEIGHT)
	p.drawOn(c, 0, 0)


	# Add QR Code
	qr_code = qr.QrCodeWidget(link)
	qr_bounds = qr_code.getBounds()
	qr_width = qr_bounds[2] - qr_bounds[0]
	qr_height = qr_bounds[3] - qr_bounds[1]
	d = Drawing(HEIGHT, HEIGHT, transform=[HEIGHT/qr_width,0,0,HEIGHT/qr_height,0,0])
	d.add(qr_code)
	renderPDF.draw(d, c, qr_left, 0)

	# Draw thin line between text and QR code
	c.line(qr_left, 0, qr_left, HEIGHT)
	c.line(qr_left + HEIGHT, 0, qr_left+HEIGHT, HEIGHT)

	img_left = qr_left + HEIGHT

	# Draw images
	c.drawImage('images/ipv6.jpg', img_left, 0, 20*mm, 1/3 * HEIGHT, mask=None, preserveAspectRatio=True, anchor='c')
	c.drawImage('images/ffrhein_logo_claim_line_rot.png', img_left, 1/3*HEIGHT, 20*mm, 2/3 * HEIGHT, mask=None, preserveAspectRatio=True, anchor='c')
Пример #5
0
def footer_building(canvas, doc, styles):
    pageinfo = _('scores_sheet')
    footer = Paragraph(''' <para align=right>Page %d - %s </para>''' % (doc.page, pageinfo), styles['Normal'])
    w, h = footer.wrap(doc.width, doc.bottomMargin)
    footer.drawOn(canvas, doc.leftMargin, h)

#
#
#
#
# class NumberedCanvas(canvas.Canvas):
#     def __init__(self, *args, **kwargs):
#         canvas.Canvas.__init__(self, *args, **kwargs)
#         self._saved_page_states = []
#
#     def showPage(self):
#         self._saved_page_states.append(dict(self.__dict__))
#         self._startPage()
#
#     def save(self):
#         """add page info to each page (page x of y)"""
#         num_pages = len(self._saved_page_states)
#         for state in self._saved_page_states:
#             self.__dict__.update(state)
#             self.draw_page_number(num_pages)
#             canvas.Canvas.showPage(self)
#         canvas.Canvas.save(self)
#
#     def draw_page_number(self, page_count):
#         self.setFont("Helvetica", 7)
#         self.drawRightString(200*mm, 20*mm,
#                              "Page %d of %d" % (self._pageNumber, page_count))
Пример #6
0
    def _header_footer(canvas,doc):
        #guardamos el estado de nuestro canvas , para poder dibujar en el 
        canvas.saveState()
        canvas.setTitle("Cotizacion Cliente")
        styles = getSampleStyleSheet()

        #header
        header = Image('/home/borbolla/metrology/static_media/assets/images/borbolla_metrology_logo.jpg' )
        header.drawHeight = 60
        header.drawWidth = 424
        header.hAlign = 'RIGHT'
        w , h = header.wrap(doc.width , doc.topMargin)
        header.drawOn(canvas , doc.leftMargin , 700)
        
        marcas = Image('/home/borbolla/metrology/static_media/assets/images/marcas.png' )
        marcas.drawWidth = 90
        marcas.drawHeight = 477
        marcas.drawOn(canvas , 20,200) 
        
        marcas2 = Image('/home/borbolla/metrology/static_media/assets/images/logo.png' )
        marcas2.drawWidth = 116
        marcas2.drawHeight = 34
        marcas2.drawOn(canvas , 20,150) 

        # Footer
        footer = Paragraph('www.borbollametrology.com', styles['Normal'])
        w, h = footer.wrap(doc.width, doc.bottomMargin)
        footer.drawOn(canvas, doc.leftMargin, h)
 
        # Release the canvas
        canvas.restoreState()
Пример #7
0
def fit_text(c, text, x, y, max_w, max_h, font_name='Helvetica', 
             padding_w=4.5, padding_h=4.5, font_decrement=0.0625):
    """Draw text, reducing font size until it fits with a given max width and
    height."""

    max_w -= (padding_w * 2.0)
    max_h -= (padding_h * 2.0)

    x += padding_w
    y += padding_h

    font_size = max_h

    while font_size > 1.0:
        ps = ParagraphStyle(name='text', alignment=TA_CENTER,
                            fontName=font_name, fontSize=font_size,
                            leading=font_size)
        p = Paragraph(text, ps)
        actual_w, actual_h = p.wrapOn(c, max_w, max_h)
        if actual_h > max_h or actual_w > max_w:
            font_size -= font_decrement
        else:
            y_pad = (max_h - actual_h) / 2
            p.drawOn(c, x, y + y_pad)
            return
Пример #8
0
def generate_certificate(description_of_items,cost_of_items,amount,cost,qty,raise_for,request ):

    buffer = BytesIO()
    styleSheet = getSampleStyleSheet()
    style = styleSheet['Normal']
    canv = Canvas('my_pdf.pdf')
    canv.setFillColorRGB(0, 0, 255)
    canv.setFont('Helvetica-Bold', 44, leading=None)
    canv.drawCentredString(102, 800, "INVOICE")
    canv.setFont('Helvetica-Bold', 8, leading=None)
    #canv.drawCentredString(38, 824, "From:")
    b = Company_credentials.objects.get(user=request.user)
    canv.setFillColorRGB(0, 0, 255)
    canv.drawCentredString(480, 826, b.company_name)
    canv.drawCentredString(480, 813, b.email)
    canv.drawCentredString(480, 801, b.country + ',' + b.phone_number)
    #canv.drawCentredString(480, 790, b.email)
    canv.setFillColorRGB(0, 0, 0)

    canv.drawCentredString(480, 790, "Raised on:" + str(datetime.date.today()) )
    canv.line(0, 785, 800, 785)
    canv.setFont('Helvetica', 21, leading=None)
    canv.setFillColorRGB(0, 0, 255)
    canv.drawCentredString(68, 760, "Description:")
    canv.setFillColorRGB(0, 0, 0)
    canv.setFont('Helvetica-Bold', 14, leading=None)
    canv.drawCentredString(120, 730, "ITEMS")
    canv.drawCentredString(320, 730, "RATE")
    canv.drawCentredString(410, 730, "QTY")
    canv.drawCentredString(500, 730, "AMOUNT")
    canv.setFont('Helvetica', 8, leading=None)
    y_coordinate = 710
    chaska = 0
    length = len(description_of_items)
    for chaska in range(length):
        canv.drawCentredString(120, y_coordinate,description_of_items[chaska])
        canv.drawCentredString(320, y_coordinate, str(cost_of_items[chaska]))
        canv.drawCentredString(410, y_coordinate, str(qty[chaska]))
        canv.drawCentredString(500, y_coordinate, '$' + str(amount[chaska]))
        y_coordinate = y_coordinate - 15
    y_coordinate = y_coordinate - 25
    canv.line(310, y_coordinate, 580, y_coordinate)
    canv.setFont('Helvetica-Bold', 12, leading=None)
    canv.drawCentredString(410, y_coordinate-16, "Total")
    canv.drawCentredString(500, y_coordinate-16, '$' + str(cost))
    canv.setFillColorRGB(0,0,255)
    canv.setFont('Helvetica', 16, leading=None)
    canv.drawCentredString(55, y_coordinate-16, "Raised For:")
    canv.setFillColorRGB(0, 0, 0)
    P = Paragraph(raise_for, style)
    aW = 180
    aH = y_coordinate-46
    w, h = P.wrap(aW, aH)  # find required space
    if w <= aW and h <= aH:
        P.drawOn(canv, 12, aH)
        aH = aH - h  # reduce the available height
    canv.save()
    pdf = buffer.getvalue()
    buffer.close()
    return pdf
Пример #9
0
 def draw(self):
     canvas = self.canv
     h, w = float(self.img.height), float(self.img.width)
     if not self.img.iptc.caption:
         fsz = 5.0
     else:
         fsz = 0.85*inch
     if w > h*1.3:
         fsz = 0.25*inch
     s = self.size - fsz
     if h > w:
         ratio = w / h
         h = s
         w = s * ratio
     else:
         ratio = h / w
         w = s
         h = s * ratio
     img = Image(self.img.path, height=h, width=w)
     w, h = img.wrap(w, h)
     iw, ih = w, h
     imgx, imgy = (self.size - s - (fsz/2.0), self.size - h)
     img.drawOn(self.canv, imgx, imgy)
     print "%.2f x %.2f (%.2f x %.2f dpi)" % (w/inch, h/inch, float(o.width) / (w/inch), float(o.height) / (h/inch) )
     p = Paragraph(self.img.iptc.caption, styleN)
     w, h = p.wrap(self.size - 10.0, 1.3*inch)
     print "Text %.2f x %.2f" % (w/inch, h/inch)
     p.drawOn(self.canv, 3.0, (imgy - h) - 3.0)
     canvas.rect(imgx, imgy, iw, ih, stroke=1, fill=0)
Пример #10
0
 def __init__(self, text, caption):
     figures.Figure.__init__(self, 0, 0, caption)
     descrStyle = ParagraphStyle("description", fontName="Courier", fontSize=8, leading=9.6)
     textStyle = B
     self.text = text
     self.left = Paragraph("<![CDATA[" + text + "]]>", descrStyle)
     self.right = Paragraph(text, B)
Пример #11
0
	def drawText(self,txt,x,y,w,h,style={}):
		margin = 0
		self.canvas.saveState()
		path = self.canvas.beginPath()
		path.rect(x,y,w,h)
		self.canvas.clipPath(path,stroke=1)
		_s = styles['BodyText']
		_s = ParagraphStyle({})
		_s.fontSize = style['fontSize']*1.0
		# _s.fontSize = style['fontSize']
		_s.leading = style['fontSize']
		print _s
		print 'writing text',txt,x,y
		while _s.fontSize > 1.0:
			p = Paragraph(txt.strip(),_s)	
			aw,ah =  p.wrapOn(self.canvas,w-margin*2,h-margin*2)
			print aw,w-margin*2,ah,h-margin*2,_s.fontSize
			break
			if (aw > w-margin*2) or (ah > h-margin*2):
				_s.fontSize = _s.fontSize - 1
				_s.leading = _s.fontSize*1.9
			else:
				break
		p.drawOn(self.canvas,x+margin,y+margin)
		self.canvas.restoreState()
Пример #12
0
    def draw_value(self, x, y, value, width=120, height=40, size=7, bold=True):
        """
            Helper function to draw a centered text above position (x, y);
            allows the text to wrap if it would otherwise exceed the given
            width

            @param x: drawing position
            @param y: drawing position
            @param value: the text to render
            @param width: the maximum available width (points)
            @param height: the maximum available height (points)
            @param size: the font size (points)
            @param bold: use bold font

            @returns: the actual height of the text element drawn
        """

        styleSheet = getSampleStyleSheet()
        style = styleSheet["Normal"]
        style.fontName = BOLD if bold else NORMAL
        style.fontSize = size
        style.leading = size
        style.alignment = TA_CENTER

        para = Paragraph(value, style)
        aH = para.wrap(width, height)[1]

        while(aH > height and style.fontSize > 4):
            # Reduce font size to make fit
            style.fontSize -= 1
            style.leading = style.fontSize
            aH = para.wrap(width, height)[1]

        para.drawOn(self.canv, x - para.width / 2, y)
        return aH
Пример #13
0
    def _draw_textarea(self, canvas: Canvas, op: OrderPosition, order: Order, o: dict):
        font = o['fontfamily']
        if o['bold']:
            font += ' B'
        if o['italic']:
            font += ' I'

        align_map = {
            'left': TA_LEFT,
            'center': TA_CENTER,
            'right': TA_RIGHT
        }
        style = ParagraphStyle(
            name=uuid.uuid4().hex,
            fontName=font,
            fontSize=float(o['fontsize']),
            leading=float(o['fontsize']),
            autoLeading="max",
            textColor=Color(o['color'][0] / 255, o['color'][1] / 255, o['color'][2] / 255),
            alignment=align_map[o['align']]
        )
        text = re.sub(
            "<br[^>]*>", "<br/>",
            bleach.clean(
                self._get_text_content(op, order, o) or "",
                tags=["br"], attributes={}, styles=[], strip=True
            )
        )
        p = Paragraph(text, style=style)
        p.wrapOn(canvas, float(o['width']) * mm, 1000 * mm)
        # p_size = p.wrap(float(o['width']) * mm, 1000 * mm)
        ad = getAscentDescent(font, float(o['fontsize']))
        p.drawOn(canvas, float(o['left']) * mm, float(o['bottom']) * mm - ad[1])
Пример #14
0
    def render(self):
        style = getSampleStyleSheet()['Normal']
        style.alignment = self.text_align
        style.fontName = self.font_name
        if self._layout.debug_fields:
            style.backColor = "rgba(255, 0, 0, 0.5)"

        if self.fit_text:
            original_size = self.font_size
            text_width = stringWidth(self.data, self.font_name, self.font_size)
            while text_width > self.width:
                self.font_size -= 1
                text_width = stringWidth(self.data, self.font_name, self.font_size)
            # Size has been adjusted. Lower text accordingly
            if original_size > self.font_size:
                self._offset_top = (original_size - self.font_size) / 2.0

        if self.height == 0:
            self.height = self.font_size
        style.fontSize = self.font_size
        style.leading = self.font_size


        p = Paragraph('<font color="%s">%s</font>' % (self.color, self.data), style)
        p.wrap(self.width, self.height)
        top = self._layout.height - self.top - self.height - self._offset_top
        p.drawOn(self._canvas, self.left, top)
Пример #15
0
    def adicionais(self, oXML=None):
        el_infAdic = oXML.find(
            ".//{http://www.portalfiscal.inf.br/nfe}infAdic")

        self.nlin += 2
        self.canvas.setFont('NimbusSanL-Bold', 6)
        self.string(self.nLeft + 1, self.nlin + 1, 'DADOS ADICIONAIS')
        self.canvas.setFont('NimbusSanL-Regu', 5)
        self.string(self.nLeft + 1, self.nlin + 4,
                    'INFORMAÇÕES COMPLEMENTARES')
        self.string(
            ((self.width / 3)*2) + 1, self.nlin + 4, 'RESERVADO AO FISCO')
        self.rect(self.nLeft, self.nlin + 2,
                  self.width - self.nLeft - self.nRight, 42)
        self.vline((self.width / 3)*2, self.nlin + 2, 42)
        # Conteúdo campos
        styles = getSampleStyleSheet()
        styleN = styles['Normal']
        styleN.fontSize = 6
        styleN.fontName = 'NimbusSanL-Regu'
        styleN.leading = 7
        fisco = tagtext(oNode=el_infAdic, cTag='infAdFisco')
        observacoes = tagtext(oNode=el_infAdic, cTag='infCpl')
        if fisco:
            observacoes = fisco + ' ' + observacoes
        P = Paragraph(observacoes, styles['Normal'])
        w, h = P.wrap(128 * mm, 32 * mm)
        altura = (self.height - self.nlin - 5) * mm
        P.drawOn(self.canvas, (self.nLeft + 1) * mm, altura - h)
        self.nlin += 36
Пример #16
0
    def GetParagraphes(self, texte="", taille_police=None):
        style = ParagraphStyle(name="style", fontName=self.parent.dictDonnees["case_nom_police"], fontSize=taille_police,
                               spaceBefore=0, spaceafter=0, leftIndent=0, rightIndent=0, alignment=1, leading=taille_police,
                               textColor=ColorWxToPdf(self.parent.dictDonnees["case_texte_couleur"]))

        liste_paragraphes = []
        hauteur_paragraphes = 0
        for texte_paragraphe in texte.split("\n") :

            # Remplacement des légendes
            liste_legendes = REGEX_LEGENDES.findall(texte_paragraphe)
            for chaine in liste_legendes :
                IDlegende = int(chaine[1:-1])
                if self.parent.dictDonnees["legendes"].has_key(IDlegende) and self.parent.dictNumerosLegendes.has_key(IDlegende):
                    couleur = UTILS_Images.rgb_to_hex(self.parent.dictDonnees["legendes"][IDlegende]["couleur"])
                    if self.parent.dictDonnees["legende_type"] == "numero":
                        numero = self.parent.dictNumerosLegendes[IDlegende]
                        chaine_remplacement = u"<font color='%s' size='-2'><super>%d</super></font>" % (couleur, numero)
                    elif self.parent.dictDonnees["legende_type"] == "carre":
                        chaine_remplacement = u"<font face='ZapfDingbats' color='%s' size='-2'><super>X</super></font>" % couleur
                    else :
                        chaine_remplacement = ""

                else :
                    chaine_remplacement = u""
                texte_paragraphe = texte_paragraphe.replace(chaine, chaine_remplacement)

            # Création du paragraphe
            paragraphe = Paragraph(texte_paragraphe, style=style)
            largeur_paragraphe, hauteur_paragraphe = paragraphe.wrapOn(self.canvas, self.largeur_case, self.hauteur_case)
            hauteur_paragraphes += hauteur_paragraphe
            liste_paragraphes.append((hauteur_paragraphe, paragraphe))
        return liste_paragraphes, hauteur_paragraphes
Пример #17
0
def createParagraph(c, text, x, y):
    """"""
    style = getSampleStyleSheet()
    width, height = letter
    p = Paragraph(text, style=style["Normal"])
    p.wrapOn(c, width, height)
    p.drawOn(c, x, y, mm)
Пример #18
0
def footer(canvas, doc):
    canvas.saveState()
    P = Paragraph("This is a multi-line footer.  It goes on every page.  " * 5,
                  styleN)
    w, h = P.wrap(doc.width, doc.bottomMargin)
    P.drawOn(canvas, doc.leftMargin, h)
    canvas.restoreState()
Пример #19
0
def processPDFLine(canvas, type, text, lineno, page, font, width, height):

    text = re.sub("("+CHAR_BOLDITALUNDER+")([^/]+)(/"+CHAR_BOLDITALUNDER+")", r"<font name=CourierPrimeBI size=12><u>\2</u></font>", text)
    text = re.sub("("+CHAR_BOLDITAL+")([^/]+)(/"+CHAR_BOLDITAL+")", r"<font name=CourierPrimeBI size=12>\2</font>", text)
    text = re.sub("("+CHAR_BOLDUNDER+")([^/]+)(/"+CHAR_BOLDUNDER+")", r"<font name=CourierPrimeB size=12><u>\2</u></font>", text)
    text = re.sub("("+CHAR_ITALUNDER+")([^/]+)(/"+CHAR_ITALUNDER+")", r"<font name=CourierPrimeI size=12><u>\2</u></font>", text)
    text = re.sub("("+CHAR_BOLD+")([^/]+)(/"+CHAR_BOLD+")", r"<font name=CourierPrimeB size=12>\2</font>", text)
    text = re.sub("("+CHAR_ITAL+")([^/]+)(/"+CHAR_ITAL+")", r"<font name=CourierPrimeI size=12>\2</font>", text)
    text = re.sub("("+CHAR_UNDER+")([^/]+)(/"+CHAR_UNDER+")", r"<u>\2</u>", text)

    text = re.sub("("+CHAR_COMMENT+")([^/]+)(/"+CHAR_COMMENT+")", r"</para><para bg=#FAFAD2><u>\2</u></para><para>", text)

    elm = fparser.fromTypeTextToElm(type, text)
    marginLeft = leftMarginForElement(elm, page)
    marginRight = rightMarginForElement(elm, page)

    # Styling Additions
    if elm.elmType == "Scene Heading":
        text = "<font name=CourierPrimeB size=12>" + text + "</font>"
    if elm.elmType == "Lyrics":
        text = "<font name=CourierPrimeI size=12>" + text + "</font>"
    if elm.elmType == "Comment":
        text = "</para><para bg=#FAFAD2><u>" + text + "</u></para><para>"

    if elm.elmType == "Transition": # right align
        para = Paragraph(text, pstyleRight)
        para.wrapOn(canvas, width, pstyleRight.fontSize*font.heightEM)
        para.drawOn(canvas,-marginRight*inch, height - (lineno+1)*pstyle.fontSize*font.heightEM - page.marginTop*inch)
    else:
        para = Paragraph(text, pstyle)
        para.wrapOn(canvas, width, pstyle.fontSize*font.heightEM)
        para.drawOn(canvas, marginLeft*inch, height - (lineno+1)*pstyle.fontSize*font.heightEM - page.marginTop*inch)
Пример #20
0
def footer_building(canvas, doc, styles):
    printing_date = timezone.now()
    printing_date = printing_date.strftime("%d/%m/%Y")
    pageinfo = "%s : %s" % (_('Printing date'), printing_date)
    footer = Paragraph(''' <para align=right>Page %d - %s </para>''' % (doc.page, pageinfo), styles['Normal'])
    w, h = footer.wrap(doc.width, doc.bottomMargin)
    footer.drawOn(canvas, doc.leftMargin, h)
 def addQnPage(self,qdict):
   # init
   keys = qdict.keys()
   keys.sort()
   # iterate
   for k,i in zip(keys,range(len(keys))):
     # topleft coords
     x = int(i>3)
     y = i%4
     # generate chart
     data = [0,0,0,0,0]
     for i in qdict[k]:
       if i >= 1:
         data[i-1]+=1
     # sizing
     spacex = (letter[0]-inch)/2.
     spacey = (letter[1]-2*inch)/4.
     wid= spacex - 0.5*inch
     hgt= spacey - 0.5*inch
     px = 0.5*inch + x*spacex
     py = 1.4*inch + (3-y)*spacey
     qchart = DeptVBC(data,(0,0),(wid,hgt))
     qchart.drawOn(self.c,px,py)
     # label
     text = `k`+'. '+textdict[k]
     p = Paragraph(text,self.pstyle)
     p.wrapOn(self.c, wid,hgt)
     p.drawOn(self.c, px , py+hgt-10)
   # page break
   self.nextpage()
Пример #22
0
def Page_Setup(canvas, doc):

    canvas.saveState()

    canvas.setFillColor(doc.gs_background)
    canvas.rect(0,0,8.5*inch, 11*inch,fill=1)

    if canvas.getPageNumber() == 1:

      canvas.drawImage(doc.leftLogoFile,x=0.3*inch, y=8.7*inch,\
                       width=0.92*inch, mask='auto', preserveAspectRatio=True)

      canvas.drawImage(doc.rightLogoFile,x=7.3*inch, y=8.7*inch,\
                       width=0.92*inch, mask='auto', preserveAspectRatio=True)



    Normal_Style=ParagraphStyle('normal')
    Footer_Style = ParagraphStyle('my-footer-style', parent=Normal_Style,
      textColor=colors.white, backColor=colors.black, alignment=TA_CENTER,
      fontSize=6, leading=7,fontName='Courier',borderPadding=(0,0,5,0))
    P = Paragraph("The New Hampshire Liberty Alliance is a non-partisan coalition "
        "working to increase individual liberty, and encourage citizen "
        "involvement in the legislative process. Bills on the Gold Standard "
        "are evaluated based on their effects on, among other things; civil "
        "liberties, personal responsibility, property rights, "
        "accountability, constitutionality, and taxation. Roll call votes on "
        "Gold Standard bills are the foundation for our annual Liberty "
        "Rating report card.", Footer_Style)
    w,h = P.wrap(doc.width, doc.bottomMargin)
    P.drawOn(canvas, doc.leftMargin,3)
    canvas.restoreState()
Пример #23
0
    def __init__(self, *args, **kwargs):
        self.level = kwargs.get('level', 0)
        self.full_page = kwargs.get('full_page', False)
        self.key = kwargs.get('key', None)
        self.closed = kwargs.get('closed', False)

        Paragraph.__init__(self, *args)
def generate_pdf(story, existing_canvas=None):
    styleSheet = getSampleStyleSheet()
    style = styleSheet['BodyText']

    c = existing_canvas or canvas.Canvas(OUT_FILENAME, pagesize=A5)
    #c.setFont("Helvetica", 28)
    # draw some lines
    #a5 is 210 mm * 148 mm
    c.rect(1*cm, 1*cm, 12.8*cm, 19*cm, fill=0)

    c.rotate(90)
    style.fontSize = 24
    style.leading = 24
    story_points = "%s points" % story['Story points'] if story['Story points'] else 'Not estimated'
    title = Paragraph("%s [%s]" % (story['Subject'],story_points), style)

    title.wrap(17*cm, 4*cm)
    title.drawOn(c, 2*cm, -3.5*cm)

    # c.drawString(2*cm, -3*cm, "%s [%d points]" % (story['Subject'],
    #                                               int(float(story['Story points']))))

    style.fontSize = 14
    style.leading = 16
    description = Paragraph(story['Description'], style)
    description.wrap(14*cm, 15*cm)
    description.drawOn(c, 2*cm, -8*cm)
    c.showPage()
    return c
Пример #25
0
    def draw(self):
        self.canv.saveState()

        self.canv.rotate(self.rotation)
        self.canv.translate(-self.width / 2. - 100, -self.height)
        Paragraph.draw(self)
        self.canv.restoreState()
Пример #26
0
 def add_to_toc_and_return(self, text, sty):
     data = str(text + sty.name).encode()
     bn = sha1(data).hexdigest()
     h = Paragraph(text + '<a name="%s"/>' % bn, sty)
     # store the bookmark name on the flowable so afterFlowable can see this
     h._bookmarkName = bn
     return h
Пример #27
0
    def addParaWithThumb(self, text, pageY, style, thumbSrc=None):
        """ Adds paragraph text to point on PDF info page """

        c = self.figureCanvas
        aW = self.pageWidth - (inch * 2)
        maxH = self.pageHeight - inch
        spacer = 10
        imgw = imgh = 25
        # Some html from markdown may not be compatible
        # with adding to PDF.
        try:
            para = Paragraph(text, style)
        except ValueError:
            print "Couldn't add paragraph to PDF:"
            print text
            text = "[Failed to format paragraph - not shown]"
            para = Paragraph(text, style)
        w, h = para.wrap(aW, pageY)   # find required space
        if thumbSrc is not None:
            parah = max(h, imgh)
        else:
            parah = h
        # If there's not enough space, start a new page
        if parah > (pageY - inch):
            print "new page"
            c.save()
            pageY = maxH    # reset to top of new page
        indent = inch
        if thumbSrc is not None:
            c.drawImage(thumbSrc, inch, pageY - imgh, imgw, imgh)
            indent = indent + imgw + spacer
        para.drawOn(c, indent, pageY - h)
        return pageY - parah - spacer  # reduce the available height
 def do_attendee (attendee, annotation, c, x, y, framesize):
     link = attendee.value
     cn = attendee.params.get("CN")
     nameaddr = cn and cn[0]
     if nameaddr:
         realname, emailaddr = parseaddr(nameaddr.replace(",", "%2C"))
         if realname:
             text = realname.replace("%2C", ",")
         elif emailaddr:
             text = emailaddr
         else:
             text = nameaddr
     elif link:
         text = link                    
     text = htmlescape(text)
     if link:
         text = '<link href="' + link + '">' + text + '</link>'
     if annotation:
         text += ' <i>' + annotation + '</i>'
     p = Paragraph(text, ParagraphStyle("normal"))
     w, h = p.wrapOn(c, *framesize)
     y -= h
     p.drawOn(c, x, y)
     # y -= (0.1 * inch)
     return y
Пример #29
0
 def create_para(self, xmltext, current_w, current_h, offset_font_size=0):
     para_text = extract_text(xmltext)
     font_name = xmltext.get('font_family')
     if font_name is None:
         font_name = 'sans-serif'
     align = xmltext.get('text_align')
     if para_text.startswith('<center>'):
         align = 'center'
     if (align == 'left') or (align == 'start'):
         alignment = TA_LEFT
     elif align == 'center':
         alignment = TA_CENTER
     else:
         alignment = TA_RIGHT
     if xmltext.get('font_size') is None:
         font_size = 10.0 - offset_font_size
     else:
         font_size = float(xmltext.get('font_size')) - offset_font_size
     if xmltext.get('line_height') is None:
         line_height = 11
     else:
         line_height = int(xmltext.get('line_height'))
     style = ParagraphStyle(name='text', fontName=font_name, fontSize=font_size,
                            alignment=alignment, leading=line_height)
     # six.print_("%s:%s" % (xmltext.tag, para_text))
     text = Paragraph(para_text, style=style)
     _, new_current_h = text.wrapOn(self.pdf, current_w, current_h)
     return text, style, new_current_h
    def create_header(self):
        headerCanvas = Drawing()
        headerRect = Rect(0, 0, width=self.width, height=50)
        headerRect.fillColor = HexColor("#607D8B")
        headerRect.strokeColor = HexColor("#607D8B")
        headerCanvas.add(headerRect)
        renderPDF.draw(headerCanvas, self.c, 0, self.height - 50)

        _header_styles = ParagraphStyle(
            "Header",
            parent=self.styles["Heading1"],
            textColor=white,
            fontName='Helvetica'
        )
        p = Paragraph("Kit Trading Fund Report", style = _header_styles)

        p.wrapOn(self.c, self.width, self.height - 50)
        p.drawOn(self.c, *self.coord(75, 10, mm))

        _sub_header_styles = ParagraphStyle(
            "SubHeader",
            parent=self.styles["Heading4"],
            textColor=white,
            fontName='Helvetica'
        )
        p = Paragraph("Monthly Report: January 2016", style = _sub_header_styles)
        p.wrapOn(self.c, self.width, self.height - 50)
        p.drawOn(self.c, *self.coord(85, 16, mm))
Пример #31
0
    def generarPlanillaFamiliaX(self, parent, ruta_pdf):
	from reportlab.lib.pagesizes import A4
	from reportlab.lib.styles import getSampleStyleSheet,ParagraphStyle
	from reportlab.platypus import Spacer, SimpleDocTemplate, Table, TableStyle
	from reportlab.platypus import Paragraph, Image
	from reportlab.lib import colors
	
	
	print parent.ui.tableWidget.item(parent.ui.tableWidget.currentRow(), 1)
	print parent.ui.tableWidget.currentRow() 
	#print str(parent.ui.tableWidget.item(parent.ui.tableWidget.currentRow(), 1).text())
	#pdf_x_familia = QtGui.QFileDialog.getSaveFileName(self, "Guardar Planilla Komunal (*.pdf)", QtCore.QDir.homePath() + "/familia-" + str(parent.ui.tableWidget.item(parent.ui.tableWidget.currentRow(), 1).text()) + ".pdf", "Documento PDF (*.pdf)")
	pdf_x_familia = "Mejorando.pdf"
	styleSheet=getSampleStyleSheet()
	story=[]
	h1=styleSheet['Heading1']
	h1.pageBreakBefore=0
	h1.keepWithNext=1
	h1.backColor=colors.red
	h2=styleSheet['Heading2']
	h2.pageBreakBefore=0
	h2.keepWithNext=1
	
	img=Image("img/logo_pdf_barra.png",580,70)
	img.hAlign = "LEFT"
	
	texto_principal = ""
	estilo_texto = ParagraphStyle('',
		        fontSize = 22,
                        alignment = 0,
                        spaceBefore = 0,
                        spaceAfter = 0,
			#backColor = '#fff',
			textColor = '#999',
			leftIndent = 10 )

	otro_estilo= ParagraphStyle('',
	             fontSize = 20,
		     textColor = '#000',
		     leftIndent = 200,
		     rightIndent = 50) 

	style_barra= ParagraphStyle('',
		     fontSize = 13,
		     textColor = '#000',
		     backColor='#f5f5f5',
		     borderColor ='#a3a3a3',
		     borderWidth = 1,
		     borderPadding = (1, 2, 5))

	style_fecha= ParagraphStyle('',
		     fontSize = 11,
		     textColor = '#000',
		     leftIndent = 500,
		     rightIndent = 10)

	h = Paragraph( texto_principal, estilo_texto)
	banner = [ [ img , h ] ]
	
	ban = Table( banner, colWidths=300 )
	ban.setStyle([ ('ALIGN',(0,0),(0,0),'LEFT'),('ALIGN',(0,0),(1,0),'LEFT'), ('VALIGN',(0,0),(1,0),'TOP'),
			('TEXTCOLOR',(0,1),(0,-1), colors.blue) ])
	story.append(ban)
	story.append(Spacer(0,10))

	dia = time.localtime()
	mes = dia.tm_mon
	mes_sp = ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre','Octubre', 'Noviembre', 'Diciembre']
 
	hoy='%s %d' % (mes_sp[mes-1], dia.tm_year)
	P= Paragraph(hoy,style_fecha)
	story.append(P)
	story.append(Spacer(0,25))

	P= Paragraph("<b>Censo Socio-Economico</b> ",otro_estilo)
	story.append(P)
	story.append(Spacer(0,25))

	P=Paragraph("<b>Información General</b> ",style_barra)
	story.append(P)
	story.append(Spacer(0,25))


	style=styleSheet['BodyText']
	
	consejo = parent.dbconn.execute("select * from consejo_comunal where id_consejo=1").fetchone()
	
	data_consejo = [['Consejo Comnual: ', consejo[2] ],
			['Estado' ,'Municipio:' , 'Parroquia:', 'Sector: ' ],
			[ consejo[3], consejo[4] , consejo[5] , consejo[6]] ,
			['Dirección: ', consejo[7] ] ]
	c=Table(data_consejo, colWidths=148)
	c.setStyle([  ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
		      ('BOX', (0,0), (-1,-1), 0.25, colors.black), ('SPAN',(1,3),(3,3)), ('SPAN',(1,0),(-1,0))
		   ])	
	story.append(c)
	story.append(Spacer(0,15))	
	
	
	
	jefe = parent.dbconn.execute("SELECT *, (Date('now') -fecha_nacimiento) as edad FROM familia where id_grupo= 1 AND jefe_familia= 'S'").fetchone()

	PO = Paragraph('''<font size=12> <b> Jefe de Familia</b></font>''',styleSheet["BodyText"])
	print jefe
	sexoJefe = "Masculino" if jefe[6] == "M" else "Femenino"
	if (jefe[9]== '' or jefe[9]== 0):
	    ingreso = "N/P"
	else:
	    ingreso = jefe[9] + " Bs. "
	datos_jefe = [[ Paragraph('''<font size=12> <b> Jefe de Familia</b></font>''',styleSheet["BodyText"]) ],
		    ['Cedula: ', jefe[12]+jefe[4], 'Apellidos y Nombres: ' , str(jefe[2])+ ' ' + str(jefe[3]) , 'Sexo: ', sexoJefe ],
		    [ 'Lugar de Nacimiento: ',jefe[12] , 'Fecha Nacimiento: ', jefe[5], 'Edad: ', jefe[19] ],
		    ['Edo Civil: ',jefe[11], 'Ingreso Mensual: ', ingreso , 'Grado de Instrucción', jefe[10] ], 
		    ['Ocupación: ', jefe[8]] ]
	
	colwidths = (100, 90, 100, 90, 110, 100)
	j = Table( datos_jefe, colwidths )
	j.setStyle([ ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
	('BOX', (0,0), (-1,-1), 0.25, colors.black),('SPAN',(0,0),(5,0)) ])
	story.append(j)
	story.append(Spacer(0,15))



	#self.dbconn.execute("SELECT * FROM familia where id_grupo= " + str( self.ui.tableWidget.item(self.ui.tableWidget.currentRow(), 0).text() ) +" AND jefe_familia= 'N'")
	parent.dbconn.execute("SELECT *, (Date('now') -fecha_nacimiento) as edad FROM familia where id_grupo= 1 AND jefe_familia= 'N'")
	rs = parent.dbconn.fetchall()
	
	integrantes = [[Paragraph('''<font size=12> <b> Integrantes del grupo familiar</b></font>''',styleSheet["BodyText"])],
			['Cedula', 'Nombre/Apellido', 'Parentesco', 'Sexo', 'Edad', 'Edo Civil' , 'Instrucción', 'Ocupación','Ingreso']]
	for familia in rs:
	    	if (familia[9]== "" or familia[9]== "0"):
		    ingreso = "N/P"
		else:
		    ingreso = familia[9] + " Bs. "
		    
		integrantes.append([str(familia[4]), str(familia[2])+ " " + str(familia[3]), str(familia[7]), str(familia[6]), str(familia[19]),str(familia[11]), str(familia[10]), str(familia[8]), ingreso ])
	
	t=Table(integrantes, (55,150, 60, 35, 35, 50, 80, 80, 45))
		
	t.setStyle([ ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
	('BOX', (0,0), (-1,-1), 0.25, colors.black), ('SPAN',(0,0),(8,0))
	 ])
	
	story.append(t)
	story.append(Spacer(0,15))

	
	
	vivienda = parent.dbconn.execute("SELECT * FROM vivienda where id_grupo= 1").fetchone()

	datos_vivienda = [[ Paragraph('''<font size=12><b>Características de la vivienda</b></font>''',styleSheet["BodyText"]) ],
		    ['Tipo de Vivienda: ', vivienda[2], 'Estado de la Vivienda: ' , vivienda[3] , 'Tenencia: ', vivienda[4] ],
		    ['Material del Piso: ',vivienda[5] , 'Material de Paredes: ', vivienda[6] ],
		    ['Material Techo: ', vivienda[7],'Habitaciones: ',vivienda[8], 'Sala Comedor: ', vivienda[9] ], 
		    ['Baños', vivienda[10] , 'Cocina: ', vivienda[11], 'Uso de Vivienda: ', vivienda[12]],
		    ['Le gustaria Mejorar: ', vivienda[13]] ]
	
	v=Table(datos_vivienda, (100,100, 110, 100, 90, 90))
	v.setStyle([ ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
	('BOX', (0,0), (-1,-1), 0.25, colors.black),('SPAN',(0,0),(5,0)),('SPAN',(3,2),(5,2)),('SPAN',(1,5),(5,5))
	 ])
	story.append(v)
	story.append(Spacer(0,15))	
	

	salud = parent.dbconn.execute("SELECT * FROM salud_bienestar where id_familia = 1").fetchone()
	vacuna = "Si" if salud[2] == "S" else "No"
	datos_salud = [[ Paragraph('''<font size=12><b>Salud y Bienestar</b></font>''',styleSheet["BodyText"]) ],
		    ['Los Niños estan vacunados: '+ str(salud[2]), '', 'Solo menores de seis(6) años : ' + str(salud[3]),  '', 'Todos: ' + salud[4], '' ] ]
	
	datos_salud.append( ['De las siguientes vacunas cuales tiene la seguridad de haberles suministrado:' ])

	parent.dbconn.execute("SELECT desc_vacuna, id_salud FROM tipos_vacuna LEFT OUTER JOIN vacuna  ON tipos_vacuna.id_tipo_vacuna = vacuna.id_tipo_vacuna")
	rs = parent.dbconn.fetchall()
	a = 1
	i = 3
	fila = ""
	
	for vacuna in rs:
	    si_no = "X" if vacuna[1] else ""
	    fila = fila + vacuna[0] + ","+ si_no + ","
	    if (a == i ):
		i = i + 3
		fila = fila[0:-1].split(',')
		datos_salud.append(  fila )
		fila = ""
	    a = a + 1
	
	
	datos_salud.append( ['Algunos de los miembros de la familia a presentado problemas de:' ])

	parent.dbconn.execute("SELECT desc_enfermedad, id_salud FROM tipo_enfermedad LEFT OUTER JOIN enfermedad  ON tipo_enfermedad.id_tipo_enfermedad = enfermedad.id_tipo_enfermedad where activa='s'")
	rs = parent.dbconn.fetchall()
	a = 1
	i = 3
	fila = ""
	
	for enfermedad in rs:
	    si_no = "X" if enfermedad[1] else ""
	    fila = fila + enfermedad[0] + ","+ si_no + ","
	    if (a == i ):
		i = i + 3
		fila = fila[0:-1].split(',')
		datos_salud.append(  fila )
		fila = ""
	    a = a + 1
	
	v=Table(datos_salud, (120,90, 110, 90, 90, 90))
	v.setStyle([ ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),	('BOX', (0,0), (-1,-1), 0.25, colors.black),
	    ('SPAN',(0,0),(5,0)), ('SPAN',(0,1),(1,1)), ('SPAN',(2,1),(3,1)),('SPAN',(4,1),(5,1)), ('SPAN',(0,2),(5,2)),('SPAN',(0,6),(5,6)) ])


	story.append(v)
	story.append(Spacer(0,25))		


	
	servicios = parent.dbconn.execute("SELECT * FROM servicios_publicos where familia = 1").fetchone()

	serv_publicos = [[ Paragraph('''<font size=12><b>Servicios Publicos Existentes</b></font>''',styleSheet["BodyText"]) ],
		    ['Aguas Blancas: ', servicios[1], 'Aguas Servidas: ' , servicios[2] , 'Gas: ', servicios[3] ],
		    ['Sistema Electrico: ',servicios[4] , 'Recolección de Basura: ', servicios[5] ],
		    ['Otros Servicios: '],
		    ['Telefonía: ', servicios[6],'Transporte: ',servicios[7] ], 
		    ['Mecanismos de Información: ', '', servicios[8] ] ]
	
	s=Table(serv_publicos, (90,100, 115, 100, 90, 90))
	s.setStyle([ ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
	('BOX', (0,0), (-1,-1), 0.25, colors.black),('SPAN',(0,0),(5,0)),('SPAN',(0,3),(5,3)),('SPAN',(0,5),(1,5)) ,('SPAN',(2,5),(5,5)) ])
	story.append(s)
	story.append(Spacer(0,15))
	
	par_comunitaria = [[ Paragraph('''<font size=12><b>Participacion Comunitaria</b></font>''',styleSheet["BodyText"]) ],
		    ['Existe organización Comunitaria: ', servicios[9] ],
		    ['Participación del jefe de familia: ', servicios[13] ],
		    ['Participación de los miembros de familia: ', servicios[10] ] ]
	s=Table(par_comunitaria, (200, 385))
	s.setStyle([ ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black),
	('BOX', (0,0), (-1,-1), 0.25, colors.black),('SPAN',(0,0),(1,0)) ])
	story.append(s)
	story.append(Spacer(0,15))
	
	doc=SimpleDocTemplate(pdf_x_familia,pagesize=letter,leftMargin=10, rightMargin=10, topMargin=10, bottomMargin=10,
			      title="Komunal - Planilla Familiar", author= "Komunal Beta" )
	#doc.build(Document, onLaterPages=HeaderFooter) 
	doc.build( story )
Пример #32
0
    def create_header(self):
        """"""
        ptext = '<font size=10><b>Statement Date: {}' \
            '</b></font>'.format('01/01/2017')
        p = Paragraph(ptext, self.styles["Normal"])
        p.wrapOn(self.canvas, self.width, self.height)
        p.drawOn(self.canvas, *self.coord(145, 14, mm))

        ptext = '''<font size=10>
        <b>Member:</b> {member}<br/>
        <b>Member ID:</b> {member_id}<br/>
        <b>Group #:</b> {group_num}<br/>
        <b>Group name:</b> {group_name}<br/>
        </font>
        '''.format(member='MIKE D',
                   member_id='X123456',
                   group_num=789456 - 1235,
                   group_name='PYTHON CORP')
        p = Paragraph(ptext, self.styles["Normal"])
        p.wrapOn(self.canvas, self.width, self.height)
        p.drawOn(self.canvas, *self.coord(145, 35, mm))
Пример #33
0
    def draw_footer(self, y_pos):
        """
        Draws the footer.
        """

        para_style = getSampleStyleSheet()['Normal']
        para_style.fontSize = 8

        footer_para = Paragraph(self.footer_text.replace("\n", "<br/>"),
                                para_style)
        disclaimer_para = Paragraph(
            self.disclaimer_text.replace("\n", "<br/>"), para_style)
        billing_address_para = Paragraph(
            self.billing_address_text.replace("\n", "<br/>"), para_style)

        footer_data = [['', footer_para], [(_('Billing Address')), ''],
                       ['', billing_address_para], [(_('Disclaimer')), ''],
                       ['', disclaimer_para]]

        footer_style = [
            # Styling for the entire footer table.
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('TEXTCOLOR', (0, 0), (-1, -1), colors.black),
            ('FONTSIZE', (0, 0), (-1, -1), 9),
            ('TEXTCOLOR', (0, 0), (-1, -1), '#AAAAAA'),

            # Billing Address Header styling
            ('LEFTPADDING', (0, 1), (0, 1), 5 * mm),

            # Disclaimer Header styling
            ('LEFTPADDING', (0, 3), (0, 3), 5 * mm),
            ('TOPPADDING', (0, 3), (0, 3), 2 * mm),

            # Footer Body styling
            # ('BACKGROUND', (1, 0), (1, 0), '#EEEEEE'),

            # Billing Address Body styling
            ('BACKGROUND', (1, 2), (1, 2), '#EEEEEE'),

            # Disclaimer Body styling
            ('BACKGROUND', (1, 4), (1, 4), '#EEEEEE'),
        ]

        if self.is_invoice:
            terms_conditions_para = Paragraph(
                self.terms_conditions_text.replace("\n", "<br/>"), para_style)
            footer_data.append([(_('TERMS AND CONDITIONS')), ''])
            footer_data.append(['', terms_conditions_para])

            # TERMS AND CONDITIONS header styling
            footer_style.append(('LEFTPADDING', (0, 5), (0, 5), 5 * mm))
            footer_style.append(('TOPPADDING', (0, 5), (0, 5), 2 * mm))

            # TERMS AND CONDITIONS body styling
            footer_style.append(('BACKGROUND', (1, 6), (1, 6), '#EEEEEE'))

        footer_table = Table(footer_data, [5 * mm, 176 * mm])

        footer_table.setStyle(TableStyle(footer_style))
        __, rendered_height = footer_table.wrap(0, 0)

        if y_pos - (self.margin + self.min_clearance) <= rendered_height:
            self.prepare_new_page()

        footer_table.drawOn(self.pdf, self.margin, self.margin + 5 * mm)
    def getTable(self):
        styleSheet = getSampleStyleSheet()
        styNormal = styleSheet['Normal']
        styNormal.spaceBefore = 20
        styNormal.spaceAfter = 20
        styNormal.alignment = 0  #LEFT
        styNormal.fontSize = 9

        #self.unzip_rapporti_stratigrafici()

        individuo = Paragraph(
            "<b>Nr Individuo</b><br/>" + str(self.nr_individuo), styNormal)

        if self.area == None:
            area = Paragraph("<b>Area</b><br/>", styNormal)
        else:
            area = Paragraph("<b>Area</b><br/>" + str(self.area), styNormal)

        if str(self.us) == "None":
            us = Paragraph("<b>US</b><br/>", styNormal)
        else:
            us = Paragraph("<b>US</b><br/>" + str(self.us), styNormal)

        if self.eta_min == "None":
            eta_min = Paragraph("<b>Età min.</b><br/>", styNormal)
        else:
            eta_min = Paragraph("<b>Età min.</b><br/>" + str(self.eta_min),
                                styNormal)

        if self.eta_max == "None":
            eta_max = Paragraph("<b>Età max.</b><br/>", styNormal)
        else:
            eta_max = Paragraph("<b>Età max.</b><br/>" + str(self.eta_max),
                                styNormal)

        if self.classi_eta == None:
            classi_eta = Paragraph("<b>Classi età</b><br/>", styNormal)
        else:
            classi_eta = Paragraph(
                "<b>Classi età</b><br/>" + str(self.classi_eta), styNormal)

        data = [individuo, area, us, eta_min, eta_max, classi_eta]

        return data
Пример #35
0
style = TableStyle([
    #('BACKGROUND', (0,0), (3,0), colors.green),
    ('TEXTCOLOR', (0, 0), (-1, 0), colors.black),
    ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
    ('FONTNAME', (0, 0), (-1, 0), 'Courier'),
    ('FONTSIZE', (0, 0), (-1, 0), 12),
    ('BOTTOMPADDING', (0, 0), (-1, 0), 12),
    ('BACKGROUND', (0, 1), (-1, -1), colors.beige),
])
table.setStyle(style)

# 3) Add borders
ts = TableStyle([
    ('BOX', (0, 0), (-1, -1), 2, colors.black),

    #('LINEBEFORE',(2,1),(2,-1),2,colors.red),
    #('LINEABOVE',(0,2),(-1,2),2,colors.green),
    ('GRID', (0, 0), (-1, -1), 2, colors.black),
])
table.setStyle(ts)

P = Paragraph(
    "Table summarizing the comparison of LoD values between two BIP:" +
    str(version1) + " & BIP:" + str(version2), styleN)

elems = []
elems.append(P)
elems.append(table)

pdf.build(elems)
def generatepdf(sigsmatched, results, final, pdffile):
    doc = SimpleDocTemplate(pdffile)
    style_sheet = getSampleStyleSheet()

    flowables = []

    img = Image("cuckoo.png", width=180, height=60)
    img.hAlign = "RIGHT"

    paragraph_1 = Paragraph("Sample Report", style_sheet['Heading1'])

    style_sheet.add(
        ParagraphStyle(name='mystyle',
                       fontFamily='Helvetica-Bold',
                       fontSize=16,
                       textColor=colors.HexColor("#DE0909")))

    paragraph_2 = Paragraph(f"{sigsmatched} signatures were triggered",
                            style_sheet['mystyle'])

    flowables.append(img)
    flowables.append(paragraph_1)
    flowables.append(paragraph_2)

    i = 0
    sigcount = 1
    for arr in final:
        for f in arr:
            #if len(results) == sigcount and f == final[-1][3]:
            if i % 4 == 0 and f != "" or i == 0:
                if i != 0:
                    for k in results[currentsig]:
                        flowables.append(
                            Paragraph(f"{k} Events:", style_sheet['BodyText']))
                        eventkeys = list(results[currentsig][k].keys())
                        keycount = 1
                        evencount = 0
                        for a in results[currentsig][k]:
                            if evencount == len(results[currentsig][k][a]):
                                break
                            for j in results[currentsig][k][a]:
                                re = a + ": " + j
                                while keycount < len(eventkeys):
                                    re = re + ", " + eventkeys[
                                        keycount] + ": " + str(
                                            results[currentsig][k]
                                            [eventkeys[keycount]][evencount])
                                    keycount += 1
                                evencount += 1
                                keycount = 1
                                flowables.append(
                                    Paragraph(f"{re}", style_sheet['Code']))

                flowables.append(
                    Paragraph(f"{sigcount}. {f}", style_sheet['Heading2']))
                currentsig = f
                i += 1
                sigcount += 1
                continue
            if f == "":
                i += 1
                continue
            if f == "None":
                flowables.append(
                    Paragraph(f"The signature does not match any TTP Number",
                              style_sheet['BodyText']))
                i += 1
                continue
            else:
                rep = f.replace("\n", "")
                flowables.append(Paragraph(f"{rep}", style_sheet['BodyText']))
                i += 1
                if f == final[-1][3]:
                    f = final[-1][0]
                    flowables = last(f, results, flowables, style_sheet)

    doc.build(flowables)
Пример #37
0
            #if there are more than one item with the same name, we will look for the longest common string for the name
            if len(groupedPlanks[i]) > 1:
                for j in range(len(groupedPlanks[i])):
                    names.append(groupedPlanks[i][j][2])
                    plankName = longSubstr(names)
            else:
                plankName = groupedPlanks[i][0][2]

            if len(groupedPlanks[i]) > 8: #ammend font size if too many sizes per label
                fs = 7
            else:
                fs = 10

            pair.append([logo,Paragraph('''<para align=center><b> '''+plankName+'''</b><br></br>'''
                                    +'<br></br>'.join(['<b>'+groupedPlanks[i][x][1] +' ' + groupedPlanks[i][x][3] + ' $'
                                                       + groupedPlanks[i][x][4] + '/sqft</b>' for x in range(len(groupedPlanks[i]))])+'''</para> ''',
                                    ParagraphStyle(name='Normal',
                                                   fontName='Times-Roman',
                                                   fontSize=fs))])
            names = []
            if len(pair) % 2 == 0:
                data.append(pair)
                pair = []
            
            if groupedPlanks[i] == groupedPlanks[-1]:
                if len(pair) % 2 != 0:
                    pair.append([logo,Paragraph('''<para align=center><b> '''+'EMPTY'+'''</b><br></br>'''
                                                +'<br></br>'.join(['<b>'+'99"x99"'+'</b>   '+'99-999'+'   '+'<b>$'
                                                                    +"3.99"+'/sqft</b>' ])+'''</para> ''',
                                                ParagraphStyle(name='Normal',
                                                                fontName='Times-Roman',
                                                                fontSize=fs))])
Пример #38
0
    def create_pdf(self):
        body = []

        styles = getSampleStyleSheet()
        spacer1 = Spacer(0, 0.25 * inch)
        spacer2 = Spacer(0, 0.5 * inch)

        tblstyle = TableStyle([('INNERGRID', (0, 0), (-1, -1), 0.25,
                                colors.black),
                               ('BOX', (0, 0), (-1, -1), 0.5, colors.black),
                               ('LEFTPADDING', (0, 0), (-1, -1), 5),
                               ('RIGHTPADDING', (0, 0), (-1, -1), 5),
                               ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                               ('VALIGN', (0, 0), (-1, -1), 'MIDDLE')])

        for s in range(len(self.datatable)):
            if self.rptdata[s] is not None:
                if self.datatable[s].find("_") != -1:
                    title = (self.datatable[s].replace("_", " "))
                else:
                    title = (' '.join(
                        re.findall('([A-Z][a-z]*)', self.datatable[s])))

                # provide the table name for the page header
                ptext = '<font size=14>%s</font>' % title + self.ttl
                body.append(Paragraph(ptext, styles["Heading2"]))
                line = LineDrw(500)
                body.append(line)
                body.append(spacer2)

                for pg in range(0, len(self.rptdata[s]), 3):
                    n = 0
                    for i in self.columnames[s][0]:
                        # add the requirement process type and notes
                        ptxt = ("<b>{0}:</b>      {1}<br/>".format(
                            i, self.rptdata[s][pg][n]))
                        body.append(Paragraph(ptxt, styles["Normal"]))
                        body.append(spacer1)
                        n += 1
                    if self.datatable[s] == 'Piping':
                        txt = 'Pipe Material'
                    else:
                        txt = 'Tube Material'
                    ptext = '<font size=14>%s</font>' % txt
                    body.append(Paragraph(ptext, styles["Heading3"]))
                    line = LineDrw(100)
                    body.append(line)
                    body.append(spacer1)

                    # this populates the upper table
                    tbldata = []
                    tbldata.append(self.columnames[s][1])
                    rowdata = self.rptdata[s][pg + 1]

                    if rowdata != []:
                        for seg in rowdata:
                            m = 0
                            seg = list(seg)
                            for item in seg:
                                # wrap any text which is longer than
                                # 10 characters
                                if type(item) == str:
                                    if len(item) >= 10:
                                        item = Paragraph(
                                            item, styles['Normal'])
                                        seg[m] = item
                                m += 1
                            tbldata.append(tuple(seg))

                            colwdth1 = []
                            for i in self.colms[s][1]:
                                colwdth1.append(i * self.textAdjust)

                        tbl1 = Table(tbldata, colWidths=colwdth1)

                        tbl1.setStyle(tblstyle)
                        body.append(tbl1)
                        body.append(spacer2)

                    if self.datatable[s] == 'Piping':
                        txt = 'Pipe Nipples'
                    else:
                        txt = 'Tube Valves'
                    ptext = '<font size=14>%s</font>' % txt
                    body.append(Paragraph(ptext, styles["Heading3"]))
                    line = LineDrw(100)
                    body.append(line)
                    body.append(spacer1)

                    # this populates the lower table
                    tbldata = []
                    tbldata.append(self.columnames[s][2])
                    rowdata = self.rptdata[s][pg + 2]

                    if rowdata != []:
                        for seg in rowdata:
                            if seg is None:
                                continue
                            m = 0
                            seg = list(seg)
                            for item in seg:
                                # wrap any text which is longer than
                                # 10 characters
                                if type(item) == str:
                                    if len(item) >= 10:
                                        item = Paragraph(
                                            item, styles['Normal'])
                                        seg[m] = item
                                m += 1
                            tbldata.append(tuple(seg))

                            colwdth1 = []
                            for i in self.colms[s][2]:
                                colwdth1.append(i * self.textAdjust)

                        tbl1 = Table(tbldata, colWidths=colwdth1)

                        tbl1.setStyle(tblstyle)
                        body.append(tbl1)

                    body.append(PageBreak())
                w, h = tbl1.wrap(15, 15)
            else:
                if self.datatable[s].find("_") != -1:
                    title = (self.datatable[s].replace("_", " "))
                else:
                    title = (' '.join(
                        re.findall('([A-Z][a-z]*)', self.datatable[s])))

                # provide the table name for the page header
                ptext = '<font size=14>%s</font>' % title + self.ttl
                body.append(Paragraph(ptext, styles["Heading2"]))
                line = LineDrw(500)
                body.append(line)

                txt = 'Not Data Set Up for this Item'
                ptext = '<font size=12>%s</font>' % txt
                body.append(Paragraph(ptext, styles["Heading2"]))

        doc = SimpleDocTemplate('tmp_rot_file.pdf',
                                pagesize=landscape(letter),
                                rightMargin=.5 * inch,
                                leftMargin=.5 * inch,
                                topMargin=.75 * inch,
                                bottomMargin=.5 * inch)

        doc.build(body)

        pdf_old = open('tmp_rot_file.pdf', 'rb')
        pdf_reader = PyPDF4.PdfFileReader(pdf_old)
        pdf_writer = PyPDF4.PdfFileWriter()

        for pagenum in range(pdf_reader.numPages):
            page = pdf_reader.getPage(pagenum)
            page.rotateCounterClockwise(90)
            pdf_writer.addPage(page)

        pdf_out = open(self.filename, 'wb')
        pdf_writer.write(pdf_out)
        pdf_out.close()
        pdf_old.close()
        os.remove('tmp_rot_file.pdf')
Пример #39
0
def ver_reporte_input_fechas(request, id):
	docente = get_object_or_404(Docente, user_ptr=request.user)
	asignatura = get_object_or_404(Asignatura, codigo=id)
	periodo = get_object_or_404(Periodo, estado=True)
	asignaturas = DocenteAsignaturaPeriodo.objects.filter(asignatura=asignatura, periodo=periodo, docente=docente)

	estiloHoja = getSampleStyleSheet()
	cabecera = estiloHoja['Heading4']
	cabecera.pageBreakBefore = 0
	cabecera.keepWithNext = 0
	story = []
	estilo = estiloHoja['BodyText']
	fichero_imagen = "elviajedelnavegante_png.png"
	imagen_logo = Image("logo.png", width=400, height=100)
	story.append(imagen_logo)
	story.append(Spacer(0, 10))
	parrafo = Paragraph("Docente: " + docente.get_full_name() + " - " + docente.cedula, estilo)
	story.append(parrafo)
	story.append(Spacer(0, 10))

	estilo = estiloHoja['BodyText']
	# asigestudiante = DocenteAsignaturaPeriodoEstudiante.objects.filter(docenteasignatura__in=asigperiodo, estudiante = estudiante)
	#horario = Horario.objects.filter(asignatura__in=asigperiodo)
	if request.method == 'POST':
		form = FechasReporte(request.POST)
		if form.is_valid():
			inicio = form['inicio'].value()
			fin = form['fin'].value()
			for i in asignaturas:
				datos = []

				horario = Horario.objects.filter(asignatura=i)
				temas = Tema.objects.filter(horario__in=horario, fecha__range=(inicio, fin))
				if temas.exists():
					parrafo = Paragraph(i.asignatura.descripcion, cabecera)
					fila_inicial = ['Tema', 'Fecha', 'Hora', 'Estado']
					story.append(parrafo)
					datos.append(fila_inicial)

					for t in temas:
						fila = [t.nombre, t.fecha, t.horario.get_inicio_display(), t.get_estado_display()]
						datos.append(fila)
					tabla = Table(datos)
					tabla.normalizeData(datos)
					tabla.setStyle([('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black)])
					tabla.setStyle([('BOX', (0, 0), (-1, -1), 0.25, colors.black)])

					story.append(tabla)
					story.append(Spacer(0, 20))
			ahora = time.strftime("%x %X")
			parrafo = Paragraph("Generado por: " + docente.get_full_name(), cabecera)
			story.append(parrafo)
			story.append(Spacer(0, 10))
			parrafo = Paragraph(ahora, cabecera)
			story.append(parrafo)
			doc = SimpleDocTemplate(docente.cedula + "-"+asignatura.codigo+".pdf", pagesize=landscape(A4), showBoundary=0)
			doc.build(story)
			output = open(docente.cedula + "-"+asignatura.codigo+".pdf")
			response = HttpResponse(output, content_type='application/pdf')
			response['Content-Disposition'] = 'attachment; filename=' +docente.cedula + "-"+asignatura.codigo+".pdf"
			return response
	else:
		form = FechasReporte()
	return render(request, 'estudiante/form_reporte.html', {'form': form}, context_instance=RequestContext(request))
    def create_sheet(self):
        styleSheet = getSampleStyleSheet()
        styNormal = styleSheet['Normal']
        styNormal.spaceBefore = 20
        styNormal.spaceAfter = 20
        styNormal.alignment = 0  #LEFT

        styleSheet = getSampleStyleSheet()
        styDescrizione = styleSheet['Normal']
        styDescrizione.spaceBefore = 20
        styDescrizione.spaceAfter = 20
        styDescrizione.alignment = 4  #Justified
        """
		#format labels
		self.id_scheda_ind = data[0]
		self.sito = data[1]
		self.area = data[2]
		self.us = data[3]
		self.nr_individuo = data[4]
		self.data_schedatura = data[5]
		self.schedatore = data[6]
		self.sesso = data[7]
		self.eta_min = data[8]
		self.eta_max =  data[9]
		self.classi_eta = data[10]
		self.osservazioni = data[11]
		"""
        #0 row
        intestazione = Paragraph(
            "<b>SCHEDA INDIVIDUI<br/>" + unicode(self.datestrfdate()) + "</b>",
            styNormal)
        #intestazione2 = Paragraph("<b>pyArchInit</b>", styNormal)

        if os.name == 'posix':
            home = os.environ['HOME']
        elif os.name == 'nt':
            home = os.environ['HOMEPATH']

        home_DB_path = ('%s%s%s') % (home, os.sep, 'pyarchinit_DB_folder')
        logo_path = ('%s%s%s') % (home_DB_path, os.sep, 'logo.jpg')
        logo = Image(logo_path)

        ##		if test_image.drawWidth < 800:

        logo.drawHeight = 1.5 * inch * logo.drawHeight / logo.drawWidth
        logo.drawWidth = 1.5 * inch

        #1 row
        sito = Paragraph("<b>Sito</b><br/>" + unicode(self.sito), styNormal)
        area = Paragraph("<b>Area</b><br/>" + unicode(self.area), styNormal)
        us = Paragraph("<b>US</b><br/>" + unicode(self.us), styNormal)
        nr_inventario = Paragraph(
            "<b>Nr. Individuo</b><br/>" + unicode(self.nr_individuo),
            styNormal)

        #2 row
        sesso = Paragraph("<b>Sesso</b><br/>" + self.sesso, styNormal)

        if str(self.eta_min) == "None":
            eta_min = Paragraph("<b>Eta' Minima</b><br/>", styNormal)
        else:
            eta_min = Paragraph(
                "<b>Eta' Minima</b><br/>" + unicode(self.eta_min), styNormal)

        if str(self.eta_max) == "None":
            eta_max = Paragraph("<b>Eta' massima</b><br/>", styNormal)
        else:
            eta_max = Paragraph(
                "<b>Eta' massima</b><br/>" + unicode(self.eta_max), styNormal)

        #3 row
        classi_eta_string = unicode(self.classi_eta).replace("<", "&lt;")
        #classi_eta = Paragraph(classi_eta_string, styNormal)
        classi_eta = Paragraph(
            "<b>Classi di eta'</b><br/>" + classi_eta_string, styNormal)

        #4 row
        osservazioni = ''
        try:
            osservazioni = Paragraph(
                "<b>Osservazioni</b><br/>" + str(self.osservazioni),
                styDescrizione)
        except:
            pass

        #12 row
        data_schedatura = Paragraph(
            "<b>Data schedatura</b><br/>" + self.data_schedatura, styNormal)
        schedatore = Paragraph("<b>Schedatore</b><br/>" + self.schedatore,
                               styNormal)

        #schema
        cell_schema = [  #00, 01, 02, 03, 04, 05, 06, 07, 08, 09 rows
            [
                intestazione, '01', '02', '03', '04', '05', '06', logo, '08',
                '09'
            ],
            [
                sito, '01', '02', area, '04', us, '06', '07', nr_inventario,
                '09'
            ],  #1 row ok
            [
                sesso, '01', '02', eta_min, '04', '05', eta_max, '07', '08',
                '09'
            ],  #2 row ok
            [classi_eta, '01', '02', '03', '04', '05', '06', '07', '08',
             '09'],  #3 row ok
            [
                osservazioni, '01', '02', '03', '04', '05', '06', '07', '08',
                '09'
            ],  #4 row ok
            [
                data_schedatura, '01', '02', '03', '04', '05', schedatore,
                '07', '08', '09'
            ]  #5 row ok
            #['https://sites.google.com/site/pyarchinit/', '01', '02', '03', '04','05', '06', '07','08', '09'] #6 row
        ]

        #table style
        table_style = [
            ('GRID', (0, 0), (-1, -1), 0.5, colors.black),
            #0 row
            ('SPAN', (0, 0), (6, 0)),  #intestazione
            ('SPAN', (7, 0), (9, 0)),  #intestazione2

            #1 row
            ('SPAN', (0, 1), (2, 1)),  #sito
            ('SPAN', (3, 1), (4, 1)),  #area
            ('SPAN', (5, 1), (7, 1)),  #us
            ('SPAN', (8, 1), (9, 1)),  #nr_inventario

            #2 row
            ('SPAN', (0, 2), (2, 2)),  #sesso
            ('SPAN', (3, 2), (5, 2)),  #eta_min
            ('SPAN', (6, 2), (9, 2)),  #eta_max
            ('VALIGN', (0, 2), (9, 2), 'TOP'),

            #3 row
            ('SPAN', (0, 3), (9, 3)),  #classi_eta

            #4 row
            ('SPAN', (0, 4), (9, 4)),  #osservazioni

            #5 row
            ('SPAN', (0, 5), (5, 5)),  #data_schedatura
            ('SPAN', (6, 5), (9, 5)),  #schedatore
            ('VALIGN', (0, 0), (-1, -1), 'TOP')
        ]

        t = Table(cell_schema,
                  colWidths=50,
                  rowHeights=None,
                  style=table_style)

        return t
Пример #41
0
    def pdf(self, formatted_time, tc, name, result):
        from reportlab.lib.enums import TA_JUSTIFY
        from reportlab.lib.pagesizes import letter
        from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image
        from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
        from reportlab.lib.units import inch
        from reportlab.pdfbase import pdfmetrics
        from reportlab.pdfbase.ttfonts import TTFont

        pdfmetrics.registerFont(TTFont('TNR', 'times.ttf'))

        doc = SimpleDocTemplate("sonuc.pdf",
                                pagesize=letter,
                                rightMargin=72,
                                leftMargin=72,
                                topMargin=72,
                                bottomMargin=18)

        metin = []
        logo = "logo.jpg"

        im = Image(logo, width=80, height=80)
        metin.append(im)
        metin.append(Spacer(1, 30))

        styles = getSampleStyleSheet()
        styles.add(
            ParagraphStyle(name='Justify',
                           alignment=TA_JUSTIFY,
                           fontName="TNR"))
        ptext = '<font size="20">Göğüs Kanseri Testi Sonuç Belgesi</font>'
        metin.append(Paragraph(ptext, styles["Justify"]))
        metin.append(Spacer(1, 30))

        ptext = '<font size="14"> Sonuç Tarihi: %s</font>' % formatted_time
        metin.append(Paragraph(ptext, styles["Justify"]))
        metin.append(Spacer(1, 12))

        new_tc = tc[:2] + '*******' + tc[9:]
        ptext = '<font size="14">T.C Kimlik NO: %s</font>' % new_tc
        metin.append(Paragraph(ptext, styles["Justify"]))
        metin.append(Spacer(1, 12))
        ptext = '<font size="14">Adı-Soyadı: %s</font>' % name
        metin.append(Paragraph(ptext, styles["Justify"]))

        metin.append(Spacer(1, 25))
        ptext = '<font size="14">Sayın %s:</font>' % name
        metin.append(Paragraph(ptext, styles["Justify"]))
        metin.append(Spacer(1, 12))

        if result == 0:
            rslt = '<b>iyi huylu</b>'
        else:
            rslt = '<b>kötü huylu</b>'

        ptext = '<font size="14">Hastanemizde yaptırmış olduğunuz testlerin sonucunda Göğüs Kanseri Testiniz %s \
                çıkmıştır.</font>' % (rslt)

        metin.append(Paragraph(ptext, styles["Justify"]))
        metin.append(Spacer(1, 12))

        ptext = '<font size="14">Bizi tercih ettiğiniz için teşekkür ederiz.</font>'
        metin.append(Paragraph(ptext, styles["Justify"]))
        metin.append(Spacer(1, 12))
        ptext = '<font size="14">Görüşmek dileğiyle,</font>'
        metin.append(Paragraph(ptext, styles["Justify"]))
        metin.append(Spacer(1, 48))
        ptext = '<font size="14">Nazilli Devlet Hastanesi</font>'
        metin.append(Paragraph(ptext, styles["Justify"]))
        metin.append(Spacer(1, 12))
        doc.build(metin)
Пример #42
0
    def __init__(self,
                 filename,
                 titulo,
                 opciones,
                 datos,
                 tipo,
                 total=False,
                 tabla=None,
                 **kw):
        super(PdfReport, self).__init__(filename, pagesize=letter, **kw)

        # Estilos
        style = getSampleStyleSheet()

        # Titulo
        header = Paragraph(titulo, style['Title'])

        # Opciones
        _opciones = ''
        xml_b = '<b>%(title)s:</b> %(value)s<br />'

        for title, value in opciones.items():
            _opciones += xml_b % {
                'title': self.__class__.get_string_options(title),
                'value': value
            }

        opciones_paragraph = Paragraph(_opciones, style['Normal'])

        if tabla is not None:
            f = 7
        else:
            tabla = datos
            f = 10

        table = Table(tabla)

        table_style = [('BACKGROUND', (0, 0), (-1, 0), colors.orange),
                       ('ALIGN', (1, 1), (-1, -1), 'CENTER'),
                       ('FONTSIZE', (0, 0), (-1, -1), f),
                       ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                       ('BOX', (0, 0), (-1, -1), 0.25, colors.black)]

        if total:
            table_style.append(
                ('BACKGROUND', (0, -1), (-1, -1), colors.orange))
        table.setStyle(TableStyle(table_style))

        # Graficos
        sw = True
        if total:
            datos.pop()
        other_labels = datos.pop(0)
        other_labels.pop(0)
        chart_datos = list(zip(*datos))
        labels = list(chart_datos.pop(0))
        if tipo == 1:  # Pie chart
            data = list(chart_datos.pop())
            if sum(data) != 0:
                chart = PieChart(data=data, labels=labels, legends=labels)
            else:
                sw = False
        elif tipo == 2:  # Bar chart
            data = chart_datos
            chart = BarChart(data=data, labels=labels, legends=other_labels)
        else:  # Line chart
            data = chart_datos
            chart = LineChart(data=data, labels=labels, legends=other_labels)

        # Agregar al pdf
        catalog = []
        catalog.append(header)
        catalog.append(Spacer(1, 50))
        catalog.append(opciones_paragraph)
        catalog.append(Spacer(1, 50))
        catalog.append(table)
        catalog.append(Spacer(1, 60))
        if sw:
            catalog.append(chart)

        self.build(catalog)
Пример #43
0
def build_flowables(stylesheet):
    return [
        # cover page
        Paragraph(version_number, stylesheet['version_number']),
        Paragraph(str(date_of_generation), stylesheet['version_number']),
        im,
        Paragraph("Game Design Document", stylesheet['gdd']),
        Paragraph(name_of_project, stylesheet['project_name']),
        PageBreak(),
        # index page
        Paragraph("Index", stylesheet['heading']),
        PageBreak(),
        #Game overview
        Paragraph("Game Overview",  stylesheet['heading']),
        Paragraph("Title: " + name_of_project, stylesheet['default']),
        Paragraph("Platform: " + selected_platform, stylesheet['default']),
        Paragraph("Genre: " + selected_genre, stylesheet['default']),
        Paragraph("Targeted age: " + selected_age_target, stylesheet['default']),
        Paragraph("Initial Release Date: " + str(initial_release_date), stylesheet['default']),
        Paragraph("Publisher: " + publisher, stylesheet['default']),
        Paragraph("Quick Review: " + quick_overview, stylesheet['default']),
        #high concept
        Paragraph("High Concept", stylesheet['heading']),
        Paragraph(high_concept, stylesheet['default']),
        #Unique sellign points
        Paragraph("Unique Selling Points", stylesheet['heading']),
        Paragraph(unique_selling_points, stylesheet['default']),
        #platform requirements according to selected
        Paragraph("Platform Minimum Requirements", stylesheet['heading']),
        Paragraph(selected_platform, stylesheet['default']),
        Paragraph(selected_device_detail, stylesheet['default']),
        #competence title
        Paragraph("Competence Title", stylesheet['heading']),
        Paragraph(name_of_project + "By " + publisher, stylesheet['default']),
        #Game objective
        Paragraph("Game Objective", stylesheet['heading']),
        Paragraph("About the game", stylesheet['default']),
        #Game rules
        Paragraph("Game Rules", stylesheet['heading']),
        Paragraph("Here Goes all the Rules", stylesheet['default']),
        #Gameplay
        Paragraph("Gameplay", stylesheet['heading']),
        Paragraph("According to selection of platfrom and gameplay type next will go image", stylesheet['default']),
        #Player NPC
        Paragraph("Player and NPC", stylesheet['heading']),
        Paragraph("All the Player and NPC Type", stylesheet['default']),
        #Concept art and mock
        Paragraph("Concept Art", stylesheet['heading']),
        Paragraph("Image 1, 2, 3, 4, 5 for iteration of every picture", stylesheet['default']),
        #Wish list
        Paragraph("Wish List", stylesheet['heading']),
        Paragraph("hear will go a list of wishes or re iteration", stylesheet['default']),
        # Barcode
        sep_line,
        headlines,
        barcode,




    ]
Пример #44
0
    def draw_course_info(self, y_pos):
        """
        Draws the main table containing the data items.
        """
        course_items_data = [[
            '', (_('Description')), (_('Quantity')),
            (_('List Price\nper item')), (_('Discount\nper item')),
            (_('Amount')), ''
        ]]
        for row_item in self.items_data:
            course_items_data.append([
                '',
                Paragraph(row_item['item_description'],
                          getSampleStyleSheet()['Normal']),
                row_item['quantity'], '{currency}{list_price:.2f}'.format(
                    list_price=row_item['list_price'],
                    currency=self.currency), '{currency}{discount:.2f}'.format(
                        discount=row_item['discount'], currency=self.currency),
                '{currency}{item_total:.2f}'.format(
                    item_total=row_item['item_total'],
                    currency=self.currency), ''
            ])

        padding_width = 7 * mm
        desc_col_width = 60 * mm
        qty_col_width = 26 * mm
        list_price_col_width = 21 * mm
        discount_col_width = 21 * mm
        amount_col_width = 40 * mm
        course_items_table = Table(course_items_data, [
            padding_width, desc_col_width, qty_col_width, list_price_col_width,
            discount_col_width, amount_col_width, padding_width
        ],
                                   splitByRow=1,
                                   repeatRows=1)

        course_items_table.setStyle(
            TableStyle([
                #List Price, Discount, Amount data items
                ('ALIGN', (3, 1), (5, -1), 'RIGHT'),

                # Amount header
                ('ALIGN', (5, 0), (5, 0), 'RIGHT'),

                # Amount column (header + data items)
                ('RIGHTPADDING', (5, 0), (5, -1), 7 * mm),

                # Quantity, List Price, Discount header
                ('ALIGN', (2, 0), (4, 0), 'CENTER'),

                # Description header
                ('ALIGN', (1, 0), (1, -1), 'LEFT'),

                # Quantity data items
                ('ALIGN', (2, 1), (2, -1), 'CENTER'),

                # Lines below the header and at the end of the table.
                ('LINEBELOW', (0, 0), (-1, 0), 1.00, '#cccccc'),
                ('LINEBELOW', (0, -1), (-1, -1), 1.00, '#cccccc'),

                # Innergrid around the data rows.
                ('INNERGRID', (1, 1), (-2, -1), 0.50, '#cccccc'),

                # Entire table
                ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                ('TOPPADDING', (0, 0), (-1, -1), 2 * mm),
                ('BOTTOMPADDING', (0, 0), (-1, -1), 2 * mm),
                ('TEXTCOLOR', (0, 0), (-1, -1), colors.black),
            ]))
        rendered_width, rendered_height = course_items_table.wrap(0, 0)
        table_left_padding = (self.page_width - rendered_width) / 2

        split_tables = course_items_table.split(
            0, self.first_page_available_height)
        if len(split_tables) > 1:
            # The entire Table won't fit in the available space and requires splitting.
            # Draw the part that can fit, start a new page
            # and repeat the process with the rest of the table.
            split_table = split_tables[0]
            __, rendered_height = split_table.wrap(0, 0)
            split_table.drawOn(self.pdf, table_left_padding,
                               y_pos - rendered_height)

            self.prepare_new_page()
            split_tables = split_tables[1].split(
                0, self.second_page_available_height)
            while len(split_tables) > 1:
                split_table = split_tables[0]
                __, rendered_height = split_table.wrap(0, 0)
                split_table.drawOn(
                    self.pdf, table_left_padding,
                    self.second_page_start_y_pos - rendered_height)

                self.prepare_new_page()
                split_tables = split_tables[1].split(
                    0, self.second_page_available_height)
            split_table = split_tables[0]
            __, rendered_height = split_table.wrap(0, 0)
            split_table.drawOn(self.pdf, table_left_padding,
                               self.second_page_start_y_pos - rendered_height)
        else:
            # Table will fit without the need for splitting.
            course_items_table.drawOn(self.pdf, table_left_padding,
                                      y_pos - rendered_height)

        if not self.is_on_first_page():
            y_pos = self.second_page_start_y_pos

        return y_pos - rendered_height - self.min_clearance
Пример #45
0
 def create_title(self):
     self.layout.append(Spacer(0, 15))
     self.layout.append(Paragraph(self.title, self.style['Title']))
Пример #46
0
    def generate_report(self):

        print('Writing report PDF {}...'.format(self.outfile))

        report = BaseDocTemplate(self.outfile,
                                 pagesize=letter,
                                 leftMargin=inch / 2,
                                 rightMargin=inch / 2,
                                 topMargin=inch,
                                 bottomMargin=inch)
        frame = Frame(report.leftMargin, report.bottomMargin, report.width,
                      report.height - inch * 0.3)
        report.addPageTemplates([
            PageTemplate(id='normal', frames=frame, onPage=self.__page_header)
        ])

        el = []

        ht = Table(self.heading_table, hAlign='LEFT')
        ht.setStyle(
            TableStyle([('FONTNAME', (0, 0), (0, -1), 'Helvetica-Bold')]))

        ht2 = Table(self.heading_table_2, hAlign='RIGHT')
        ht2.setStyle(
            TableStyle([('FONTNAME', (0, 0), (0, -1), 'Helvetica-Bold')]))

        ht_w = 3.75 * inch
        ht2_w = 4 * inch

        data = [[ht, ht2]]
        data_table = Table(data, colWidths=[ht_w, ht2_w])
        el.append(data_table)

        el.append(Spacer(1, 0.2 * inch))

        el.append(Paragraph("FAILED REPORT:", self.no_genomic_findings))
        el.append(
            Paragraph("{}".format(self.sample_record['PathologyNotes']),
                      self.no_genomic_findings))
        el.append(Spacer(1, 0.2 * inch))

        for text in self.static_text['tiers']:
            el.append(Paragraph(text, self.tier_text_style))

        el.append(self.standard_spacer)

        el.append(Paragraph(self.static_text['method'], self.text_block_style))
        el.append(Spacer(1, 0.2 * inch))

        el.append(
            Paragraph(self.static_text['technical assessment'],
                      self.text_block_style))
        el.append(Spacer(1, 0.2 * inch))

        el.append(
            Paragraph(self.static_text['disclaimer'], self.text_block_style))

        el.append(self.standard_spacer)

        hotspot_1 = [(Paragraph(self.static_text['hotspot_1'],
                                self.text_block_style))]
        hotspot_2 = [(Paragraph(self.static_text['hotspot_2'],
                                self.text_block_style))]
        hotspot_3 = [(Paragraph(self.static_text['hotspot_3'],
                                self.text_block_style))]

        cds = [(Paragraph(self.static_text['cds'], self.text_block_style))]

        cnv_1 = [(Paragraph(self.static_text['cnv_1'], self.text_block_style))]
        cnv_2 = [(Paragraph(self.static_text['cnv_2'], self.text_block_style))]

        fusion = [(Paragraph(self.static_text['fusion'],
                             self.text_block_style))]

        gene_list = [[
            hotspot_1, hotspot_2, hotspot_3, cds, cnv_1, cnv_2, fusion
        ]]

        gene_list_table = Table(gene_list)
        el.append(gene_list_table)

        report.build(el)
Пример #47
0
 def create_sub_title(self):
     self.layout.append(Paragraph(self.sub_title, self.style['sub_title']))
Пример #48
0
    def __init__(self,
                 filename,
                 titulo,
                 opciones,
                 datos,
                 tipo,
                 total=False,
                 tabla=None,
                 **kw):
        SimpleDocTemplate.__init__(self, filename, pagesize=letter, **kw)

        # Estilos
        style = getSampleStyleSheet()

        # Titulo
        header = Paragraph(titulo, style['Title'])

        # Opciones
        op = ''
        if 'fi' in opciones:
            op = op + '<b>Fecha Inicial:</b> %s<br />' % opciones['fi']
        if 'ff' in opciones:
            op = op + '<b>Fecha Final:</b> %s<br />' % opciones['ff']
        if 'g' in opciones:
            op = op + '<b>Grupo:</b> %s<br />' % opciones['g']
        if 'gi' in opciones:
            op = op + '<b>Grupo Inicial:</b> %s<br />' % opciones['gi']
        if 'gf' in opciones:
            op = op + '<b>Grupo Final:</b> %s<br />' % opciones['gf']
        if 'opt' in opciones:
            op = op + '<b>Opcion:</b> %s<br />' % opciones['opt']
        if 'ano' in opciones:
            op = op + '<b>Año:</b> %s<br />' % opciones['ano']
        if 'red' in opciones:
            op = op + '<b>Red:</b> %s<br />' % opciones['red']
        if 'predica' in opciones:
            op = op + '<b>Predica:</b> %s<br />' % opciones['predica']
        if 'total_grupos' in opciones:
            op = op + '<b>Total de grupos:</b> %s<br />' % opciones[
                'total_grupos']
        if 'total_grupos_inactivos' in opciones:
            op = op + '<b>Total de grupos inactivos:</b> %s<br />' % opciones[
                'total_grupos_inactivos']
        op_p = Paragraph(op, style['Normal'])

        # Tabla

        if tabla is not None:
            d = tabla
            f = 7
        else:
            d = datos
            f = 10

        table = Table(d)
        table_style = [('BACKGROUND', (0, 0), (-1, 0), colors.orange),
                       ('ALIGN', (1, 1), (-1, -1), 'CENTER'),
                       ('FONTSIZE', (0, 0), (-1, -1), f),
                       ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
                       ('BOX', (0, 0), (-1, -1), 0.25, colors.black)]

        if total:
            table_style.append(
                ('BACKGROUND', (0, -1), (-1, -1), colors.orange))
        table.setStyle(TableStyle(table_style))

        # Graficos

        sw = True
        if total:
            datos.pop()

        other_labels = datos.pop(0)
        other_labels.pop(0)
        chart_datos = list(zip(*datos))
        labels = list(chart_datos.pop(0))
        if tipo == 1:  # Pie chart
            data = list(chart_datos.pop())
            if sum(data) != 0:
                chart = PieChart(data=data, labels=labels, legends=labels)
            else:
                sw = False
        elif tipo == 2:  # Bar chart
            data = chart_datos
            chart = BarChart(data=data, labels=labels, legends=other_labels)
        else:  # Line chart
            data = chart_datos
            chart = LineChart(data=data, labels=labels, legends=other_labels)

        # Agregar al pdf
        catalog = []
        catalog.append(header)
        catalog.append(Spacer(1, 50))
        catalog.append(op_p)
        catalog.append(Spacer(1, 50))
        catalog.append(table)
        catalog.append(Spacer(1, 60))
        if sw:
            catalog.append(chart)

        self.build(catalog)
Пример #49
0
    def exportMotifs(self):
        # Iterate through each motif
        num_cols = 2
        row_iterator = 0

        styles = getSampleStyleSheet()
        titleStyle = styles['Title']
        titleStyle.alignment = 2
        titleStyle.fontSize = 20
        title = Paragraph("Graphlets", titleStyle)
        tableData = [[title]]

        listStyle = TableStyle([('BACKGROUND', (1, 1), (-2, -2), colors.green),
                                ('TEXTCOLOR', (0, 0), (1, -1), colors.black)])
        numberOfRows = len(self._data)
        # iterate over results in multiples of two
        for index in range(0, numberOfRows - 1, 2):
            # Two motifs per row
            # Input first motif
            firstMotifFilename = self.svgCache[str(self._data[index][0])]
            factor = .2
            sx = sy = factor
            drawing1 = svg2rlg(firstMotifFilename)
            drawing1.width, drawing1.height = drawing1.minWidth(
            ) * sx, drawing1.height * sy
            drawing1.scale(sx, sy)

            # Input Last motif
            secondMotifFilename = self.svgCache[str(self._data[index + 1][0])]
            drawing2 = svg2rlg(secondMotifFilename)
            drawing2.width, drawing2.height = drawing2.minWidth(
            ) * sx, drawing2.height * sy
            drawing2.scale(sx, sy)

            # Append the data
            tableData.append(["", ""])
            tableData.append([self._data[index][0], self._data[index + 1][0]])

            tableData.append([drawing1, drawing2])
            tableData.append([self._data[index][1], self._data[index + 1][1]])
            tableData.append(["", ""])

            self.progress.emit(index / numberOfRows * 100)

            if QThread.currentThread().isInterruptionRequested():
                return

        # For the last row if add the last row
        if (numberOfRows % 2 != 0):
            lastElementIndex = numberOfRows - 1
            lastmotifRow = self.svgCache[str(self._data[lastElementIndex][0])]
            drawing1 = svg2rlg(lastmotifRow)
            factor = .2
            sx = sy = factor
            drawing1.width, drawing1.height = drawing1.minWidth(
            ) * sx, drawing1.height * sy
            drawing1.scale(sx, sy)
            tableData.append(["", ""])
            tableData.append([self._data[lastElementIndex][0], ""])
            tableData.append([drawing1, ""])
            tableData.append([self._data[lastElementIndex][1], ""])
            tableData.append(["", ""])

        elements = []
        t = Table(tableData)
        listStyle.add("ALIGN", (0, 0), (-1, -1), "CENTER")
        listStyle.add("VALIGN", (0, 0), (-1, -1), "MIDDLE")
        listStyle.add("", (0, 0), (-1, -1), "MIDDLE")
        #listStyle.add("BACKGROUND",(0,0),(-1,-1),colors.red)
        t.setStyle(listStyle.getCommands())
        elements.append(t)
        elements.append(svg2rlg("./report/plot.svg"))
        # write the to disk
        self.pdfFile.build(elements)

        self.finished.emit(True)
Пример #50
0
def print_pdf_EARLY_SETTLEMENT(request, agreement_id):

    pdf_buffer = BytesIO()
    my_doc = SimpleDocTemplate(pdf_buffer,
                               rightMargin=50,
                               leftMargin=50,
                               topMargin=20,
                               bottomMargin=50
                               )
    flowables = []

    sample_style_sheet = getSampleStyleSheet()
    sample_style_sheet.list()

    agreement_detail = go_agreement_querydetail.objects.get(agreementnumber=agreement_id)
    agreement_customer = go_customers.objects.get(customernumber=agreement_detail.agreementcustomernumber)
    account_summary = go_account_transaction_summary.objects.filter(agreementnumber=agreement_id)
    if agreement_detail.agreementdefname != 'Hire Purchase' and agreement_detail.agreementdefname != 'Management Fee':
        agreement_type = 'Lease'
        sales_tax_rate = 1.2
    else:
        agreement_type = 'HP'
        sales_tax_rate = 1.0

    settlement_figure_queryset = account_summary.aggregate(Sum('transnetpayment'))
    settlement_figure = settlement_figure_queryset['transnetpayment__sum']
    settlement_figure_queryset_gross = account_summary.aggregate(Sum('transgrosspayment'))
    settlement_figure_gross = settlement_figure_queryset_gross['transgrosspayment__sum']
    if agreement_type == 'Lease':
        settlement_figure_vat = settlement_figure * decimal.Decimal(sales_tax_rate)
    else:
        settlement_figure_vat = settlement_figure * decimal.Decimal(sales_tax_rate)

    next_rental_date = go_account_transaction_summary.objects.filter(agreementnumber=agreement_id,
                                                                            transactionsourceid__in=['SP1', 'SP2',
                                                                                                     'SP3', 'GO1', 'GO3'],
                                                                            transtypeid__isnull=False,
                                                                            transactiondate__gt=datetime.date.today()).first()
    next = next_rental_date.transactiondate.strftime("%d/%m/%Y")

    paragraph_33 = Paragraph(

        "<u> Early Termination Figure </u>",

        sample_style_sheet['Heading1']
    )
    arrears_total_collected = request.GET.get('arrears_total_collected')

    a = Paragraph('''<u>Hire Agreement Number:</u>''', sample_style_sheet['BodyText'])
    b = Paragraph('''<u>Hire Agreement Name:</u>''', sample_style_sheet['BodyText'])
    c = Paragraph('''<u>Goods:</u>''', sample_style_sheet['BodyText'])
    d = Paragraph('''Terminal Settlement Figure:''', sample_style_sheet['Heading4'])
    e = Paragraph("£" + str(format(arrears_total_collected)), sample_style_sheet['Heading4'])
    table3 = [a, agreement_id], \
             [b, agreement_customer.customercompany], \
             [c, "As per schedule NCF01"], \
             [d, e]

    paragraph_4 = Paragraph(
        "In response to your request for a termination figure for agreement " + agreement_id + " we have pleasure in providing the following information. For security purposes the termination details are provided by email and post.If you have not requested this, please contact us immediately."
        ,
        sample_style_sheet['BodyText']
    )
    paragraph_5 = Paragraph(

        "Your Account details are protected by the Data Protection Act (DPA), so we can only discuss your account with you. We will not discuss details of your account with any other person unless you first give us your express permission to do so. This is to ensure the details about your business remain secure at all times. "
        ,
        sample_style_sheet['BodyText']
    )
    paragraph_6 = Paragraph(
        "These types of agreements have huge tax benefits to your business and are not interest only contracts, we are not allowed or permitted to discount over a certain level, however there are no penalties for early termination. This figure has been calculated after taking into account the transactions up to and including todays date and is valid until the date shown below. We are assuming that your bank will not recall any direct debit, standing order and any cheques already received by us will be honoured. The Termination Sum which you will have to pay upon early termination of this Agreement will be based upon the remaining total gross rentals shown on the agreement in the Rental payments section as also shown in clause 9 (b). This termination sum represents damages and not a supply of services therefore you will not receive a separate vat invoice as per clause 9 (d). The total payable below is only valid until the date shown below subject to the agreement being upto date. "
        ,
        sample_style_sheet['BodyText']
    )
    paragraph_7 = Paragraph(
        "<b>Important - Your Personal Information</b> - We may use your personal information for a variety of purposes and further details of the use of information by us can be found about this and your other rights if you see our Fair Processing Notice at: www.bluerockfinance.co.uk / fair - processing - notice /. We consider that such processing is necessary for our legitimate interests in considering applications and in operating Agreements and our business, and it is a requirement of entering into an Agreement. You have a right to object to our processing your information on grounds relating to your particular situation."
        ,
        sample_style_sheet['BodyText']
    )
    paragraph_8 = Paragraph(
        "If you decide to terminate the agreement early and applying the maximum discount possible, including the notice period, please see below:       "
        ,
        sample_style_sheet['BodyText']
    )

    f = Paragraph("Total Payable for Settlement:", sample_style_sheet['Heading4'])
    h = Paragraph("Valid Until:", sample_style_sheet['Heading4'])
    i = Paragraph(next, sample_style_sheet['Heading4'])

    table5 = [f, e, h, i],

    j = Paragraph("Bank Name:", sample_style_sheet['BodyText'])
    k = Paragraph("Coutts & Co", sample_style_sheet['BodyText'])
    l = Paragraph("Account No & Sort Code:", sample_style_sheet['BodyText'])
    m = Paragraph("0576 9981   18 - 00 - 02", sample_style_sheet['BodyText'])

    n = Paragraph("Account Name:", sample_style_sheet['BodyText'])
    o = Paragraph("Bluerock Secured Finance", sample_style_sheet['BodyText'])
    p = Paragraph("Reference:", sample_style_sheet['BodyText'])
    q = Paragraph(agreement_id, sample_style_sheet['BodyText'])

    table4 = [j, k, l, m], \
             [n, o, p, q]

    paragraph_11 = Paragraph(
        "We offer a new business discount for further finance taken out prior to the valid until date shown above. If you would like to discuss the end of hire options & requirements, then please contact your broker."
        ,
        sample_style_sheet['BodyText']
    )
    paragraph_12 = Paragraph(
        "We would like to take this opportunity to thank you for using Bluerock Secured Finance Ltd and wish you "
        "and your business every success in the future."
        ,
        sample_style_sheet['BodyText']
    )
    paragraph_125 = Paragraph(
        "",
        sample_style_sheet['BodyText']
    )

    paragraph_13 = Paragraph(
        " Yours faithfully,"
        ,
        sample_style_sheet['BodyText']
    )
    paragraph_14 = Paragraph(
        "Alan Richards"
        ,
        sample_style_sheet['BodyText']
    )
    paragraph_15 = Paragraph(
        " Customer Services"
        ,
        sample_style_sheet['BodyText']
    )
    paragraph_16 = Paragraph(

        " VAT Reg No. 974 594073 | Authorised & Regulated by the Financial Conduct Authority Firm Ref No: 729205 | Company Reg No. 06944649."
        ,

        sample_style_sheet['Heading6']
    )

    im = Image("static/assets/images/others/bluerock-logo.jpg", width=3.4 * inch, height=0.8 * inch)
    im.hAlign = 'RIGHT'

    if agreement_customer.customeraddress1:
        address1 = Paragraph(agreement_customer.customeraddress1, sample_style_sheet['BodyText'])
    else:
        address1 = ''
    if agreement_customer.customeraddress2:
        address2 = Paragraph(agreement_customer.customeraddress2, sample_style_sheet['BodyText'])
    else:
        address2 = ''
    if agreement_customer.customeraddress3:
        address3 = Paragraph(agreement_customer.customeraddress3, sample_style_sheet['BodyText'])
    else:
        address3 = ''
    if agreement_customer.customeraddress4:
        address4 = Paragraph(agreement_customer.customeraddress4, sample_style_sheet['BodyText'])
    else:
        address4 = ''
    if agreement_customer.customeraddress5:
        address5 = Paragraph(agreement_customer.customeraddress5, sample_style_sheet['BodyText'])
    else:
        address5 = ''
    if agreement_customer.customerpostcode:
        postcode = Paragraph(agreement_customer.customerpostcode, sample_style_sheet['BodyText'])
    array = [agreement_customer.customercompany, address1, address2, address3, address4, address5, postcode]
    while ('' in array): array.remove('')
    array.append('')
    array.append('')
    array.append('')
    array.append('')

    data2 = [['', ''],
             [array[0], ''],
             [array[1], ''],
             [array[2], ''],
             [array[3], ''],
             [array[4], ''],
             [array[5], im],
             ]

    t2 = Table(data2, colWidths=247, rowHeights=15)
    t3 = Table(table3, colWidths=247, rowHeights=15, style=[])
    t5 = Table(table5, colWidths=99, rowHeights=18, style=[])
    t4 = Table(table4, colWidths=120, rowHeights=15, style=[])

    t4._argW[0] = 1.2 * inch
    t4._argW[1] = 2 * inch
    t4._argW[2] = 1.9 * inch
    t4._argW[3] = 1.8 * inch

    t5._argW[0] = 2.4 * inch
    t5._argW[1] = 1.5 * inch
    t5._argW[2] = 1.5 * inch
    t5._argW[3] = 1.5 * inch

    flowables.append(t2)
    flowables.append(paragraph_33)
    flowables.append(t3)
    flowables.append(paragraph_4)
    flowables.append(paragraph_5)
    flowables.append(paragraph_6)
    flowables.append(paragraph_7)
    flowables.append(paragraph_8)
    flowables.append(t5)
    flowables.append(t4)
    flowables.append(paragraph_11)
    flowables.append(paragraph_12)
    flowables.append(paragraph_13)
    flowables.append(paragraph_125)
    flowables.append(paragraph_125)
    flowables.append(paragraph_125)
    flowables.append(paragraph_14)
    flowables.append(paragraph_15)
    flowables.append(paragraph_16)

    my_doc.build(flowables)

    pdf_EARLY_SETTLEMENT_value = pdf_buffer.getvalue()
    pdf_buffer.close()
    response = HttpResponse(content_type='application.pdf')

    filename = 'Apellio ' + agreement_id + " Early Settlement Figure"

    response['Content-Disposition'] = "attachment; filename=%s.pdf" % filename

    response.write(pdf_EARLY_SETTLEMENT_value)
    return response
Пример #51
0
                   alignment=TA_CENTER))
styles.add(
    ParagraphStyle(name='EquityHeading',
                   fontName='Palatino Linotype',
                   fontSize=12,
                   alignment=TA_JUSTIFY))
styles.add(
    ParagraphStyle(name='Body',
                   fontName='Palatino Linotype',
                   fontSize=10,
                   alignment=TA_JUSTIFY))
# Define story list for holding flowables
story = list()
# Add a paragraph to the pdf story with the title. </u> is XML for underline.
story.append(
    Paragraph('<u>HL Fund and Share Account Trades: Tax Year XXXX-XX</u>',
              style=styles['MainTitle']))
# Add a blank line. If font size is 10, then height=12 adds a blank line.
story.append(Spacer(5, 30))

# In loop below, recreate individual, larger figures for each equity.
# Set accuracy of Tick labels to be used, depending on Buy-Sell interval
monthYear = mdates.DateFormatter('%b-%y')
dayMonthYear = mdates.DateFormatter('%d-%b-%y')
# Create historical price plots. Each plot will be saved in-memory to BytesIO object to be put into PDF document
for equity_name, equity in prices.items():
    if equity.get('Price History') is not None:
        fig, ax = plt.subplots(figsize=(7, 4), tight_layout=True)
        ax.plot(equity['Price History'].index,
                equity['Price History']['Close'],
                color='blue',
                linewidth=1)
Пример #52
0
def seatingChartByStudent(request, id):
    mealTime = models.MealTime.objects.get(pk=id)

    allStudents = set(mealTime.allStudents())
    seenStudents = set()

    data = []

    for tableAssignment in mealTime.tableassignment_set.all():
        table = tableAssignment.table
        student = tableAssignment.student

        data.append((student.first_name, student.last_name, table.description))

        seenStudents.add(student)

    leftovers = [(s.first_name, s.last_name)
                 for s in (allStudents - seenStudents)]
    leftovers.sort(key=lambda s: (s[1], s[0]))
    data.sort(key=lambda s: (s[1], s[0]))

    normal = getSampleStyleSheet()["Normal"]
    heading = getSampleStyleSheet()["Title"]
    heading.fontSize = 40

    story = []
    story.append(Paragraph(mealTime.name, heading))
    story.append(FrameBreak())
    story.append(NextPageTemplate("twoCol"))

    for first, last, table in data:
        story.append(Paragraph("%s %s: %s" % (first, last, table), normal))

    out = BytesIO()
    doc = BaseDocTemplate(out,
                          pagesize=letter,
                          author="Rectory School Seating Chart Generator",
                          title=mealTime.name)

    top = Frame(doc.leftMargin, doc.height, doc.width, 100)
    frame1 = Frame(doc.leftMargin,
                   doc.bottomMargin,
                   doc.width / 2 - 6,
                   doc.height - 75,
                   id='col1')
    frame2 = Frame(doc.leftMargin + doc.width / 2 + 6,
                   doc.bottomMargin,
                   doc.width / 2 - 6,
                   doc.height - 75,
                   id='col2')
    doc.addPageTemplates([
        PageTemplate(id='topColHeader', frames=[top, frame1, frame2]),
    ])

    frame1 = Frame(doc.leftMargin,
                   doc.bottomMargin,
                   doc.width / 2 - 6,
                   doc.height,
                   id='col1')
    frame2 = Frame(doc.leftMargin + doc.width / 2 + 6,
                   doc.bottomMargin,
                   doc.width / 2 - 6,
                   doc.height,
                   id='col2')
    doc.addPageTemplates([
        PageTemplate(id='twoCol', frames=[frame1, frame2]),
    ])

    #start the construction of the pdf
    doc.build(story)

    response = HttpResponse(content_type='application/pdf')
    response[
        'Content-Disposition'] = 'filename="{mealTime:} by student.pdf"'.format(
            mealTime=mealTime.name)

    response.write(out.getvalue())

    return response
Пример #53
0
def _create_invoice(invoice_buffer, invoice, proposal):

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

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

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

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

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

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

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

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

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

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

    return invoice_buffer
 def _section_3(self):
     elems = [
         Paragraph(
             "<i>For the above listed case only, please correct the charge(including the new O.C.G.A. Code Section) and/or disposition (if Rule Nisi, include new disposition date) to indicate:</i>",
             styles["main"]),
     ]
     width = 188 * mm
     ps = styles["field-label"]
     if self.data["change_text"]:
         text_width = stringWidth(self.data["change_text"], ps.fontName,
                                  ps.fontSize)
         lines = textwrap.wrap(
             self.data["change_text"],
             int(
                 len(self.data["change_text"]) /
                 (text_width / int((width) + 1))))
         if len(lines) < 2:
             lines.append("")
     else:
         lines = ["", ""]
     table_data = list()
     for line in lines:
         table_data.append([Paragraph(line, ps)])
     elems.append(
         Table(table_data,
               style=extend_table_style(styles["main-table"], [
                   ("LINEBELOW", (0, 0),
                    (-1, -1), 0.25 * mm, "black", "butt"),
               ]),
               rowHeights=9.7 * mm))
     ts = extend_table_style(styles["main-table"],
                             [("ALIGN", (0, 0), (-1, -1), "CENTER"),
                              ("VALIGN", (0, 0), (-1, -1), "TOP")])
     elems.append(
         Table(
             [
                 [
                     Paragraph(
                         "This change is being made pursuant to O.C.G.A. §§ 40-13-32 and 40-13-33 as follows:",
                         style=styles["main"])
                 ],
                 [
                     self._create_radio_option(
                         "within  90 days of disposition at the court’s discretion",
                         4.42 * mm,
                         checked=self.data["change_reason_within90"],
                         style=ts)
                 ],
                 [
                     self._create_radio_option(
                         "more than 90 days but not more than 180 days after disposition pursuant to the notification and hearing requirements of O.C.G.A. §40-13-32",
                         4.42 * mm,
                         checked=self.data["change_reason_within180"],
                         style=ts)
                 ],
                 [
                     self._create_radio_option(
                         "to correct a clerical error (at any time) ",
                         4.42 * mm,
                         checked=self.data["change_reason_clerical"],
                         style=ts)
                 ],
             ],
             style=extend_table_style(styles["main-table"], [
                 ("TOPPADDING", (0, 0), (-1, -1), 5 * mm),
             ]),
         ))
     elems.extend([
         Spacer(0, 5 * mm),
         self._create_field(
             "Court Official Requesting Change (please print):", 91 * mm,
             "%s" % self.data["change_court_official"], 96.5 * mm),
         self._create_field(
             "Title of Official Requesting Change (please print):", 94 * mm,
             "%s" % self.data["change_title_official"], 93.5 * mm),
         Spacer(0, 5 * mm),
     ])
     elems.append(
         Table(
             [[
                 Paragraph("Signature of Requesting Official:",
                           styles["field-label"]),
                 SignatureRect(124 * mm,
                               9.5 * mm,
                               label="Requesting Official",
                               sig_id="RS-01"),
             ]],
             style=extend_table_style(styles["main-table"], [
                 ("LEFTPADDING", (1, 0), (1, -1), 0.5 * mm),
                 ("LINEBELOW", (1, 0), (1, -1), 0.25 * mm, "black", "butt"),
             ]),
             colWidths=(61.5 * mm, 126 * mm),
             rowHeights=9.7 * mm,
         ))
     elems.append(Spacer(0, 5 * mm))
     table_data = [
         [
             Table(
                 [[
                     Paragraph("Date of Request:", styles["field-label"]),
                     SignatureDatetimeRect(
                         59 * mm, 9.5 * mm, sig_id="RS-01"),
                 ]],
                 style=extend_table_style(styles["main-table"], [
                     ("LEFTPADDING", (1, 0), (1, -1), 0.5 * mm),
                     ("LINEBELOW", (1, 0),
                      (1, -1), 0.25 * mm, "black", "butt"),
                 ]),
                 colWidths=(32.5 * mm, 61 * mm),
                 rowHeights=9.7 * mm,
             ),
             # Image("dds_seal.jpg", width=30 * mm, height=15 * mm, kind='proportional'),
             Paragraph(
                 "<b>Court Seal Here</b>",
                 extend_style(styles["main"],
                              textColor=colors.HexColor(0xC1C1C1),
                              alignment=TA_CENTER)),
         ],
         [
             Paragraph("<i>DS-1195&nbsp;&nbsp;01/07</i>",
                       extend_style(styles["main"], fontSize=6,
                                    leading=10)), None
         ]
     ]
     elems.append(
         Table(table_data,
               style=extend_table_style(styles["main-table"], [
                   ("SPAN", (1, 0), (1, 1)),
                   ("LEFTPADDING", (0, 1), (0, 1), 0.5 * mm),
                   ("TOPPADDING", (1, 0), (1, -1), 4.5 * mm),
                   ("LEFTPADDING", (1, 0), (1, -1), 28 * mm),
                   ("VALIGN", (1, 0), (1, -1), "MIDDLE"),
                   ("ALIGN", (1, 0), (1, -1), "CENTER"),
               ]),
               rowHeights=(9.7 * mm, 9.0 * mm)))
     elems.append(Spacer(0, 0.9 * mm))
     return [self._create_section_table(elems)]
Пример #55
0
def export_labuses_diff(imports, production, previous_imports,
                        previous_production):
    data = join_labuse_data(imports, production)
    previous_data = join_labuse_data(previous_imports, previous_production)
    if not data and not previous_data:
        return tuple()

    # It's OK to use set() on the keys as they are unique (substance names)
    data_set = set(data.keys())
    previous_data_set = set(previous_data.keys())

    # Compute added, changed and removed keys, taking into account they are
    # unique.
    added_keys = list(data_set.difference(previous_data_set))
    changed_keys = [
        key for key in data_set.intersection(previous_data_set)
        if instances_equal(data[key], previous_data[key]) is False
    ]
    removed_keys = list(previous_data_set.difference(data_set))

    if not added_keys and not changed_keys and not removed_keys:
        # Nothing has been changed, return empty tuple
        return ()

    # Now populate PDF
    subtitle = Paragraph(subtitle_text, h2_style)
    subtitle.keepWithNext = True
    ret = (subtitle, )
    all_data = (
        (_('Added'), added_keys, data, {}),
        (_('Changed'), changed_keys, data, previous_data),
        (_('Removed'), removed_keys, {}, previous_data),
    )
    for sub_subtitle, keys, dictionary, previous_dictionary in all_data:
        if not keys:
            # Do not add anything if there are no keys for this sub-section
            continue

        if dictionary and previous_dictionary:
            # Changed
            data = tuple(
                table_row_diff(dictionary[key], previous_dictionary[key])
                for key in keys)
        elif not previous_dictionary:
            # Added
            data = tuple(table_row(dictionary[key]) for key in keys)
        elif not dictionary:
            # Removed
            data = tuple(table_row(previous_dictionary[key]) for key in keys)

        table = rows_to_table(table_header, data,
                              col_widths([1.0, 3, 4, 4, 15.3]),
                              SINGLE_HEADER_TABLE_STYLES)
        ret += (
            Paragraph(sub_subtitle, h3_style),
            table,
            # Also insert linebreak to keep it beautiful
            Paragraph('<br/>', h3_style))

    # TODO: comments
    return ret
Пример #56
0
def prepare_ballot(e, total, n, emails, keyemails, intpdf):
    #print "test...creating ballot.."
    #print total
    #print n

    #create ballots
    for v in range(100,total+100):
        serial = str(v)
        key = os.urandom(RSIZE)
	skey = base64.b64encode(key)
        codes = ["",""]
        recs = ["",""]
	votes = ["",""]
	ciphers = ["",""]
	plains = ["",""]
        for ab in range(2):
	    #print "script run"

	    p = subprocess.Popen(["sh","/var/www/finer/EC-ElGamal/GenPerm.sh", str(n), str(total)],stdout=subprocess.PIPE,stderr=subprocess.PIPE)
	    output,err = p.communicate()
	    votes[ab] = output
	    #read from the disk file for ciphers
	    f = open('/var/www/finer/EC-ElGamal/EC_cipher.txt')
	    lines = f.readlines()
	    f.close()
	    flag = 0
	    i = 0
	    for enc in lines:
		i+=1
		if i >= 2:
		    if i%2 == 0:
			ciphers[ab]+=" "	
		    else: #" " and "," alternating
			ciphers[ab]+=","	
		ciphers[ab]+=enc.strip()
	    #read from the disk file for plains
            f = open('/var/www/finer/EC-ElGamal/EC_plain.txt')
            lines = f.readlines()
            f.close()
            i = 0
            for decommit in lines:
                i+=1
                if i >= 2:
                    if i%2 == 0:
                        plains[ab]+=" "
                    else: #" " and "," alternating
                        plains[ab]+=","
                plains[ab]+=decommit.strip()

	    for i in range(n):
    	        message = bytes(serial+str(ab)+str(i)).encode('utf-8')
    	        c = hmac.new(key, message, digestmod=hashlib.sha256).digest()
	        c1 = long(binascii.hexlify(c[0:8]), 16) #convert 64 bit string to long
	        c1 &= 0x3fffffffffffffff # 64 --> 62 bits
	        sc1 = base36encode(c1)
		while len(sc1)<12:#length padding
		    sc1 = "0"+sc1
	        r1 = long(binascii.hexlify(c[8:12]), 16) #convert 32 bit string to long
                r1 &= 0x7fffffff # 32 --> 31 bits
                sr1 = base36encode(r1)
		while len(sr1)<6:#length padding
                    sr1 = "0"+sr1
                if i > 0:
		    codes[ab]+=","
		    recs[ab]+=","
	        codes[ab]+=addbars(sc1)
	        recs[ab]+=sr1
	new_b = Ballot(election = e, serial = serial, key = skey, votes1 = votes[0],votes2 = votes[1],plain1 = plains[0],plain2 = plains[1] ,cipher1 = ciphers[0],cipher2 = ciphers[1], codes1 = codes[0],codes2 = codes[1],rec1 = recs[0],rec2 = recs[1])
        new_b.save()
    #mark as prepared
    e.prepared = True
    e.save()
    # assign email ballots
    #get choices
    options = e.choice_set.order_by('id').values('text')
    opts = [x['text'] for x in options]
    #get all the unassigned ballots
    unused = Ballot.objects.filter(election = e)# all are not used
    counter = 0
    for voter in emails:
	#generate random token
	token = long(binascii.hexlify(os.urandom(16)), 16)
        stoken = base36encode(token)#no padding 128 bit
	b = unused[counter]
	counter += 1
	email = voter.rstrip()
	assign = Assignment(election = e, vID = stoken+email, serial = b.serial)
	assign.save()
	#mark as used
	b.used = True
	b.save()
	#store token
	new_t = Tokens(election = e, token = stoken, email = email)
	new_t.save()
	#get codes and options
    	codes1 = b.codes1.split(',')
    	codes2 = b.codes2.split(',')
    	rec1 = b.rec1.split(',')
    	rec2 = b.rec2.split(',')
##################################String sort bug!!!!!!!!!!!!#######################
    	perm1 = [int(x) for x in b.votes1.split(',')]
    	perm2 = [int(x) for x in b.votes2.split(',')]
####################################################################################
    	#sort according to perm1
    	sorted1 = sorted(zip(perm1,codes1,rec1))
    	sorted2 = sorted(zip(perm2,codes2,rec2))
    	ballot_code1 = [y for (x,y,z) in sorted1]
    	ballot_code2 = [y for (x,y,z) in sorted2]
    	ballot_rec1 = [z for (x,y,z) in sorted1]
    	ballot_rec2 = [z for (x,y,z) in sorted2]
    	#send email for the first time
    	emailbody = "Hello,\n\nHere is your ballot.\n"
	emailbody+= "================================================\nSerial Number: "+b.serial+"\n"
	emailbody+= "================================================\nBallot A: \n"
	for i in range(len(opts)):
	    emailbody+= "Votecode: "+ballot_code1[i]+"  Receipt: "+ballot_rec1[i]+ "  Option: "+opts[i]+"\n"
        emailbody+= "================================================\nBallot B: \n"
        for i in range(len(opts)):
            emailbody+= "Votecode: "+ballot_code2[i]+"  Receipt: "+ballot_rec2[i]+ "  Option: "+opts[i]+"\n"
	emailbody+= "================================================\n"
    	emailbody+= "\nVBB url: "+BB_URL+"vbb/"+e.EID+"/\n"
    	emailbody+= "ABB url: "+BB_URL+"abb/"+e.EID+"/\n"
	emailbody+= "Client url: "+CLIENT_URL+e.EID+"/"+stoken+"/\n"
    	emailbody+= "\nFINER Ballot Distribution Server\n"
    	#send email		
    	p = subprocess.Popen(["sudo","/var/www/finer/bingmail.sh","Ballot for Election: "+e.question, emailbody,email],stdout=subprocess.PIPE,stderr=subprocess.PIPE, env=env)
    	output,err = p.communicate()
###################
#pdf ballots
    zip_buffer = cStringIO.StringIO()
    zfile = zipfile.ZipFile(zip_buffer,'w')
    for i in range(intpdf):
	#generate random token
	token = long(binascii.hexlify(os.urandom(16)), 16)
        stoken = base36encode(token)#no padding 128 bit
	b = unused[counter]
	counter += 1
	email = "pdf"+str(i)
	assign = Assignment(election = e, vID = stoken+email, serial = b.serial)
	assign.save()
	#mark as used
	b.used = True
	b.save()
	#store token
	new_t = Tokens(election = e, token = stoken, email = email)
	new_t.save()
	#get codes and options
    	codes1 = b.codes1.split(',')
    	codes2 = b.codes2.split(',')
    	rec1 = b.rec1.split(',')
    	rec2 = b.rec2.split(',')
##################################String sort bug!!!!!!!!!!!!#######################
        perm1 = [int(x) for x in b.votes1.split(',')]
        perm2 = [int(x) for x in b.votes2.split(',')]
####################################################################################
    	#sort according to perm1
    	sorted1 = sorted(zip(perm1,codes1,rec1))
    	sorted2 = sorted(zip(perm2,codes2,rec2))
    	ballot_code1 = [y for (x,y,z) in sorted1]
    	ballot_code2 = [y for (x,y,z) in sorted2]
    	ballot_rec1 = [z for (x,y,z) in sorted1]
    	ballot_rec2 = [z for (x,y,z) in sorted2]
	#generate the pdf
	buffer = cStringIO.StringIO()
    	# Create the PDF object, using the IO object as its "file."
	  #register ttf fonts
 	ttffont='/usr/share/fonts/truetype/ttf-liberation/'
    	pdfmetrics.registerFont(TTFont('LiberationSans', ttffont+'LiberationSans-Regular.ttf'))
    	pdfmetrics.registerFont(TTFont('LiberationSansBd', ttffont+'LiberationSans-Bold.ttf'))
    	pdfmetrics.registerFont(TTFont('LiberationSansIt', ttffont+'LiberationSans-Italic.ttf'))
    	pdfmetrics.registerFont(TTFont('LiberationSansBI', ttffont+'LiberationSans-BoldItalic.ttf'))
	#create pdf doc
	doc = SimpleDocTemplate(buffer, pagesize=A4,leftMargin=0.1*inch,rightMargin=0.1*inch)
	style = ParagraphStyle(
        	name='Normal',
		#firstLineIndent = 0,
		#leftIndent = 0,
        	fontName='LiberationSansBd',
        	fontSize=14,
		leftMargin=0.3*inch,
            	firstLineIndent = 0.3*inch,
    	)
    
    	style_warning = ParagraphStyle(
        	name='Normal',
        	fontName='LiberationSans',
        	fontSize=12,
        	leftMargin=0.5*inch,
                firstLineIndent = 0.5*inch,
    	)
	#prepare table data
	data = [['Πολιτικό κόμμα', 'Κωδικός A', 'Απόδειξη A','','Πολιτικό κόμμα', 'Κωδικός A', 'Απόδειξη A']]
	data2 = [['Πολιτικό κόμμα', 'Κωδικός B', 'Απόδειξη B','','Πολιτικό κόμμα', 'Κωδικός B', 'Απόδειξη B']]

	for ii in range(len(opts)/2):
		tempname1 = opts[2*ii].split(';')
                tempname2 = opts[2*ii+1].split(';')
		temprow = [tempname1[0],ballot_code1[2*ii], ballot_rec1[2*ii],'',tempname2[0],ballot_code1[2*ii+1],ballot_rec1[2*ii+1]]
		data.append(temprow)
                temprow = [tempname1[0],ballot_code2[2*ii], ballot_rec2[2*ii],'',tempname2[0],ballot_code2[2*ii+1],ballot_rec2[2*ii+1]]
                data2.append(temprow)

	serial = [['Σειριακός αριθμός:',b.serial,'Σειριακός αριθμός:',b.serial]]

	#pdf part
	parts = []

	table_serial = Table(serial, [2*inch,1.65 * inch, 2*inch,1.65* inch])
        table_serial.setStyle(TableStyle([
    	('FONT', (0, 0), (-1, 0), 'LiberationSansBd'),
    	('FONTSIZE', (0, 0), (-1, -1), 14),
    	('ALIGN', (0, 0), (-1, 0), 'CENTER'),
    	]))

    	parts.append(table_serial)
    	parts.append(Spacer(1, 0.2 * inch))
    	table_with_style = Table(data, [1.5 * inch, 1.3 * inch, 0.8*inch,0.1*inch, 1.5*inch,1.3 * inch, 0.8*inch])

   	table_with_style.setStyle(TableStyle([
    	('FONT', (0, 0), (-1, -1), 'LiberationSans'),
    	('FONT', (0, 0), (-1, 0), 'LiberationSansBd'),
    	('FONTSIZE', (0, 0), (-1, -1), 9),
    	('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
    	('BOX', (0, 0), (-1, 0), 0.25, colors.green),
    	('ALIGN', (0, 0), (-1, 0), 'CENTER'),
    	('BOX',(0,0),(-1,-1),2,colors.black),
    	('BOX', (1, 0), (2, -1),2, colors.black),
    	('BOX', (4, 0), (-1, -1),2, colors.black),
    	]))

    
    	parts.append(table_with_style)

    	parts.append(Spacer(1, 0.4 * inch))
    	#drawimage
	img = qrcode.make(SAMPLE_URL+e.EID+"/"+stoken+"/0/")
        output = cStringIO.StringIO() ## temp QR file
        img.save(output,'PNG')
        output.seek(0) #rewind the data
        I = Image(output, width = 150, height = 150)
	I.hAlign = 'LEFT'
	table_img = Table([[I,"A"]], [4*inch,4* inch])
    	table_img.setStyle(TableStyle([
    	('FONT', (0, 0), (-1, 0), 'LiberationSansBd'),
    	('FONTSIZE', (0, 0), (-1, -1), 120),
    	('ALIGN', (0, 0), (-1, 0), 'LEFT'),
    	('VALIGN', (0, 0), (-1, 0), 'TOP'),
    	]))
    	parts.append(table_img)
	#parts.append(I)
    	parts.append(Spacer(1, 0.3 * inch))
        parts.append(Paragraph("Εξυπηρετητής Ψηφοδελτίων FINER &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp "+BB_URL+"abb/"+e.EID+"/", style))
    	parts.append(Spacer(1, 0.55 * inch))
    	parts.append( Paragraph("Παρακαλούμε χρησιμοποιήστε οποιαδήποτε από τις δύο πλευρές αυτού του φύλλου.",style_warning))
#########append url for debug
    	#parts.append(Paragraph(SAMPLE_URL+e.EID+"/"+stoken+"/",style_warning))

    	parts.append(table_serial)
    	parts.append(Spacer(1, 0.2 * inch))
    	table_with_style = Table(data2, [1.5 * inch, 1.3 * inch, 0.8*inch,0.1*inch, 1.5*inch,1.3 * inch, 0.8*inch])

    	table_with_style.setStyle(TableStyle([
    	('FONT', (0, 0), (-1, -1), 'LiberationSans'),
    	('FONT', (0, 0), (-1, 0), 'LiberationSansBd'),
    	('FONTSIZE', (0, 0), (-1, -1), 9),
    	('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black),
    	('BOX', (0, 0), (-1, 0), 0.25, colors.green),
    	('ALIGN', (0, 0), (-1, 0), 'CENTER'),
    	('BOX',(0,0),(-1,-1),2,colors.black),
    	('BOX', (1, 0), (2, -1),2, colors.black),
    	('BOX', (4, 0), (-1, -1),2, colors.black),
    	]))
    
    	parts.append(table_with_style)

    	parts.append(Spacer(1, 0.4 * inch))
    	#drawimage
        img = qrcode.make(SAMPLE_URL+e.EID+"/"+stoken+"/1/")
        output = cStringIO.StringIO() ## temp QR file
        img.save(output,'PNG')
        output.seek(0) #rewind the data
        I = Image(output, width = 150, height = 150)
        I.hAlign = 'LEFT'
        table_img = Table([[I,"B"]], [4*inch,4* inch])
        table_img.setStyle(TableStyle([
        ('FONT', (0, 0), (-1, 0), 'LiberationSansBd'),
        ('FONTSIZE', (0, 0), (-1, -1), 120),
        ('ALIGN', (0, 0), (-1, 0), 'LEFT'),
        ('VALIGN', (0, 0), (-1, 0), 'TOP'),
        ]))
        parts.append(table_img)
        #parts.append(I)
    	parts.append(Spacer(1, 0.3 * inch))
    	parts.append(Paragraph("Εξυπηρετητής Ψηφοδελτίων FINER &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp "+BB_URL+"abb/"+e.EID+"/", style))
    	parts.append(Spacer(1, 0.55 * inch))
    	parts.append( Paragraph("Παρακαλούμε χρησιμοποιήστε οποιαδήποτε από τις δύο πλευρές αυτού του φύλλου.",style_warning))

    	doc.build(parts)

	output.close()
	#save pdf
        zfile.writestr("Ballots/"+str(i)+".pdf", buffer.getvalue())
        buffer.close()

    new_pdf = Pdfballot(election = e, token = stoken)
    new_pdf.save()
    zfile.close()
    new_pdf.pdf.save("Ballots"+e.EID+".zip",ContentFile(zip_buffer.getvalue()))
    zip_buffer.close()
#send the PDF ballot link
    emailbody = "Hello,\n\nYour ballots are generated. You can download them now.\n"
    emailbody+= "URL: "+Ballot_URL+e.EID+"/"+stoken+"/\n"
    emailbody+= "\nFINER Ballot Distribution Server\n"
    #send email             
    p = subprocess.Popen(["sudo","/var/www/finer/bingmail.sh","PDF Ballots for Election: "+e.question, emailbody,e.c_email],stdout=subprocess.PIPE,stderr=subprocess.PIPE, env=env)
    output,err = p.communicate()	

########################################
	
    #send ABB CSV data
    #random key for column 1
    k1 = os.urandom(KSIZE)
    sk1 = base64.b64encode(k1)
    new_r = Randomstate(election = e, notes = "k1",random = sk1)
    new_r.save()

###send key to key holders
    emailbody = "Dear Key Holder,\n\n Your private key is:\n"
    emailbody+= "================================================\n"	
    emailbody+= sk1+"\n"
    emailbody+= "================================================\n"
    emailbody+= "\nYour Tally URL: "+BB_URL+"keyholder/"+e.EID+"/\n"
    emailbody+= "\nFINER  Election Authority\n"
    email = keyemails
    #send email         
    p = subprocess.Popen(["sudo","/var/www/finer/bingmail.sh","Private Key for Election Definition "+e.EID, emailbody,email],stdout=subprocess.PIPE,stderr=subprocess.PIPE, env=env)
    output,err = p.communicate()
##########################

    #create csv file and encrypt the codes
    output = cStringIO.StringIO() ## temp output file
    writer = csv.writer(output, dialect='excel')
    #first row n, k1.
    writer.writerow([str(n),sk1])
    #get all the ballots
    all_ballots = Ballot.objects.filter(election = e)
    for each in all_ballots:
	writer.writerow([each.serial,each.key])#second row serial , key.
	#encrypt codes
	temp_list = each.codes1.split(',')
	enc_list = []
	for temp in temp_list:
	    enc_list.append(base64.b64encode(encrypt(temp,k1,key_size=128)))	
	writer.writerow(enc_list)
	#write cipher
	temp_list = each.cipher1.split(',')
	writer.writerow(temp_list)
	#write plain
        temp_list = each.plain1.split(',')
        writer.writerow(temp_list)
	#do the same for ballot 2
        #encrypt codes
        temp_list = each.codes2.split(',')
        enc_list = []
        for temp in temp_list:
            enc_list.append(base64.b64encode(encrypt(temp,k1,key_size=128)))
        writer.writerow(enc_list)
        #write cipher
        temp_list = each.cipher2.split(',')
        writer.writerow(temp_list)
        #write plain
        temp_list = each.plain2.split(',')
        writer.writerow(temp_list)
    #post
    reply = requests.post(BB_URL+'abb/'+e.EID+'/upload/',files = {'inputfile':ContentFile(output.getvalue(),name = "init.csv")}, verify=False)
    
    #close
    output.close()
    return reply
Пример #57
0
def hello_pdf(strtest='', title='', tablename='default', excel_rows=3):
    rl_config.warnOnMissingFontGlyphs = 0
    pdfmetrics.registerFont(TTFont('song', r"./fonts/simsun.ttc"))
    pdfmetrics.registerFont(TTFont('fs', r"./fonts/simfang.ttf"))
    pdfmetrics.registerFont(TTFont('hei', r"./fonts/simhei.ttf"))
    pdfmetrics.registerFont(TTFont('yh', r"./fonts/msyh.ttf"))
    pdfmetrics.registerFont(TTFont('yh2', r"./fonts/msyhbd.ttf"))
    pdfmetrics.registerFont(TTFont('华文中宋', r"./fonts/STZHONGS.TTF"))
    pdfmetrics.registerFont(TTFont('颜体_准', r"./fonts/FZYanSJW_Zhun.ttf"))
    pdfmetrics.registerFont(TTFont('颜体_中', r"./fonts/FZYanSJW_Zhong.ttf"))
    #设置字体:常规、斜体、粗体、粗斜体
    addMapping('cjk', 0, 0, 'song')  #normal
    addMapping('cjk', 0, 1, 'fs')  #italic
    addMapping('cjk', 1, 0, 'hei')  #bold
    addMapping('cjk', 10, 1, 'yh')  #italic and bold

    p = canvas.Canvas(tablename + '.pdf')  #,pagesize=
    #默认(0, 0)点在左下角,此处把原点(0,0)向上和向右移动,后面的尺寸都是相对与此原点设置的
    #注意:移动原点时,向右向上为正,坐标系也是向右为+x,向上为+y
    #p.translate(0.5*inch, 0.5*inch)
    '''
    #画一条线
    p.setStrokeColorRGB(0/255, 123/255, 198/255) #改变线颜色#设置颜色,画笔色和填充色
    p.setFillColorRGB(0/255, 123/255, 198/255)
    p.setLineWidth(1)
    p.line(46.5/25.4*inch,(297-23)/25.4*inch, (210-19)/25.4*inch, (297-23)/25.4*inch)
    
    draw_string(string,x,y,font = 'song',size = 14,color = 'red', anchor = 'middle')
    Pa.drawOn(p, 0*inch, (297-49.5)/25.4*inch)
    '''

    #画矩形 共三个
    '''p.setStrokeColorRGB(216/255, 216/255, 216/255) 
    p.setFillColorRGB(216/255, 216/255, 216/255) #设置背景颜色
    p.rect(0, (297-65)/25.4*inch, 210/25.4*inch, 22/25.4*inch, fill=1)

    p.setStrokeColorRGB(0/255, 123/255, 198/255) 
    p.setFillColorRGB(0/255, 123/255, 198/255) #设置背景颜色
    p.rect(0, 0, 210/25.4*inch, 9/25.4*inch, fill=1)
    '''
    #右上角“策略运行报告”
    p.drawImage(r"./figures/策略运行报告.png", 130 / 25.4 * inch, 268 / 25.4 * inch,
                63 / 25.4 * inch, 18 / 25.4 * inch)

    #左上角公司Logo
    p.drawImage(r"./figures/Logo.png", 10 / 25.4 * inch, 270 / 25.4 * inch,
                65 / 25.4 * inch, 17 / 25.4 * inch)

    #蓝色渐变底
    p.drawImage(r"./figures/back_block.png", 0 / 25.4 * inch,
                246 / 25.4 * inch, 210 / 25.4 * inch, 21 / 25.4 * inch)
    #底部脚注的背景
    p.drawImage(r"./figures/back_block.png", 0 / 25.4 * inch, 4 / 25.4 * inch,
                210 / 25.4 * inch, 14 / 25.4 * inch)

    #下脚注
    p.setFont('华文中宋', 14)  #设置字体
    p.setStrokeColorRGB(38 / 255, 38 / 255, 38 / 255)  #改变线颜色#设置颜色,画笔色和填充色
    p.setFillColorRGB(38 / 255, 38 / 255, 38 / 255)  #改变字体颜色与填充颜色
    p.drawString(10 / 25.4 * inch, 11 / 25.4 * inch, u"专业实力 敏锐嗅觉 互利共赢")

    p.setFont('华文中宋', 8)  #设置字体
    p.setStrokeColorRGB(38 / 255, 38 / 255, 38 / 255)  #改变线颜色#设置颜色,画笔色和填充色
    p.setFillColorRGB(38 / 255, 38 / 255, 38 / 255)  #改变字体颜色与填充颜色
    p.drawString(
        10 / 25.4 * inch, 7 / 25.4 * inch,
        u"免责声明:本资料中所有观点及投资组合运作表现仅供潜在投资人参考,并不构成管理人及投资顾问对投资者投资回报、经营业绩等任何承诺。")

    #给出标题
    p.setFont('颜体_中', 26)  #设置字体
    p.setStrokeColorRGB(38 / 255, 38 / 255, 38 / 255)  #改变线颜色#设置颜色,画笔色和填充色
    p.setFillColorRGB(38 / 255, 38 / 255, 38 / 255)  #改变字体颜色与填充颜色
    p.drawString(65 / 25.4 * inch, (297 - 62) / 25.4 * inch, title)
    '''
    p.setStrokeColorRGB(0/255, 123/255, 198/255) 
    p.setFillColorRGB(0/255, 123/255, 198/255) #设置背景颜色
    p.rect(0, (297-49)/25.4*inch, 210/25.4*inch, 21/25.4*inch, fill=1)
    '''

    #说明段落
    ParagraphStyle.defaults['wordWrap'] = "CJK"  #实现中文自动换行
    styleSheet = getSampleStyleSheet()
    style = styleSheet['BodyText']
    style.fontName = '华文中宋'
    style.fontSize = 11  #字号
    style.leading = 17  #设置行距
    style.leftIndent = 15 / 25.4 * inch
    style.rightIndent = 0 * 27 / 25.4 * inch
    style.textColor = colors.HexColor('#111111')  #设置字体颜色
    #style.firstLineIndent = 32 #首行缩进
    #Pa = Paragraph(u'<b>这里是粗体</b>,<i>这里是斜体</i>, <strike>这是删除线</strike>, <u>这是下划线</u>, <sup>这是上标</sup>, <em>这里是强调</em>, <font color=#ff0000>这是红色</font>', style)
    Pa = Paragraph(strtest, style)
    Pa.wrapOn(p, 7.6 * inch, 10 * inch)
    Pa.drawOn(p, 0 * inch, (297 - 50) / 25.4 * inch)

    #插入小标题背景
    p.drawImage(r"./figures/title_block.png", 10 / 25.4 * inch,
                (297 - 75 - 2) / 25.4 * inch, 80 / 25.4 * inch,
                8 / 25.4 * inch)
    p.drawImage(r"./figures/title_block.png", 10 / 25.4 * inch,
                (97 + excel_rows * 2) / 25.4 * inch, 80 / 25.4 * inch,
                8 / 25.4 * inch)
    p.drawImage(r"./figures/title_block.png", 10 / 25.4 * inch,
                57 / 25.4 * inch, 80 / 25.4 * inch, 8 / 25.4 * inch)

    #插入小标题(还要考虑年数很多的问题)
    p.setFont('颜体_中', 13)  #设置字体
    p.setStrokeColorRGB(38 / 255, 38 / 255, 38 / 255)  #改变线颜色#设置颜色,画笔色和填充色
    p.setFillColorRGB(38 / 255, 38 / 255, 38 / 255)  #改变字体颜色与填充颜色
    p.drawString(15 / 25.4 * inch, (297 - 74) / 25.4 * inch, u"一、策略名字 策略历史收益")
    p.drawString(15 / 25.4 * inch, (100 + excel_rows * 2) / 25.4 * inch,
                 u"二、年收益与波动")
    p.drawString(15 / 25.4 * inch, 60 / 25.4 * inch, u"三、收益率平稳性")

    #插入图片 3张
    p.drawImage(r"./figures/fig1.jpg", 35 / 25.4 * inch,
                (297 - 95 - 80) / 25.4 * inch, 135 / 25.4 * inch,
                93 / 25.4 * inch)
    p.drawImage(r"./figures/fig1_AC.jpg", 40 / 25.4 * inch, 20 / 25.4 * inch,
                135 / 25.4 * inch, 40 / 25.4 * inch)
    p.drawImage(r"./figures/{}_OUTPUT.jpeg".format(tablename),
                30 / 25.4 * inch, (80 - excel_rows) / 25.4 * inch,
                150 / 25.4 * inch, excel_rows * 4.5 / 25.4 * inch)

    #表格
    '''
    tabl = table_model(data_table)
    tabl.wrapOn(p, 7*inch, 7.8*inch)
    tabl.drawOn(p, 0*inch, 7.5*inch)
    '''
    #柱状图1

    #饼状图1
    '''
    pie = autoLegender(draw_pie(data_pie,labs_pie,color_pie,250),'hahaha',400,250,'off',labs_pie,color_pie)
    pie.wrapOn(p, 7*inch, 7.6*inch)
    pie.drawOn(p, 0*inch, 5.5*inch)
    '''
    #折线
    '''
    pl = autoLegender(draw_lines(data2,100,180,color_pie[0:6]),'',180,250,'off')
    pl.wrapOn(p, 7*inch, 8*inch)
    pl.drawOn(p, 0*inch, 3*inch)
    pl = autoLegender(draw_lines(data2,100,180,color_pie[0:6]),'',180,250,'off')
    pl.wrapOn(p, 7*inch, 8*inch)
    pl.drawOn(p, 3.5*inch, 3*inch)
    '''
    #加水印
    '''
    p.rotate(5)
    p.setFont('yh2', 60) #设置字体
    transparentblack = colors.Color(216/255,216/255,216/255,alpha = 0.2)
    p.setFillColor(transparentblack)
    p.drawString(40/24.5*inch, (297-100)/24.5*inch, u"智研")
    p.drawString(145/24.5*inch, (297-100)/24.5*inch, u"智研")
    
    p.drawString(36.66/24.5*inch, 141.34/24.5*inch, u"智研")
    p.drawString(141.66/24.5*inch, 141.34/24.5*inch, u"智研")
    
    p.drawString(33.33/24.5*inch, 70.67/24.5*inch, u"智研")
    p.drawString(138.33/24.5*inch, 70.67/24.5*inch, u"智研")
    
    p.drawString(30/24.5*inch, 15/24.5*inch, u"智研")
    p.drawString(135/24.5*inch, 15/24.5*inch, u"智研")
    transparentblack = colors.Color(0,0,0,alpha = 1)
    p.setFillColor(transparentblack)
    p.rotate(-5)  
    '''
    #保存pdf
    p.showPage()
    p.save()
    print("----- Successfully generated:", tablename, end='\n\n')
    return 'succeed'
Пример #58
0
    def create_pdf(self):
        """Create a PDF output file."""
        for child_elem in self.bnml:
            if child_elem.tag in ['header-even', 'header']:
                default_header_style = self.styleSheet['Header']
                header_attrib_dict = self.fill_attribute_dict(
                    child_elem.attrib)
                if 'style' in header_attrib_dict:
                    default_header_style = getattr(self.styleSheet,
                                                   header_attrib_dict['style'],
                                                   'Header')
                header_style = self.merge_paragraph_styles(
                    default_header_style, header_attrib_dict)
                header_text = child_elem.text.strip()
                self.header_even_paragraph: Paragraph = Paragraph(
                    header_text, header_style)

                for embedded_attrib in child_elem:
                    if embedded_attrib.tag is not None and embedded_attrib.tag == 'page-number':
                        pagenum_attrib_dict = self.fill_attribute_dict(
                            embedded_attrib.attrib)
                        self.header_even_pagenum_style = self.merge_paragraph_styles(
                            default_header_style, pagenum_attrib_dict)

            if child_elem.tag == 'header-odd':
                default_header_style = self.styleSheet['Header']
                header_attrib_dict = self.fill_attribute_dict(
                    child_elem.attrib)
                if 'style' in header_attrib_dict:
                    default_header_style = getattr(self.styleSheet,
                                                   header_attrib_dict['style'],
                                                   'Header')
                header_style = self.merge_paragraph_styles(
                    default_header_style, header_attrib_dict)
                header_text = child_elem.text.strip()
                self.header_odd_paragraph: Paragraph = Paragraph(
                    header_text, header_style)

                for embedded_attrib in child_elem:
                    if embedded_attrib.tag is not None and embedded_attrib.tag == 'page-number':
                        pagenum_attrib_dict = self.fill_attribute_dict(
                            embedded_attrib.attrib)
                        self.header_odd_pagenum_style = self.merge_paragraph_styles(
                            default_header_style, pagenum_attrib_dict)

            if child_elem.tag == 'footer':
                default_footer_style = self.styleSheet['Footer']
                footer_attrib_dict = self.fill_attribute_dict(
                    child_elem.attrib)
                if 'style' in footer_attrib_dict:
                    default_footer_style = getattr(self.styleSheet,
                                                   footer_attrib_dict['style'],
                                                   'Header')
                footer_style = self.merge_paragraph_styles(
                    default_footer_style, footer_attrib_dict)
                footer_text = child_elem.text.strip()
                self.footer_paragraph: Paragraph = Paragraph(
                    footer_text, footer_style)

            if child_elem.tag == 'pagebreak':
                self.story.append(PageBreak())

            if child_elem.tag == 'linebreak':
                space = child_elem.attrib.get('space', '30')
                space_amt = int(space)
                self.story.append(Spacer(0, space_amt))

            if child_elem.tag == 'paragraph':
                paragraph_attrib_dict = self.fill_attribute_dict(
                    child_elem.attrib)
                self.draw_paragraph(child_elem, paragraph_attrib_dict)

            if child_elem.tag == 'troparion':
                neumes_list = []
                lyrics_list = []
                dropcap = None
                dropcap_offset = 0

                for troparion_child_elem in child_elem:
                    if troparion_child_elem.tag == 'pagebreak':
                        self.story.append((PageBreak()))

                    if troparion_child_elem.tag == 'neumes':
                        neumes_elem = troparion_child_elem
                        attribs_from_bnml = self.fill_attribute_dict(
                            neumes_elem.attrib)
                        neumes_style = self.merge_paragraph_styles(
                            self.styleSheet['Neumes'], attribs_from_bnml)

                        for neume_char in neumes_elem.text.strip().split():
                            neume = Neume(char=neume_char,
                                          font_family=neumes_style.fontName,
                                          font_size=neumes_style.fontSize,
                                          color=neumes_style.textColor)
                            neumes_list.append(neume)

                    if troparion_child_elem.tag == 'lyrics':
                        lyrics_elem = troparion_child_elem
                        lyrics_style = self.styleSheet['Lyrics']
                        attribs_from_bnml = self.fill_attribute_dict(
                            lyrics_elem.attrib)
                        lyrics_style = self.merge_paragraph_styles(
                            lyrics_style, attribs_from_bnml)

                        for lyric_text in lyrics_elem.text.strip().split():
                            lyric = Lyric(text=lyric_text,
                                          font_family=lyrics_style.fontName,
                                          font_size=lyrics_style.fontSize,
                                          color=lyrics_style.textColor,
                                          top_margin=lyrics_style.spaceBefore)
                            lyrics_list.append(lyric)

                    if troparion_child_elem.tag == 'dropcap':
                        dropcap_elem = troparion_child_elem
                        dropcap_style = self.styleSheet['Dropcap']
                        if dropcap_elem.attrib:
                            attribs_from_bnml = self.fill_attribute_dict(
                                dropcap_elem.attrib)
                            dropcap_style = self.merge_paragraph_styles(
                                dropcap_style, attribs_from_bnml)
                        dropcap_text = dropcap_elem.text.strip()
                        dropcap = Dropcap(dropcap_text, 10, dropcap_style)
                        dropcap_offset = dropcap.width + dropcap.x_padding

                # Pop off first letter of lyrics, since it will be drawn as a dropcap
                if dropcap and lyrics_list:
                    lyrics_list[0].text = lyrics_list[0].text[1:]
                    lyrics_list[0].recalc_width()

                if neumes_list:
                    neume_chunks = neume_dict.chunk_neumes(neumes_list)
                    glyph_line: List[Glyph] = self.make_glyph_list(
                        neume_chunks, lyrics_list)
                    lines_list: List[GlyphLine] = self.line_break(
                        glyph_line, Cursor(dropcap_offset, 0), self.doc.width,
                        self.styleSheet['Neumes'].leading,
                        self.styleSheet['Neumes'].wordSpace)
                    if len(lines_list) > 1 or self.styleSheet[
                            'Neumes'].alignment is TA_JUSTIFY:
                        lines_list: List[GlyphLine] = self.line_justify(
                            lines_list, self.doc.width, dropcap_offset)

                    for i, glyph_line in enumerate(lines_list):
                        if i == 0 and dropcap:
                            data = [[dropcap, glyph_line]]
                            row_height = max(dropcap.height, glyph_line.height)
                            t = Table(data,
                                      colWidths=[dropcap_offset, None],
                                      rowHeights=[row_height])
                            t.setStyle(
                                TableStyle([
                                    ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
                                    ('LEFTPADDING', (0, 0), (-1, -1), 0),
                                    ('RIGHTPADDING', (0, 0), (-1, -1), 0),
                                    ('BOTTOMPADDING', (0, 0), (-1, -1), 0),
                                    ('TOPPADDING', (0, 0), (-1, -1), 0),
                                ]))
                            t.spaceAfter = glyph_line.leading - glyph_line.height
                            self.story.append(t)
                        else:
                            self.story.append(glyph_line)

        try:
            self.doc.build(self.story,
                           onFirstPage=self.draw_footer,
                           onEvenPages=self.draw_header_footer,
                           onOddPages=self.draw_header_footer)
        except IOError:
            logging.error("Could not save XML file.")
Пример #59
0
def create_pdf_resume(user):
    from reportlab.lib.pagesizes import letter
    from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Image
    from reportlab.lib.units import inch

    doc = SimpleDocTemplate("farsi_resume.pdf", pagesize=letter, rightMargin=110, leftMargin=72, topMargin=72,
                            bottomMargin=18)

    story = []

    styles = add_styles()
    # bold_style = styles['Justify-Bold']
    # normal_style = styles['Justify']
    right_bold_style = styles['Right-Bold']
    right_normal_indented_style = styles['Right-indented']
    right_normal_style = styles['Right']
    right_small_style = styles['Right-small']
    # right_bold_titr_style = styles['Right-Bold-Titr']
    # centre_bold_style = styles['Centre-Bold']
    # centre_normal_style = styles['Centre']

    # story.append(Paragraph(get_farsi_formatted_text('بسمه تعالی'), centre_normal_style))
    # story.append(Spacer(1, 15))

    d = Drawing(100, 1)
    line = Line(0, 0, 450, 0, strokeColor=colors.lavender)
    d.add(line)
    story.append(d)
    story.append(Spacer(1, 15))

    # p_img = ImageReader(logo)
    # p_img = Paragraph('<img src=\"./{}\" valign=\"top\"/>'.format(logo), right_normal_style)
    logo = 'python_logo.png'
    p_img = Image(logo, 1.2*inch, .3*inch, hAlign='LEFT')
    story.append(p_img)
    req = urllib.request.Request("http://tipn.parsadp.com/api/v1.0{}".format(user['image']))
    req.add_header('token', 'og4ZNFIdbDW9sahj3DqWpVgSA2YiPVtuCBqbYhbx5QuZ2qH47syY2eazArK6HKujtF+w1GUBI1L1J7xeXPmBFDv4j45gubO2CX8qxmuYs3u31RgfdbK+cW3JdezhAoEG')
    p_img = urllib.request.urlopen(req)
    img = Image(p_img, 1*inch, 1*inch, hAlign='RIGHT')
    #story.append(img)

    text = '{}<br/>{}<br/>{}<br/>{}<br/>{}<br/>'.format(
        get_farsi_formatted_text('نام و نام خانوادگی: {} {}'.format(user['name'], user['last_name'])),
        get_farsi_formatted_text('تاریخ تولد: {}'.format(get_jalali_date(user['birthday']))),
        get_farsi_formatted_text('وضعیت تاهل: {}'.format(user['is_married'])),
        get_farsi_formatted_text('ایمیل: {}'.format(user['email'])),
        get_farsi_formatted_text('آدرس: {}'.format(user['address'])))

    p = Paragraph(text, right_normal_style)
    colWidths = [5*inch, 2.5*inch]
    # rowHeights = []
    table = Table([[p, img]], colWidths=colWidths)
    table.setStyle(TableStyle([('BACKGROUND', (0, 0), (-1, -1), colors.white),
                               ('TEXTCOLOR', (0, 0), (-1, -1), colors.black),
                               ("VALIGN", (0, 1), (-1, -1), "CENTER"),
                               ('ALIGN', (0, 0), (0, 0), 'RIGHT'),
                               # ('RIGHTPADDING', (0, 0), (0, 0), 0)
                               ('ALIGN', (-1, -1), (-1, -1), 'CENTER')
                               ]))
    story.append(table)
    story.append(Spacer(1, 15))
    d = Drawing(100, 1)
    line = Line(20, 0, 430, 0, strokeColor=colors.lavender)
    d.add(line)
    # r = Rect(0, 0, 450, 3, fillColor=colors.lavenderblush, strokeColor=colors.red)
    # d.add(r)
    story.append(d)

    # p2 = Paragraph('{}{}'.format(text, '<img src="./python_logo.png" valign="top"/>'), right_normal_style)
    # story.append(p2)

    # p3 = Paragraph('{}{}'.format('<img src="./python_logo.png" valign="top" width="100" height="100"/>', text),
    #                right_normal_style)
    # story.append(p3)

    # story.append(Spacer(1, 12))
    # story.append(Paragraph(get_farsi_formatted_text('نام و نام خانوادگی: {} {}'.format(user['name'],
    #                                                                                    user['last_name'])),
    #                        right_normal_indented_style))
    # story.append(Paragraph(get_farsi_formatted_text('تاریخ تولد: {}'.format(get_jalali_date(user['birthday']))), right_normal_indented_style))
    # story.append(Paragraph(get_farsi_formatted_text('وضعیت تاهل: {}'.format(user['is_married'])), right_normal_indented_style))
    # story.append(Paragraph(get_farsi_formatted_text('آدرس ایمیل: {}'.format(user['email'])), right_normal_indented_style))
    # story.append(Paragraph(get_farsi_formatted_text('آدرس: {}'.format(user['address'])), right_normal_indented_style))
    # story.append(Spacer(1, 10))

    if user['proficiencies']:
        story.append(Paragraph(get_farsi_formatted_text('مهارت ها :'), right_bold_style))
        story.append(Spacer(1, 3))
        story.append(d)
        story.append(Spacer(1, 3))

        profs = []
        for prof in user['proficiencies']:
            # story.append(Paragraph(get_farsi_formatted_text(' - {}  در سطح {}'.format(prof['skill']['title'],
            #                                                                           prof['skill_level'])),
            #                        right_normal_indented_style))
            # story.append(Spacer(1, 5))
            profs.append([Paragraph(get_farsi_formatted_text(prof['skill_level']),
                                    right_normal_indented_style),
                          Paragraph(get_farsi_formatted_text(' - %s' % prof['skill']['title']), right_normal_style)])

        # colWidths = [2*inch, 3*inch, 2*inch]
        # rowHeights = []
        # table = Table(profs, colWidths=colWidths, rowHeights=rowHeights)
        table = Table(profs)
        table.setStyle(TableStyle([('BACKGROUND', (0, 0), (-1, -1), colors.white),
                                   ('TEXTCOLOR', (0, 0), (-1, -1), colors.black),
                                   ("VALIGN", (0, 0), (-1, -1), "RIGHT"),
                                   ('ALIGN', (0, 0), (-1, -1), 'RIGHT'),
                                   # ('RIGHTPADDING', (0, 0), (0, 0), 0)
                                   # ,('ALIGN', (-1, -1), (-1, -1), 'CENTER')
                                   ]))
        story.append(table)
        # story.append(Paragraph('<html><head><style>.rightToleft{text-align:right;direction:rtl;float:right}</style>'
        #                        '</head><body><div class="rightToleft">', right_normal_indented_style))
        # for prof in user['proficiencies']:
        #     story.append(Paragraph(get_farsi_list_item(' - {}  در سطح {}'.format(prof['skill']['title'],
        #                                                prof['skill_level'])), right_normal_indented_style))
        # story.append(Paragraph('</ul></div></body></html>', right_normal_indented_style))  # dont work
        #
        # story.append(Paragraph('<div  align="right" dir="rtl"><ul>', right_normal_indented_style))
        # for prof in user['proficiencies']:
        #     story.append(Paragraph(get_farsi_list_item(' - {}  در سطح {}'.format(prof['skill']['title'],
        #                                                   prof['skill_level'])), right_normal_indented_style))
        # story.append(Paragraph('</ul></div>', right_normal_indented_style)) # dont work

        # list_f = ListFlowable([
        #     ListItem(Paragraph(get_farsi_formatted_text(' - {}  در سطح {}'.format(prof['skill']['title'],
        #                                                                                   prof['skill_level'])),
        #                                right_normal_indented_style)) for prof in user['proficiencies']], bulletType='bullet',
        #                       start='square', align='right')
        # story.append(list_f)
        story.append(Spacer(1, 5))

    if user['experiences']:
        story.append(d)
        story.append(Paragraph(get_farsi_formatted_text('تجربیات کاری :'), right_bold_style))
        story.append(Spacer(1, 3))
        story.append(d)
        story.append(Spacer(1, 3))

        expes = []
        for exp in user['experiences']:
            # story.append(Paragraph(get_farsi_formatted_text(' - {} در {}'.format(exp['title'], exp['company']['name'])),
            #                        right_normal_indented_style))
            # story.append(Paragraph(get_farsi_formatted_text('{}'.format(exp['description'])),
            #                        right_normal_indented_style))
            p1 = [Paragraph(get_farsi_formatted_text('- {} در {}'.format(exp['title'],
                             exp['company']['name'])), right_normal_style),
                                   Paragraph(get_farsi_formatted_text(exp['description']), right_small_style)]

            if exp['currently_work_here']:
                p2 = Paragraph(get_farsi_formatted_text('از تاریخ: {}    تاکنون').format(
                        get_jalali_date(exp['from_date'])), right_small_style)
            else:
                p2 = Paragraph(get_farsi_formatted_text('از تاریخ: {}    تا تاریخ: {}').format(
                    get_jalali_date(exp['from_date']), get_jalali_date(exp['to_date'])), right_small_style)
            # story.append(Spacer(1, 5))
            expes.append([p2, p1])
        # colWidths = [2*inch, 3*inch, 2*inch]
        # rowHeights = []
        # table = Table(expes, colWidths=colWidths, rowHeights=rowHeights)
        table = Table(expes)
        table.setStyle(TableStyle([('BACKGROUND', (0, 0), (-1, -1), colors.white),
                                   ('TEXTCOLOR', (0, 0), (-1, -1), colors.black),
                                   ("VALIGN", (0, 0), (-1, -1), "RIGHT"),
                                   ('ALIGN', (0, 0), (-1, -1), 'RIGHT'),
                                   # ('RIGHTPADDING', (0, 0), (0, 0), 0)
                                   # ,('ALIGN', (-1, -1), (-1, -1), 'CENTER')
                                   ]))
        story.append(table)
        story.append(Spacer(1, 5))

    if user['educations']:
        story.append(d)
        story.append(Paragraph(get_farsi_formatted_text('سوابق تحصیلی :'), right_bold_style))
        story.append(Spacer(1, 3))
        story.append(d)
        story.append(Spacer(1, 3))

        edus = []
        for edu in user['educations']:
            # p1 = [Paragraph(get_farsi_formatted_text(edu['school']['title']),
            #                         right_normal_indented_style),
            #               Paragraph(get_farsi_formatted_text('- {} {}'.format(edu['degree'], edu['field_of_study'])),
            #                         right_normal_style)]
            p1 = Paragraph(get_farsi_formatted_text(' - {}  {} از {}'.format(edu['degree'], edu['field_of_study'],
                                             edu['school']['title'])), right_normal_style)
            p4 = ''
            if edu['date_attended_from'] and edu['date_attended_to']:
                p4 = Paragraph(get_farsi_formatted_text('از تاریخ: {}    تا تاریخ: {}').format(
                    get_jalali_date(edu['date_attended_from']), get_jalali_date(edu['date_attended_to'])), right_small_style)
            edus.append([p4, p1])
            # story.append(Paragraph(get_farsi_formatted_text(' - {}  {} از {}'.format(edu['degree'], edu['field_of_study'],
            #                                                                        edu['school']['title'])), right_normal_indented_style))
            if edu['grade']:
                p2 = Paragraph(get_farsi_formatted_text('معدل: {}'.format(get_farsi_numbers(edu['grade']))),
                                                                right_small_style)
                edus.append(["", p2])
            if edu['description']:
                p3 = Paragraph(get_farsi_formatted_text('{}'.format(edu['description'])),
                                   right_normal_indented_style)
                edus.append(["", p3])
            # story.append(Spacer(1, 5))
        table = Table(edus)
        table.setStyle(TableStyle([('BACKGROUND', (0, 0), (-1, -1), colors.white),
                                   ('TEXTCOLOR', (0, 0), (-1, -1), colors.black),
                                   # ("VALIGN", (0, 0), (-1, -1), "CENTER"),
                                   ('ALIGN', (0, 0), (-1, -1), 'RIGHT'),
                                   # ('RIGHTPADDING', (0, 0), (0, 0), 0)
                                   # ,('ALIGN', (-1, -1), (-1, -1), 'CENTER')
                                   ]))
        story.append(table)
        story.append(Spacer(1, 5))

    if user['languages']:
        story.append(d)
        story.append(Paragraph(get_farsi_formatted_text('زبان ها:'), right_bold_style))
        story.append(Spacer(1, 3))
        story.append(d)
        story.append(Spacer(1, 3))

        langs = []
        for lang in user['languages']:
            # story.append(Paragraph(get_farsi_formatted_text('{}  در سطح {}'.format(lang['name'], lang['proficiency'])),
            #                        right_normal_indented_style))
            langs.append([Paragraph(get_farsi_formatted_text(lang['proficiency']),
                                    right_normal_indented_style),
                          Paragraph(get_farsi_formatted_text(' - %s' % lang['name']), right_normal_style)])

        table = Table(langs)
        table.setStyle(TableStyle([('BACKGROUND', (0, 0), (-1, -1), colors.white),
                                   ('TEXTCOLOR', (0, 0), (-1, -1), colors.black),
                                   ("VALIGN", (0, 0), (-1, -1), "RIGHT"),
                                   ('ALIGN', (0, 0), (-1, -1), 'RIGHT'),
                                   ]))
        story.append(table)
        story.append(Spacer(1, 5))

    if user['interest']:
        story.append(d)
        story.append(Paragraph(get_farsi_formatted_text('علاقمندی ها :'), right_bold_style))
        story.append(Spacer(1, 3))
        story.append(d)
        story.append(Paragraph(get_farsi_formatted_text('- {}'.format(user['interest'])), right_normal_indented_style))
        story.append(Spacer(1, 10))

    # doc.build(story)
    doc.watermark = 'MOTANAWEB'
    # logo = 'python_logo.png'
    # p_img = Paragraph('<img src=\"./{}\" width="265" height="75"/>'.format(logo), right_normal_style)
    # p_img = Paragraph('<img src=\"./{}\" width="132" height="37"/>'.format(logo), right_normal_style)
    # p_img_ = ParagraphAndImage()
    # story.append(p_img)
    doc.multiBuild(story, canvasmaker=FooterCanvas)
 def _section_2(self):
     elems = list()
     table_data = list()
     table_data.append([
         Table([[
             self._create_field("Court", 11.5 * mm,
                                "%s" % self.data["court_name"], 101.1 * mm),
             self._create_field("Telephone #", 24.5 * mm,
                                "%s" % self.data["court_phone"], 49.5 * mm),
         ]],
               style=styles["main-table"],
               colWidths=(113.8 * mm, None))
     ])
     ps = extend_style(style=styles["main"], fontSize=10, leading=12)
     table_data.append([
         Table(
             [[
                 self._create_field("Citation Number", 31.6 * mm,
                                    "%s" % self.data["court_citation"],
                                    103.5 * mm),
                 Paragraph("&nbsp;(if no citation, use case number)",
                           style=ps)
             ]],
             style=styles["main-table"],
         )
     ])
     table_data.append([
         Table(
             [[
                 self._create_field("Original Charge", 30.5 * mm, "%s" %
                                    self.data["court_charge"], 89.5 * mm),
                 self._create_field("O.C.G.A. §", 21 * mm, "%s" %
                                    self.data["court_ocga"], 47 * mm),
             ]],
             style=styles["main-table"],
         )
     ])
     table_data.append([
         Table([[
             self._create_field("Disposition Date", 31.8 * mm,
                                "%s" % self.data["court_disposition_date"],
                                58.8 * mm),
             self._create_field("Violation Date", 27.6 * mm,
                                "%s" % self.data["court_violation_date"],
                                61.2 * mm),
         ]],
               style=styles["main-table"],
               colWidths=(97.7 * mm, None))
     ])
     option_list = [
         "Guilty", "Nolo Contendere", "Bond Forfeiture", "First Offender"
     ]
     idx = option_list.index(self.data["court_disposition"])
     option_elems = list()
     for i in range(0, len(option_list)):
         checked = True if idx == i else False
         label = "<i>%s</i>" % option_list[i] if option_list[
             i] == "Nolo Contendere" else option_list[i]
         option_elems.append(
             self._create_radio_option(label, 4.42 * mm, checked=checked))
     option_elems.insert(
         0, Paragraph("Original Disposition:", styles["field-label"]))
     table_data.append([
         Table(
             [option_elems],
             style=styles["main-table"],
             colWidths=(40.5 * mm, 25.5 * mm, 45 * mm, 38 * mm, None),
         )
     ])
     elems.append(
         Table(
             table_data,
             style=styles["main-table"],
             rowHeights=9.7 * mm,
         ))
     return [self._create_section_table(elems)]