コード例 #1
0
ファイル: expedientes.py プロジェクト: edutorvi/prueba
    def draw_canvas(self, page_count):
        page1 = "Pág %s de %s" % (self._pageNumber, page_count)
        page2 = "Gobierno Regional de Cajamarca"
        x1 = 128
        x2 = 500
        x2 = 461
        self.saveState()
        self.setStrokeColorRGB(0, 0, 0)
        self.setLineWidth(0.5)
        self.line(66, 71, A4[0] - 66, 71)  #linea footer
        self.setFont('Times-Roman', 10)
        self.drawString(A4[0] - x1, 59, page1)  #texto footer

        self.setFont('Times-Roman', 12)
        self.drawString(A4[0] - x2, 785, page2)  #texto cabecera
        self.line(66, 780, A4[0] - 66, 780)  #linea cabecera

        #self = canvas.Canvas(filename, bottomup=0)
        f = Image('static/img/logo_Region_Cajamarca2019.png',
                  width=147,
                  height=50)  #imagen
        #f=Image('static/img/gr2019.png', width=73, height=25)#imagen
        f.drawOn(self, 75, 780)  #posicion DE LA IMAGEN en el encabezado

        self.restoreState()
コード例 #2
0
 def draw(self) -> None:
     w, h = 3 * cm, 3 * cm
     image = Image(self.image_src)
     image.drawWidth = w
     image.drawHeight = h
     image.drawOn(self.canv, self.doc.width - w - (0.09 * cm),
                  -(self.doc.topMargin / 1.75))
コード例 #3
0
def header(canvas, doc):
    width, height = doc.pagesize

    styles = get_custom_stylesheet_1()

    if doc.logo_path:
        img = Image(doc.logo_path, width=76.2, height=76.2)
        img.wrapOn(canvas, width, height)
        img.drawOn(canvas, 100, 700)

    ptext = 'Statement Date: {}'.format('01/01/2017')
    p = Paragraph(ptext, styles["Bold"])
    p.wrapOn(canvas, width, height)
    p.drawOn(canvas, 400, 700)

    ptext = '''
    <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/>
    '''.format(member=doc.data.member_name,
               member_id=doc.data.member_id,
               group_num=doc.data.group_num,
               group_name=doc.data.group_name)
    p = Paragraph(ptext, styles["Normal"])
    p.wrapOn(canvas, width, height)
    p.drawOn(canvas, 400, 730)
コード例 #4
0
ファイル: reporting.py プロジェクト: Lucterios2/core
 def parse_image(self, xmlimage, current_x, current_y, current_w, current_h):
     if xmlimage.text is not None:
         from PIL import ImageFile
         ImageFile.LOAD_TRUNCATED_IMAGES = True
         img_content = xmlimage.text.strip()
         is_base64 = img_content[:len(BASE64_PREFIX)] == BASE64_PREFIX
         if is_base64:
             img_file = open_from_base64(img_content)
         else:
             img_file = open(img_content, "rb")
         try:
             img = Image(img_file)
             if current_h is not None:
                 img.drawHeight = current_h
                 img.drawWidth = current_w
             else:
                 current_h = img.drawHeight
                 current_w = img.drawWidth
             _, new_current_h = img.wrapOn(self.pdf, current_w, current_h)
             img.drawOn(self.pdf, current_x, self.height - current_y - current_h)
             self.position_y = current_y + max(new_current_h, current_h)
             return img
         finally:
             if img_file is not None:
                 img_file.close()
     else:
         return None
コード例 #5
0
ファイル: views.py プロジェクト: dbsiavichay/furb
def get_letterhead_page(canvas, doc):
        # Save the state of our canvas so we can draw on it
		canvas.saveState()
		styles = getSampleStyleSheet()
		base_path = join(settings.BASE_DIR, 'static/assets/report/')

		escudo = Image(base_path + 'escudo_morona.png', width=6*cm,height=2*cm)
		logo = Image(base_path + 'logo_morona.jpg', width=2*cm,height=2*cm)
		aside = Image(base_path + 'aside.png', width=1*cm,height=10*cm)
		footer_caption = Image(base_path + 'footer-caption.png', width=6.5*cm,height=1.5*cm)
		footer_image = Image(base_path + 'footer-image.png', width=3*cm,height=1.5*cm)

		w, h = escudo.wrap(doc.width, doc.topMargin)
		escudo.drawOn(canvas, doc.leftMargin, doc.height + doc.topMargin - 20)

		w, h = logo.wrap(doc.width, doc.topMargin)
		logo.drawOn(canvas, doc.leftMargin + 480, doc.height + doc.topMargin - 20)

		w, h = aside.wrap(doc.width, doc.topMargin)
		aside.drawOn(canvas, doc.leftMargin + 510, doc.height + doc.topMargin - 375)
		
		w, h = footer_caption.wrap(doc.width, doc.topMargin)
		footer_caption.drawOn(canvas, doc.leftMargin, doc.height + doc.topMargin - 770)

		w, h = footer_image.wrap(doc.width, doc.topMargin)
		footer_image.drawOn(canvas, doc.leftMargin + 430, doc.height + doc.topMargin - 770)

        # Release the canvas
		canvas.restoreState()
コード例 #6
0
ファイル: reporting.py プロジェクト: loudubewe/core
 def parse_image(self, xmlimage, current_x, current_y, current_w,
                 current_h):
     if (xmlimage.text is not None) and (xmlimage.text.strip() != ''):
         from PIL import ImageFile
         ImageFile.LOAD_TRUNCATED_IMAGES = True
         img_content = xmlimage.text.strip()
         is_base64 = img_content[:len(BASE64_PREFIX)] == BASE64_PREFIX
         if is_base64:
             img_file = open_from_base64(img_content)
         else:
             img_file = open(img_content, "rb")
         try:
             img = Image(img_file)
             if current_h is not None:
                 img.drawHeight = current_h
                 img.drawWidth = current_w
             else:
                 current_h = img.drawHeight
                 current_w = img.drawWidth
             _, new_current_h = img.wrapOn(self.pdf, current_w, current_h)
             getLogger('lucterios.printing').debug(
                 "-- parse_image (x=%.2f/y=%.2f/h=%.2f/w=%.2f) --",
                 current_x, current_y, current_h, current_w)
             img.drawOn(self.pdf, current_x,
                        self.height - current_y - current_h)
             self.position_y = current_y + max(new_current_h, current_h)
             return img
         finally:
             if img_file is not None:
                 img_file.close()
     else:
         return None
コード例 #7
0
def draw_side_binding(canvas):
    canvas.setFont("Helvetica", 12)
    canvas.drawString(0, 2.35 * inch, '2G018653')

    image = Image(os.path.dirname(os.path.realpath(__file__)) + '/2g_logo.png')
    image.drawHeight = .70 * inch * image.drawHeight / image.drawWidth
    image.drawWidth = .70 * inch

    image.drawOn(canvas, 0, 1.55 * inch)

    paragraph_style = ParagraphStyle('paraStyle')
    paragraph_style.fontSize = 6
    paragraph_style.leading = 8

    company_name = '2g Digital Post, Inc.'
    address_one = '280 East Magnolia Blvd'
    address_two = 'Burbank, CA 91502'
    phone_number = '818.863.8900'
    todays_date = '2016-08-17'
    standard = 'Std: 1080'
    frames_per_second = 'FR: 23.98PsF'
    part = 'Part: 1 of 1'
    total_runtime = 'TRT: 114:17'

    current_y = 1.4

    for text in (company_name, address_one, address_two, phone_number,
                 todays_date, standard, frames_per_second, part,
                 total_runtime):
        paragraph = Paragraph(text, paragraph_style)
        paragraph.wrap(.9375 * inch, .5 * inch)
        paragraph.drawOn(canvas, 0, current_y * inch)

        current_y -= .1
コード例 #8
0
    def add_product_images(self, report):
        """ Check if the specified imagery exists, load it into the
        canvas if it is available.
        """
        top_found = os.path.exists(report.top_image_filename)
        bot_found = os.path.exists(report.bottom_image_filename)

        log.info("Add image: %s, %s", report.top_image_filename, report.bottom_image_filename)
        if not top_found or not bot_found:
            log.warn("Not adding unavailable product images")
            return

        # Resize the images with wand first so they will fit in the
        # document as expected. The output size when height scaled to
        # 125px will be close to 300x175 when viewed in the pdf.
        orig_image0_filename = report.top_image_filename
        orig_image1_filename = report.bottom_image_filename

        image0_filename = "temp_image0.png"
        image1_filename = "temp_image1.png"
        with WandImage(filename=orig_image0_filename) as img:
            img.transform(resize="x125")
            img.save(filename=image0_filename)

        with WandImage(filename=orig_image1_filename) as img:
            img.transform(resize="x125")
            img.save(filename=image1_filename)

        # Reload the scaled images, draw with absolute coordinates
        img_zero = Image(image0_filename)
        img_one = Image(image1_filename)

        img_zero.drawOn(self.canvas, *self.coord(135, 100, mm))
        img_one.drawOn(self.canvas, *self.coord(135, 150, mm))
コード例 #9
0
    def addHbcHeader(self):
        c = self.c
        top = self.top

        S = ParagraphStyle('dflt-right')
        S.alignment = 2

        img = utils.ImageReader('logoHD.png')
        iw, ih = img.getSize()
        aspect = ih / float(iw)

        width = 200
        I = Image('logoHD.png', width=width, height=(width * aspect))
        w, h = I.wrap(200, 50)
        I.drawOn(self.c, 14 * cm, top - h - 1 * cm)

        P = Paragraph(
            "<strong>HEADBANG CLUB</strong><br/>" +
            "15 RUE FERDINAND BUISSON<br/>" +
            "16160 GOND-PONTOURE<br/>CHARENTE - FRANCE<br/>" +
            "VAT - FR63824464127<br/>" + "TEL - +33 (0)6 63 92 55 96<br/>" +
            "[email protected] / [email protected]", S)
        w, h = P.wrap(300, 50)
        P.drawOn(self.c, 21 * cm - w - 0.5 * cm, self.top - h - 4 * cm)
        pass
コード例 #10
0
ファイル: dailyReport.py プロジェクト: kykk0010/TradingSystem
    def tradingReport(self, c):
        title = "DAILY TRADING" 
        c.setFont("Helvetica", 24)
        c.drawString(50,770, title)
        c.setFont("Helvetica", 16)
        c.drawString(50,730, "DATE :")
        c.drawString(110,730, str(today.year) + "/" + str(today.month) + "/" + str(today.day) ) # DATE
        c.line(110, 727, 185, 727)
        c.drawString(300,730, "Today's Performance :")
        c.line(465, 727, 515, 727)
        c.drawString(470,730, "4%")          # PROFIT value
        c.drawString(50,680, "Market Analysis")

        columHeight = [1*cm, 1*cm, 1*cm, 1*cm]
        t=Table(self._data, 2.5*cm, columHeight)             # The size of each cells
        t.setStyle(TableStyle([('GRID',(0,0),(-1,-1),1,colors.black),
                               ('VALIGN',(0,0),(-1,-1),'TOP')]))
                           
        t.wrapOn(c, 50,50)  
        t.drawOn(c, 50,550)     #Table Location

        c.drawString(50,500, "Intraday performance of Algorithm1")
        graph_1 = Image("example.png")
        graph_1.drawHeight = 6*cm
        graph_1.drawWidth = 17.5*cm
        #graph_1.wrapOn(c, 50,20)
        graph_1.drawOn(c,50,322)

        c.drawString(50,295, "Intraday performance of Algorithm2")
        graph_2 = Image("example2.png")
        graph_2.drawHeight = 6*cm
        graph_2.drawWidth = 17.5*cm
        #graph_2.wrapOn(c, 50,20)
        graph_2.drawOn(c,50,117)
コード例 #11
0
ファイル: pdf.py プロジェクト: Talengi/phase
    def draw_logo(self, canvas):
        """ Draw the logo on pdf according to following settings:
        logo_path: absolute path to image
        wanted_height: wanted height in mm (optional, default 20 mm)
        logo_x: x coordinate in mm (optional, default 13 mm)
        logo_y: y coordinate in mm (optional, default 55 mm)
        """
        if not self.company_logo_settings:
            return
        # Get logo settings
        logo_path = self.company_logo_settings.get('path', None)
        wanted_height = self.company_logo_settings.get('wanted_height', 20)
        logo_x = self.company_logo_settings.get('x', 13)
        logo_y = self.company_logo_settings.get('y', 55)

        # Sanity check
        if not os.access(logo_path, os.R_OK):
            return

        # get original lgo dimensions to compute ratio
        logo = utils.ImageReader(logo_path)
        width, height = logo.getSize()
        ratio = float(width) / height

        # Compute width according to wanted height
        computed_width = int(wanted_height * ratio)

        # Draw logo
        im = Image(logo_path, computed_width * mm, wanted_height * mm)
        im.drawOn(canvas, *self.coord(logo_x, logo_y))
コード例 #12
0
ファイル: imagepdf.py プロジェクト: robmyers/codebag
 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)
コード例 #13
0
    def createImage(self,
                    fn,
                    aspect=None,
                    width=None,
                    height=None,
                    indent=None,
                    padding=10,
                    shift=True,
                    return_image=False):
        _, file_extension = os.path.splitext(fn)
        if file_extension.lower().strip() == '.pdf':
            logger.critical('Doesnt WORK ON PDFS yet')
            raise

        #Get image dimensions
        img = ImageReader(fn)
        iw, ih = img.getSize()

        #Set parameters
        if aspect is None:
            if width is None and height is None:
                width = iw
                height = ih
            elif height is None:
                aspect = float(ih) / float(iw)
                height = aspect * width
            elif width is None:
                aspect = float(iw) / float(ih)
                width = aspect * height
        else:
            width = iw * aspect
            height = ih * aspect

        if height > self.mheight:
            logger.warning('Image is taller than the entire page')
        if width + (indent or 0.0) > self.mwidth:
            logger.warning('Entering side margin...check')

        i = Image(fn, width=width, height=height)

        if return_image:
            return i

        #Shif down before adding to make room
        if shift:
            self.shiftPos(height + padding)

        #Indent if necessary
        if not indent is None:
            self.c.saveState()
            self.c.translate(indent, 0)

        #Draw the image
        i.drawOn(self.c, self.pos[0], self.pos[1])

        #Restore if needed
        if not indent is None:
            self.c.restoreState()

        return width, height
コード例 #14
0
def header(canvas, doc):
    width, height = doc.pagesize
    
    styles = getSampleStyleSheet()
    
    ptext = '<font size=10><b>Statement Date: {}' \
        '</b></font>'.format('01/01/2017')
    
    img = Image(doc.logo_path, width=76.2, height=76.2)
    img.wrapOn(canvas, width, height)
    img.drawOn(canvas, 100, 725)

    p = Paragraph(ptext, styles["Normal"])
    p.wrapOn(canvas, width, height)
    p.drawOn(canvas, 400, 800)

    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=doc.data.member_name,
               member_id=doc.data.member_id,
               group_num=doc.data.group_num,
               group_name=doc.data.group_name
               )
    p = Paragraph(ptext, styles["Normal"])
    p.wrapOn(canvas, width, height)
    p.drawOn(canvas, 400, 730)
コード例 #15
0
ファイル: pdf.py プロジェクト: pmzhou/phase
    def draw_logo(self, canvas):
        """ Draw the logo on pdf according to following settings:
        logo_path: absolute path to image
        wanted_height: wanted height in mm (optional, default 20 mm)
        logo_x: x coordinate in mm (optional, default 13 mm)
        logo_y: y coordinate in mm (optional, default 55 mm)
        """
        if not self.company_logo_settings:
            return
        # Get logo settings
        logo_path = self.company_logo_settings.get('path', None)
        wanted_height = self.company_logo_settings.get('wanted_height', 20)
        logo_x = self.company_logo_settings.get('x', 13)
        logo_y = self.company_logo_settings.get('y', 55)

        # Sanity check
        if not os.access(logo_path, os.R_OK):
            return

        # get original lgo dimensions to compute ratio
        logo = utils.ImageReader(logo_path)
        width, height = logo.getSize()
        ratio = float(width) / height

        # Compute width according to wanted height
        computed_width = int(wanted_height * ratio)

        # Draw logo
        im = Image(logo_path, computed_width * mm, wanted_height * mm)
        im.drawOn(canvas, *self.coord(logo_x, logo_y))
コード例 #16
0
    def _header_footer(canvas, doc):
        # Save the state of our canvas so we can draw on it
        canvas.saveState()
        styles = getSampleStyleSheet()

        # Header
        img = utils.ImageReader('https://www.martinhelder.pt/img/logotipo.png')
        img_w, img_h = img.getSize()
        header = Image('https://www.martinhelder.pt/img/logotipo.png',
                       width=0.7 * img_w,
                       height=0.7 * img_h)
        width, height = header.wrap(doc.width, doc.topMargin)
        header.drawOn(canvas, doc.leftMargin + 0 * width,
                      doc.height + doc.topMargin - height + 35)

        # Footer
        right = ParagraphStyle('BodyText', alignment=TA_RIGHT, fontName='Vera')
        footer = Table([[
            Paragraph(str(doc.page), styles['BodyText']),
            Paragraph(
                "Documento gerado a " +
                datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"), right)
        ]],
                       colWidths=(None, 0.8 * doc.width))
        footer.wrap(doc.width, doc.topMargin)
        footer.drawOn(canvas, doc.leftMargin, 0.6 * doc.bottomMargin)

        # Release the canvas
        canvas.restoreState()
コード例 #17
0
    def draw(self):
        ptext = '<font size=10><b>Statement Date: {}' \
            '</b></font>'.format('01/01/2017')

        p = Paragraph(ptext, self.styles["Normal"])
        p.wrapOn(self.canv, self.width, self.height)
        p.drawOn(self.canv, *self.coord(110, 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=self.xml_data.member_name,
                   member_id=self.xml_data.member_id,
                   group_num=self.xml_data.group_num,
                   group_name=self.xml_data.group_name
                   )
        p = Paragraph(ptext, self.styles["Normal"])
        p.wrapOn(self.canv, self.width, self.height)
        p.drawOn(self.canv, *self.coord(110, 35, mm))
        
        if self.logo:
            logo_obj = Image(self.logo, width=76.2, height=76.2)
            logo_obj.wrapOn(self.canv, self.width, self.height)
            logo_obj.drawOn(self.canv, *self.coord(15, 35, mm))
コード例 #18
0
 def parse_image(self, xmlimage, current_x, current_y, current_w,
                 current_h):
     if xmlimage.text is not None:
         from PIL import ImageFile
         ImageFile.LOAD_TRUNCATED_IMAGES = True
         img_content = xmlimage.text.strip()
         is_base64 = img_content[:len(BASE64_PREFIX)] == BASE64_PREFIX
         if is_base64:
             img_file = open_from_base64(img_content)
         else:
             img_file = open(img_content, "rb")
         try:
             img = Image(img_file)
             if current_h is not None:
                 img.drawHeight = current_h
                 img.drawWidth = current_w
             else:
                 current_h = img.drawHeight
                 current_w = img.drawWidth
             _, new_current_h = img.wrapOn(self.pdf, current_w, current_h)
             img.drawOn(self.pdf, current_x,
                        self.height - current_y - current_h)
             self.position_y = current_y + max(new_current_h, current_h)
             return img
         finally:
             if img_file is not None:
                 img_file.close()
     else:
         return None
コード例 #19
0
    def createDocument(self, canvas, doc):
        """
		Create the document
		"""
        self.c = canvas
        normal = self.styles["Normal"]
        centered = ParagraphStyle(name="centered", alignment=TA_CENTER)

        logo = imgPath + "khatemalogo.jpg"
        img = Image(logo, 50, 50)
        img.wrapOn(self.c, self.width, self.height)
        img.drawOn(self.c, *self.coord(10, 20, mm))

        header_text = "<font size=12><b>Khatmah Medical Factory</b></font>"
        p = Paragraph(header_text, normal)
        p.wrapOn(self.c, self.width, self.height)
        p.drawOn(self.c, *self.coord(30, 8, mm))

        ptext = "<font size=7><a>For the manufacture and maintenance of </a></font>"
        p = Paragraph(ptext, normal)
        p.wrapOn(self.c, self.width, self.height)
        p.drawOn(self.c, *self.coord(30, 13, mm))

        ptext = "<font size=7><a>tools support for people with special needs</a></font>"
        p = Paragraph(ptext, style=normal)
        p.wrapOn(self.c, self.width, self.height)
        p.drawOn(self.c, *self.coord(30, 16, mm))

        ptext = "<font size=8><a><b>First factory is specialized in the Gulf region</b></a></font>"
        p = Paragraph(ptext, style=normal)
        p.wrapOn(self.c, self.width, self.height)
        p.drawOn(self.c, *self.coord(30, 22, mm))

        ptext = "<font size=9><a><b>A Great Hope & Unlimited Ambition</b></a></font>"
        p = Paragraph(ptext, style=normal)
        p.wrapOn(self.c, self.width, self.height)
        p.drawOn(self.c, *self.coord(148, 22, mm))

        self.c.line(*self.coord(10, 22, mm), *self.coord(202, 22, mm))

        ptext = '<font size=10><u><b>All Raw Material </b></u></font>'
        p = Paragraph(ptext, style=normal)
        p.wrapOn(self.c, self.width, self.height)
        p.drawOn(self.c, *self.coord(12, 30, mm))

        datetimestr = datetime.now()
        timestampstr = datetimestr.strftime('%Y-%m-%d %H:%M:%S')
        ptext = "<font size=6><a>{} - </a></font>".format(
            self.refile) + "<font size=6><a>{} </a></font>".format(
                timestampstr)
        p = Paragraph(ptext, style=normal)
        p.wrapOn(self.c, self.width, self.height)
        p.drawOn(self.c, *self.coord(10, 286, mm))

        self.c.line(*self.coord(10, 285, mm), *self.coord(202, 285, mm))
        ptext = '<font size=10><p>CR:1010421226 - PC: 13217 - Wasel : 7966 - Tel & Fax: 014151557 - Mob: 0505721609 <br/>Website: www.khatmahfactory.com - E-mail : [email protected] - 3rd Industrial Area - Riyadh - Saudi Arabia </p></font>'
        p = Paragraph(ptext, centered)
        p.wrapOn(self.c, self.width, self.height)
        p.drawOn(self.c, *self.coord(0, 295, mm))
コード例 #20
0
def header_footer(canvas, doc):
    canvas.saveState()

    footer = Image('./skpi/footer.png', 19 * cm, 2.5 * cm)
    w, h = footer.wrap(doc.width, doc.bottomMargin)
    footer.drawOn(canvas, doc.leftMargin, h)

    canvas.restoreState()
コード例 #21
0
ファイル: ug2.py プロジェクト: akmiller01/alexm-util
    def createDocument(self):
        """"""
        for page in self.e.findall("page"):
            for image in page.findall("image"):
                logo = Image(image.get("src"))
                logo.drawHeight = int(image.get("height"))
                logo.drawWidth = int(image.get("width"))
                logo.wrapOn(self.c, self.width, self.height)
                logo.drawOn(self.c, *self.coord(int(image.get("left")),int(image.get("top"))+int(image.get("height")) ))
            for text in page.findall("text"):
                if len(text.getchildren())==0:
                    font = self.fonts[text.get("font")]
                    style = ParagraphStyle(
                        'default',
                        fontName="Arial",
                        leading=int(font["size"])+7,
                        fontSize=font["size"],
                        textColor=font["color"],
                        backColor=font["background"],
                        firstLineIndent=int(font["indent"]),
                    )
                    self.createParagraph(text.text, int(text.get("left")), (int(text.get("top"))+int(text.get("height"))),style)
                else:
                    innerText = ElementTree.tostring(text.getchildren()[0])
                    font = self.fonts[text.get("font")]
                    style = ParagraphStyle(
                        'default',
                        fontName="Arial",
                        leading=int(font["size"])+7,
                        fontSize=font["size"],
                        textColor=font["color"],
                        backColor=font["background"],
                        firstLineIndent=int(font["indent"]),
                    )
                    self.createParagraph(innerText, int(text.get("left")), (int(text.get("top"))+int(text.get("height"))),style)
            for line in page.findall("line"):
                self.c.setDash(int(line.get("on")),int(line.get("off")))
                self.c.setStrokeColor(line.get("color"))
                self.c.line(int(line.get("x1")),self.height-int(line.get("y1")),int(line.get("x2")),self.height-int(line.get("y2")))
            for table in page.findall("table"):
                self.c.setDash(1,0)
                tabDat = dataDictionary[table.get("data")]
                if table.get("widths"):
                    colWidths = [float(width) for width in table.get("widths").split(",")]
                else:
                    colWidths = float(table.get("width"))/len(tabDat[0])
                if table.get("heights"):
                    rowHeights = [float(height) for height in table.get("heights").split(",")]
                else:
                    rowHeights = float(table.get("height"))/len(tabDat)
                t = Table(tabDat,colWidths,rowHeights,style=tableStyles[table.get("data")])
                t.wrapOn(self.c, self.width, self.height)
                t.drawOn(self.c, *self.coord(int(table.get("left")), int(table.get("top"))+int(table.get("height"))))

            self.c.showPage()
コード例 #22
0
def InsertImage(path, c, width, cursor):
    # Adjust aspect ratio
    img = utils.ImageReader(path)
    iw, ih = img.getSize()
    aspect = ih / float(iw)

    img = Image(path, width=width, height=(width * aspect))
    img.drawOn(c, 0, cursor)
    cursor -= img.imageHeight

    return cursor
コード例 #23
0
def headerFooter(canvas, doc):
    canvas.saveState()

    header = Image(f'./skmk/header.png', 19 * cm, 2.5 * cm)
    w, h = header.wrap(doc.width, 2.5 * cm)
    header.drawOn(canvas, 1 * cm, doc.height + 4 * cm)

    footer = Image(f'./skmk/footer.png', 19 * cm, 1.8 * cm)
    w, h = footer.wrap(doc.width, 2.5 * cm)
    footer.drawOn(canvas, 1 * cm, h - 1.5 * cm)

    canvas.restoreState()
コード例 #24
0
    def footer(cls, canvas, doc):
        #width, height = doc.pagesize
        #ptext = """<font name=times-roman size=16 color="#028654">Grow A better Tommorrow </font><img src="{LogoPath}" width="112.5" height="54.75"/>""".format(
        #	LogoPath= doc.logo_path_footer)
        #p = Paragraph(ptext, cls.LABEL_STYLE)
        #p.wrapOn(canvas, width, height)
        #p.drawOn(canvas, 250, 35)

        width, height = doc.pagesize
        img = Image(doc.logo_path_footer, width=160, height=75)
        img.wrapOn(canvas, width, height)
        x, y = doc.Position
        img.drawOn(canvas, x - 30, y)
コード例 #25
0
def get_letterhead_page(canvas, doc):
    # Save the state of our canvas so we can draw on it
    canvas.saveState()
    styles = getSampleStyleSheet()
    base_path = join(settings.BASE_DIR, 'static/assets/img/')

    logo = Image(base_path + 'logo.jpg', width=5 * cm, height=2.5 * cm)

    w, h = logo.wrap(doc.width, doc.topMargin)
    logo.drawOn(canvas, doc.leftMargin + 400, doc.height + doc.topMargin - 30)

    # Release the canvas
    canvas.restoreState()
コード例 #26
0
    def firstPageGraphics(canvas, doc):
        canvas.saveState()

        im = Image(signature, 5.8 * cm, 3.05 * cm)
        im.drawOn(canvas, 100, 100)
        canvas.setLineWidth(.3)
        canvas.line(45, 80, 550, 80)
        canvas.setFont('DejaVuB', 9)
        canvas.drawString(145, 65, footer1)
        canvas.setFont('DejaVu', 9)
        canvas.drawString(50, 50, footer2)
        # canvas.drawString(60, 35, footer3)
        canvas.restoreState()
コード例 #27
0
ファイル: tablas.py プロジェクト: yunica/python_pdf_edit
    def _encabezado(canvas, archivoPDF):
        """Guarde el estado de nuestro lienzo para que podamos aprovecharlo"""

        canvas.saveState()
        estilos = getSampleStyleSheet()

        # encabezado imagen
        encabezado_imagen = Image("LOGOCONDORCUNCA-min.png", 150, 169.63)
        anchura, altura = encabezado_imagen.wrap(archivoPDF.width, archivoPDF.topMargin)
        encabezado_imagen.drawOn(canvas, 200, 600)

        # Suelta el lienzo
        canvas.restoreState()
コード例 #28
0
    def create_header(self):
        logo_path = 'img\\logo.png'
        logo = Image(logo_path, 2.222 * inch, 1 * inch)
        logo.wrapOn(self.canvas, self.width, self.height)
        logo.drawOn(self.canvas, *self.coord(.5, 1.5, inch))

        ptext = '<font size=22><b>Soumission</b></font>'
        p = Paragraph(ptext, self.styles['Normal'])
        p.wrapOn(self.canvas, self.width, self.height)
        p.drawOn(self.canvas, *self.coord(3.5, 1))

        ptext = '''  <font size=10>
                    <b>Client:</b> MachinMachine <br/>
                    <b>Date:</b> {}<br/>
                    <b>Adresse:</b> 5 Rue des axes,<br/>
                    Granby, QC , J2J<br/>
                    <b>Tel:</b> (450) 123-1111<br/>
                    </font>
                    '''.format('01/01/2018')
        p = Paragraph(ptext, self.styles['Normal'])
        p.wrapOn(self.canvas, self.width, self.height)
        p.drawOn(self.canvas, *self.coord(1, 3, inch))

        ptext = '''  <font size=10>
                    <b>Fournisseur:</b> SuperShop <br/>
                    <b>Date:</b> {}<br/>
                    <b>Adresse:</b> 123 Rue des colonnes,<br/>
                    Granby, QC J2J<br/>
                    <b>Tel:</b> (450) 123-1234<br/>
                    </font>
                    '''.format('01/01/2018')
        p = Paragraph(ptext, self.styles['Normal'])
        p.wrapOn(self.canvas, self.width, self.height)
        p.drawOn(self.canvas, *self.coord(6, 3, inch))

        ptext = '''  <font size=10>
                    Monsieur Machin,<br/><br/>
                    Voici notre soumission pour l'usinage de vos beignes en titane<br/>
                    selon le dessin beignes_001293_revA.<br/><br/>
                    Prix: $1000.00 / chaque <br/>
                    Quantite: 1000 <br/>
                    Total: $1,000,000.00 <br/>
                    <br/>
                    Cordialement, <br/>
                    <br/>
                    Patrick Touchette
                    </font>
                    '''.format('01/01/2018')
        p = Paragraph(ptext, self.styles['Normal'])
        p.wrapOn(self.canvas, self.width, self.height)
        p.drawOn(self.canvas, *self.coord(1, 6, inch))
コード例 #29
0
    def add_header_footer_images(self):
        """ Load the header, footer and side by side imagery .
        """

        # Add the header images
        img_name = "%s/../resources/calibration_report_header.png" \
                   % self.dir_name
        img_head = Image(img_name)
        img_head.drawOn(self.canvas, *self.coord(0, 48, mm))

        img_name = "%s/../resources/calibration_report_footer.png" \
                   % self.dir_name
        img_foot = Image(img_name)
        img_foot.drawOn(self.canvas, *self.coord(0, 280, mm))
コード例 #30
0
 def header():
     c.setLineWidth(.3)
     c.setFont('Helvetica', 22)
     c.drawString(4 * cm, 27 * cm, 'SICOLAB')
     c.setFont('Helvetica', 14)
     c.drawString(4 * cm, 26 * cm, 'Reporte de Asignaturas')
     img = Image('static/images/logo_carrera.jpg',
                 width=2.5 * cm,
                 height=2.5 * cm)
     img.drawOn(c, 17 * cm, 25.6 * cm)
     img = Image('static/images/sicolab_logo.png',
                 width=3 * cm,
                 height=3 * cm)
     img.drawOn(c, 0.8 * cm, 25.2 * cm)
コード例 #31
0
    def header_footer(self, canvas, doc):
        canvas.saveState()
        height_adjust = self.add_banner(canvas, doc)

        # Document Header
        if self.pdf_components.get('hdr_image', None) and self.firstPage:
            header = Image(self.pdf_components.get('hdr_image'),
                           height=25 * mm,
                           width=191 * mm)
            header.drawOn(canvas, doc.rightMargin,
                          doc.height + doc.topMargin - 15 * mm)
            self.firstPage = False
        elif self.firstPage:
            header = Paragraph(self.pdf_components.get('hdr_html', ''),
                               self.style['centered'])
            w, h = header.wrap(doc.width, doc.topMargin)
            header.drawOn(canvas, doc.leftMargin,
                          doc.height + doc.topMargin - height_adjust * h)

        # Document Footer
        if self.pdf_components.get('ftr_image', None):
            footer = Image(self.pdf_components.get('ftr_image'), 8.5 * inch,
                           1.8 * inch)
            footer.drawOn(canvas, 0, 0)
        else:
            footer = Paragraph(self.pdf_components.get('ftr_html', ''),
                               self.style['centered'])
            w, h = footer.wrap(doc.width, doc.bottomMargin)
            footer.drawOn(canvas, doc.leftMargin, height_adjust * h)

        # Release the Canvas
        canvas.restoreState()
コード例 #32
0
ファイル: bb.py プロジェクト: nagendragd/BalanceBendersMath
    def writeHint(self, canv, hint):
        bal = "../images/balance2.jpg"
        im = Image(bal, 5.5*inch, 0.75*inch)
        self.x = self.left_margin
        y=self.y
        im.drawOn(canv, self.x, self.y-self.hint_height)

        # now place the non-zero coeff shapes on the scales
        self.placeShapes(canv, hint.lhs)
        self.x = self.right_scale_x
        self.placeShapes(canv, hint.rhs)

        self.y = y - self.hint_height
        self.y -= self.spacing
コード例 #33
0
def capa(canvas, doc):
    cabecalho = Image('static/topFrame.png', 535, 63)
    w, h = cabecalho.wrap(doc.width, doc.topMargin)
    cabecalho.drawOn(canvas, doc.leftMargin + 5, doc.height + doc.topMargin - 40)

    canvas.setFont('Helvetica', 14)
    canvas.setFillColor(HexColor('#3366cc'))
    canvas.drawRightString(560, 220, doc_config['laudo'])
    canvas.setFont('Helvetica', 10)
    canvas.setFillColor(HexColor('#6a6a6a'))
    canvas.drawRightString(560, 180, doc_config['nome'])
    canvas.setFillColor(HexColor('#6a6a6a'))
    canvas.drawRightString(560, 160, doc_config['empresa'])
    canvas.setFillColor(HexColor('#6a6a6a'))
    canvas.drawRightString(560, 140, doc_config['cargo'])
コード例 #34
0
def capa(canvas, doc):
    cabecalho = Image('static/topFrame.png', 535, 63)
    w, h = cabecalho.wrap(doc.width, doc.topMargin)
    cabecalho.drawOn(canvas, doc.leftMargin + 5,
                     doc.height + doc.topMargin - 40)

    canvas.setFont('Helvetica', 14)
    canvas.setFillColor(HexColor('#3366cc'))
    canvas.drawRightString(560, 220, doc_config['laudo'])
    canvas.setFont('Helvetica', 10)
    canvas.setFillColor(HexColor('#6a6a6a'))
    canvas.drawRightString(560, 180, doc_config['nome'])
    canvas.setFillColor(HexColor('#6a6a6a'))
    canvas.drawRightString(560, 160, doc_config['empresa'])
    canvas.setFillColor(HexColor('#6a6a6a'))
    canvas.drawRightString(560, 140, doc_config['cargo'])
コード例 #35
0
ファイル: pdf_builder.py プロジェクト: acounsel/scorecard
def _header(canvas, doc):
    # Save the state of our canvas so we can draw on it
    canvas.saveState()

    # Header
    header_url = 'Accountability+Counsel_Logo_Color+(2).png'
    header = Image('{0}{1}'.format(file_url, header_url),
                   width=112.3,
                   height=29)
    header.hAlign = 'RIGHT'

    w, h = header.wrap(doc.width, doc.topMargin)
    header.drawOn(canvas, w + 530, doc.height + doc.topMargin - h)

    # Release the canvas
    canvas.restoreState()
コード例 #36
0
 def enTestePremiehrePage(self, canvas, doc):
     self.numeroPage += 1
     canvas.saveState()
     imageLogo = '%s/echiquierLatejcon4T.png' % (path.dirname(__file__))
     latecon = Image(imageLogo, width=5.51 * cm, height=2.00 * cm)
     latecon.drawOn(canvas, 1 * cm, A4[1] - (3 * cm))
     doc.handle_nextPageTemplate('pageSuivante')
     basdepageStyle = ParagraphStyle('basdepage')
     basdepageStyle.fontName = 'Helvetica-Bold'
     basdepageStyle.fontSize = 7
     basdepageStyle.textColor = 'black'
     basdepage = Paragraph(
         'Sudoku anthropomorphique de la grille %s' % (self.identifiant),
         basdepageStyle)
     basdepage.wrap(doc.width, doc.bottomMargin)
     basdepage.drawOn(canvas, doc.leftMargin, 1 * cm)
     canvas.restoreState()
コード例 #37
0
    def _header_footer(self, canvas, doc):
        # Save the state of our canvas so we can draw on it
        canvas.saveState()

        style_right = ParagraphStyle(name='right',
                                     parent=self.bodystyle,
                                     fontName='arialuni',
                                     fontSize=10,
                                     alignment=TA_RIGHT)

        fieldsight_logo = Image('http://' + self.base_url +
                                '/static/images/fs1.jpg')
        fieldsight_logo._restrictSize(1.5 * inch, 1.5 * inch)

        # headerleft = Paragraph("FieldSight", self.bodystyle)
        headerright = Paragraph(self.project_name, style_right)

        # w1, h1 = headerleft.wrap(doc.width, doc.topMargin)
        w2, h2 = headerright.wrap(doc.width, doc.topMargin)

        textWidth = stringWidth(self.project_name,
                                fontName='arialuni',
                                fontSize=10)

        fieldsight_logo.drawOn(canvas, doc.leftMargin,
                               doc.height + doc.topMargin + 12)
        headerright.drawOn(canvas, doc.leftMargin,
                           doc.height + doc.topMargin + 20)
        try:
            project_logo = Image(self.project_logo)
            project_logo._restrictSize(0.4 * inch, 0.4 * inch)
            project_logo.drawOn(
                canvas,
                headerright.width + doc.leftMargin - 0.5 * inch - textWidth,
                doc.height + doc.topMargin + 10)
        except:
            pass
        # header.drawOn(canvas, doc.leftMargin + doc.width, doc.height + doc.topMargin +20)

        # Footer
        footer = Paragraph('Page no. ' + str(canvas._pageNumber), style_right)
        w, h = footer.wrap(doc.width, doc.bottomMargin)
        footer.drawOn(canvas, doc.leftMargin, h + 40)

        # Release the canvas
        canvas.restoreState()
コード例 #38
0
    def _header_footer(canvas, doc):
        canvas.saveState()
        styles = getSampleStyleSheet()
        canvas.setFont("DejaVu Sans", 7)

        im = Image('assets/images/TaT_DF_LOGO.png')
        im._restrictSize(1000 * mm, 30 * mm)
        im.drawOn(canvas, doc.leftMargin, doc.height - 20 * mm)

        # Footer
        canvas.drawRightString(
            doc.width + doc.rightMargin, 10 * mm,
            'Falls Probleme auftreten, schreiben Sie eine E-Mail an [email protected]'
        )

        # Release the canvas
        canvas.restoreState()
コード例 #39
0
def _header_footer(canvas, doc):
        # Save the state of our canvas so we can draw on it
        canvas.saveState()
        # Header
        png_path=os.path.dirname(__file__)+os.path.sep+'static'+os.path.sep+'images'+os.path.sep+'nutanixlogo.png'
        loggerObj.LogMessage("info",file_name + " :: PNG File path - " + png_path)        
        header = Image(png_path, height=0.50 * inch, width=5 * cm)
        w, h = header.wrap(doc.width, doc.topMargin)
        header.drawOn(canvas, doc.leftMargin, doc.height + doc.topMargin - h)
        
 
        # Footer
        
        footer = Paragraph('Tel: 1 (855) 688-2649 | Fax: 1 (408) 916-4039 | Email: [email protected]. &copy 2014 Nutanix, Inc. All Rights Reserved.', FooterMsgStyle)
        w, h = footer.wrap(doc.width, doc.bottomMargin) 
        footer.drawOn(canvas, doc.leftMargin, h) 
        # Release the canvas
        canvas.restoreState()
コード例 #40
0
def cabecera(canvas, datos_de_la_empresa):
    """
    Escribe el texto «CERTIFICADO DE CALIDAD», el logotipo de la empresa, una 
    imagen de geotextiles y un par de rayajos de adorno.
    """
    fuente = "Helvetica-Bold"
    tamanno = 12
    canvas.saveState()
    canvas.setFont(fuente, tamanno)
    canvas.drawCentredString(PAGE_WIDTH / 2.0 + 1*cm, 
                             PAGE_HEIGHT - 2 * cm, 
                             escribe("CERTIFICADO DE CALIDAD"))
    canvas.restoreState()
    rutalogo = datos_de_la_empresa.logo
    if rutalogo:
        rutalogo = os.path.join("..", "imagenes", rutalogo)
        logo = Image(rutalogo)
        logo.drawHeight = 2*cm * logo.drawHeight / logo.drawWidth
        logo.drawWidth = 2*cm
        logo.drawOn(canvas, 2.75*cm, PAGE_HEIGHT - 1*cm - 2*cm)
    # OJO: Foto de geotextiles HARCODED.
    rutafoto = os.path.join("..", "imagenes", "foto_geotextiles.jpg")
    foto = Image(rutafoto)
    foto.drawHeight = 2*cm * foto.drawHeight / foto.drawWidth
    foto.drawWidth = 2*cm
    foto.drawOn(canvas, PAGE_WIDTH - 5*cm, PAGE_HEIGHT - 2.75*cm - 2*cm)
    canvas.saveState()
    canvas.setStrokeColor(colors.green)
    canvas.rect(PAGE_WIDTH - 5*cm, PAGE_HEIGHT - 2.75*cm - 2*cm, 2*cm, 2*cm)
    ## XXX: Esto de ahora es un poco chapuza, y como cambie algún margen se va 
    ## al carajo este trocito de línea que se supone que debería ser parte de 
    ## la sección Denominación.
    canvas.line(PAGE_WIDTH - 5*cm + 2*cm, PAGE_HEIGHT - 3.25*cm, 
                PAGE_WIDTH - 5*cm + 2.25*cm, PAGE_HEIGHT - 3.25*cm)
    ## XXX: EOChapuza
    canvas.restoreState()
    canvas.line(5*cm, PAGE_HEIGHT - 1*cm, # (x1, y1)
                5*cm, PAGE_HEIGHT - 2.5*cm) # (x2, y2)
    canvas.line(PAGE_WIDTH - 3*cm, PAGE_HEIGHT - 1*cm, # (x1, y1)
                PAGE_WIDTH - 3*cm, PAGE_HEIGHT - 2.5*cm) # (x2, y2)
    # En la primera página también debe ir el pie
    pie(canvas, datos_de_la_empresa)
コード例 #41
0
    def add_coefficients(self, report):
        """ Add the calibration equation image, as well as the
        calibration coefficients defined in the report object.
        """
        img_name = "%s/../resources/calibration_text_and_equation.png" \
                   % self.dir_name
        img_equ = Image(img_name)
        img_equ.drawOn(self.canvas, *self.coord(40, 180, mm)) 

        pfx_txt = "Where 'p' is pixel index, and:"
        self.create_paragraph(pfx_txt, 60, 190)

        c0_txt = "Coefficient <b>C0 =</b> %s" % report.coefficient_0
        self.create_paragraph(c0_txt, 60, 200)
        c1_txt = "Coefficient <b>C1 =</b> %s" % report.coefficient_1
        self.create_paragraph(c1_txt, 60, 208)
        c2_txt = "Coefficient <b>C2 =</b> %s" % report.coefficient_2
        self.create_paragraph(c2_txt, 60, 216) 
        c3_txt = "Coefficient <b>C3 =</b> %s" % report.coefficient_3
        self.create_paragraph(c3_txt, 60, 224)
コード例 #42
0
ファイル: views.py プロジェクト: mkates/devicecove
def _header_footer(canvas, doc):
    # Save the state of our canvas so we can draw on it
    canvas.saveState()
    styles = getSampleStyleSheet()
    styles.add(ParagraphStyle(name='Light', fontName='Helvetica',alignment=TA_CENTER,fontSize=6,leading=8,textColor=colors.Color(0,0,0,.5)))

    # Header
    #header = Paragraph('This is our obligatory message that we attach to the bottom of every one of our pages. This information is intended for the Veterinary Clinic.', styles['Normal'])

    # Background Image 
    img2 = Image('/Users/alexanderkates/Dropbox/WebProjects/medbay/medapp/static/img/pdf/pdfbackground.jpg',width=8.5*inch,height=11*inch)
    img2.drawOn(canvas,0,0)

    # Footer
    footer = Paragraph('This report was generated by Vetcove on August 25th, 2014. Information in this report is subject to change, and is strictly intended for the viewing by Colts Neck Equine. For more information, contact Vetcove directly at www.vetcove.com, via email at [email protected], or py phone at 732.598.6434', styles['Light'])
    w, h = footer.wrap(doc.width, doc.bottomMargin)
    footer.drawOn(canvas, doc.leftMargin, h+20)

    # Release the canvas
    canvas.restoreState()
コード例 #43
0
ファイル: generar.py プロジェクト: bojack5/metrology
    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()
コード例 #44
0
ファイル: generar.py プロジェクト: bojack5/metrology
    def _header_factura(canvas,doc):
        #guardamos el estado de nuestro canvas , para poder dibujar en el 
        canvas.saveState()
        canvas.setTitle("Factura")
        styles = getSampleStyleSheet()

        #header
        header = Image('/home/borbolla/metrology/static_media/assets/images/logo_servicio.png' )
        header.drawHeight = 70
        header.drawWidth = 399
        header.hAlign = 'RIGHT'
        w , h = header.wrap(doc.width , doc.topMargin)
        header.drawOn(canvas , doc.leftMargin , 700)
        
        

        # 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()
コード例 #45
0
ファイル: render.py プロジェクト: akmiller01/alexm-util
    def createDocument(self):
        """"""
        for page in self.e.findall("page"):
            for image in page.findall("image"):
                if image.get("variable")=="True":
                    src = image.get("path")+self.country+"/"+image.get("src")
                    dest = image.get("path")+self.country+"/reduced_"+image.get("src")
                    pilImg = PILImage.open(src)
                    size = (pilImg.size[0]/1.5,pilImg.size[1]/1.5)
                    pilImg.thumbnail(size,PILImage.NEAREST)
                    pilImg.save(dest,optimize=True)
                else:
                    src = image.get("path")+image.get("src")
                    dest = src
                # logo = Image(dest)
                logo = Image(src)
                logo.drawHeight = int(image.get("height"))
                logo.drawWidth = int(image.get("width"))
                logo.wrapOn(self.c, self.width, self.height)
                logo.drawOn(self.c, *self.coord(int(image.get("left")),int(image.get("top"))+int(image.get("height")) ))
            for text in page.findall("text"):
                if len(text.getchildren())==0:
                    font = self.fonts[text.get("font")]
                    if text.get("replace"):
                        replacement = dataDictionary[self.country][text.get("replace")]
                    else:
                        replacement = text.text
                        
                    if text.get("shrink"):
                        fontSize = float(font["size"])
                        height = int(text.get("height"))
                        textLen = float(len(replacement))
                        divisor = max(((textLen/25.0)+(2.0/3.0)),1)
                        fontSizeAdj = int(fontSize / divisor)
                        fontSizeDiff = int(float(fontSize-fontSizeAdj)/2.0)
                        heightAdj = height-fontSizeDiff
                    else:
                        fontSizeAdj = int(font["size"])
                        heightAdj = int(text.get("height"))
                        
                    style = ParagraphStyle(
                        'default',
                        fontName="Arial",
                        leading=fontSizeAdj,
                        fontSize=fontSizeAdj,
                        borderPadding = int(font["padding"]),
                        textColor=font["color"],
                        backColor=font["background"],
                        firstLineIndent=int(font["indent"]),
                    )
                    
                    self.createParagraph(replacement, int(text.get("left")), (int(text.get("top"))+heightAdj),style)
                else:
                    innerText = ElementTree.tostring(text.getchildren()[0])
                    font = self.fonts[text.get("font")]
                    if text.get("replace"):
                        replacement = dataDictionary[self.country][text.get("replace")]
                    else:
                        replacement = innerText
                        
                    if text.get("shrink"):
                        fontSize = float(font["size"])
                        height = int(text.get("height"))
                        textLen = float(len(replacement))
                        divisor = max(((textLen/25.0)+(2.0/3.0)),1)
                        fontSizeAdj = int(fontSize / divisor)
                        fontSizeDiff = int(float(fontSize-fontSizeAdj)/2.0)
                        heightAdj = height-fontSizeDiff
                    else:
                        fontSizeAdj = int(font["size"])
                        heightAdj = int(text.get("height"))
                        
                    style = ParagraphStyle(
                        'default',
                        fontName="Arial",
                        leading=fontSizeAdj,
                        fontSize=fontSizeAdj,
                        borderPadding = int(font["padding"]),
                        textColor=font["color"],
                        backColor=font["background"],
                        firstLineIndent=int(font["indent"]),
                    )
                    
                    self.createParagraph(replacement, int(text.get("left")), (int(text.get("top"))+heightAdj),style)
            for line in page.findall("line"):
                self.c.setDash(int(line.get("on")),int(line.get("off")))
                self.c.setStrokeColor(line.get("color"))
                self.c.line(int(line.get("x1")),self.height-int(line.get("y1")),int(line.get("x2")),self.height-int(line.get("y2")))
            for table in page.findall("table"):
                self.c.setDash(1,0)
                tabDat = dataDictionary[self.country][table.get("data")]
                if table.get("widths"):
                    colWidths = [float(width) for width in table.get("widths").split(",")]
                else:
                    colWidths = float(table.get("width"))/len(tabDat[0])
                if table.get("heights"):
                    rowHeights = [float(height) for height in table.get("heights").split(",")]
                else:
                    rowHeights = float(table.get("height"))/len(tabDat)
                t = Table(tabDat,colWidths,rowHeights,style=tableStyles[table.get("data")])
                t.wrapOn(self.c, self.width, self.height)
                t.drawOn(self.c, *self.coord(int(table.get("left")), int(table.get("top"))+int(table.get("height"))))

            self.c.showPage()
コード例 #46
0
def cabecalho(canvas, doc):
    cabecalho = Image('static/topFrame.png', 535, 63)
    w, h = cabecalho.wrap(doc.width, doc.topMargin)
    cabecalho.drawOn(canvas, doc.leftMargin + 5, doc.height + doc.topMargin - 40)
コード例 #47
0
ファイル: pdf.py プロジェクト: stephanekirsch/e-colle
def creditsects(form,elev,classe):
	"""renvoie les crédits ects pdf de l'élève elev, ou si elev vaut None renvoie les crédits ects pdf de toute la classe en un seul fichier"""
	datedujour = form.cleaned_data['date'].strftime('%d/%m/%Y')
	filiere,annee = form.cleaned_data['classe'].split("_")
	signataire = form.cleaned_data['signature']
	etoile = form.cleaned_data['etoile']
	tree=etree.parse(join(RESOURCES_ROOT,'classes.xml')).getroot()
	classexml=tree.findall("classe[@nom='{}'][@annee='{}']".format(filiere,annee)).pop()
	domaine = classexml.get("domaine")
	branche = classexml.get("type").lower()
	precision = classexml.get("precision")
	signature = False
	if 'tampon' in form.cleaned_data:
		signature = form.cleaned_data['tampon']
	LIST_NOTES="ABCDEF"
	response = HttpResponse(content_type='application/pdf')
	if elev is None:
		eleves = Eleve.objects.filter(classe=classe).order_by('user__last_name','user__first_name').select_related('user')
		nomfichier="ECTS_{}.pdf".format(unidecode(classe.nom)).replace(" ","-").replace('*','etoile')
		credits = NoteECTS.objects.credits(classe)[0]
	else:
		eleves=[elev]
		credits=[False]
		nomfichier=unidecode("ECTS_{}_{}_{}.pdf".format(classe.nom.upper(),elev.user.first_name,elev.user.last_name.upper())).replace(" ","-")
	response['Content-Disposition'] = "attachment; filename={}".format(nomfichier)
	pdf = easyPdf()
	cm = pdf.format[0]/21
	pdf.marge_x = cm # 1cm de marge gauche/droite
	pdf.marge_y = 1.5*cm # 1,5cm de marge haut/bas
	I = Image(join(RESOURCES_ROOT,'marianne.jpg'))
	I.drawHeight = 1.8*cm
	I.drawWidth = 3*cm
	if signature and signataire == 'Proviseur':
		try:
			I2 = Image(join(RESOURCES_ROOT,'proviseur.png'))
		except Exception:
			try:
				I2 = Image(join(RESOURCES_ROOT,'proviseur.png'))
			except Exception:
				I2 = False
	elif signature and signataire == 'Proviseur adjoint':
		try:
			I2 = Image(join(RESOURCES_ROOT,'proviseuradjoint.png'))
		except Exception:
			try:
				I2 = Image(join(RESOURCES_ROOT,'proviseuradjoint.png'))
			except Exception:
				I2 = False
	else:
		I2 = False
	if I2:
		I2.drawHeight = 3*cm
		I2.drawWidth = 3*cm
	newpage = False
	style=ParagraphStyle(name='normal',fontSize=9,leading=11,spaceAfter=5)
	styleResume=ParagraphStyle(name='resume',fontSize=9,leading=11,spaceAfter=0)
	styleTitre=ParagraphStyle(name='titre',fontSize=12,leading=13,fontName="Helvetica-Bold",borderColor='black',borderPadding=(0,0,2,0),borderWidth=1,backColor='#DDDDDD',spaceAfter=2)
	data1 = [["A","Très Bien","C","Assez Bien","E","Passable"],["B","Bien","D","Convenable","F","Insuffisant"]]
	LIST_STYLE1 = TableStyle([('GRID',(0,0),(-1,-1),.2,(0,0,0))
								,('VALIGN',(0,0),(-1,-1),'MIDDLE')
								,('ALIGN',(0,0),(-1,-1),'CENTRE')
								,('FACE',(0,0),(-1,-1),'Helvetica')
								,('SIZE',(0,0),(-1,-1),8)
								,('BACKGROUND',(0,0),(-1,-1),(.9,.9,.9))])
	t1=Table(data1,colWidths=[.8*cm,2*cm,.8*cm,2*cm,.8*cm,2*cm],rowHeights=[12]*2)
	t1.setStyle(LIST_STYLE1)
	data2 = [["8","D","","Université","",""],["7","D","","Université","",""],["6","D","","Université","",""],\
			["5","M","","Université ou grande école","",""],["4","M","","Université ou grande école","",""],["3","L","ATS","Université ou grande école","",""],\
			["2","L","STS-IUT","","Université","CPGE"],["1","L","STS-IUT","","Université","CPGE"],["0","Bac","Enseignement secondaire","","",""]]
	LIST_STYLE2 = TableStyle([('GRID',(0,0),(1,4),.8,(0,0,0))
								,('GRID',(3,0),(5,4),.8,(0,0,0))
								,('GRID',(0,5),(5,8),.8,(0,0,0))
								,('VALIGN',(0,0),(-1,-1),'MIDDLE')
								,('ALIGN',(0,0),(-1,-1),'CENTRE')
								,('FACE',(0,0),(-1,-1),'Helvetica-Bold')
								,('SIZE',(0,0),(-1,-1),8)
								,('BACKGROUND',(0,0),(-1,-1),(1,1,1))
								,('SPAN',(3,0),(5,0))
								,('SPAN',(3,1),(5,1))
								,('SPAN',(3,2),(5,2))
								,('SPAN',(3,3),(5,3))
								,('SPAN',(3,4),(5,4))
								,('SPAN',(3,5),(5,5))
								,('SPAN',(2,6),(3,6))
								,('SPAN',(2,7),(3,7))
								,('SPAN',(2,8),(5,8))
								,('BACKGROUND',(3,0),(5,2),'#FABF8F')
								,('BACKGROUND',(3,3),(5,4),'#FBD4B4')
								,('BACKGROUND',(2,5),(2,5),'#76923C')
								,('BACKGROUND',(3,5),(5,5),'#FDE9D9')
								,('BACKGROUND',(4,6),(4,7),'#FDE9D9')
								,('BACKGROUND',(2,6),(3,7),'#D6E3BC')
								,('BACKGROUND',(5,6),(5,7),'#FF9900')])
	t2=Table(data2,colWidths=[.84*cm,.91*cm,.75*cm,1.4*cm,2.5*cm,2.5*cm],rowHeights=[.8*cm]*9)
	t2.setStyle(LIST_STYLE2)
	texte="1. Information sur l'étudiant"
	p1=Paragraph(texte,styleTitre)
	texte="2. Information sur la formation"
	p3=Paragraph(texte,styleTitre)
	texte="3. Information sur le niveau de la formation"
	p5=Paragraph(texte,styleTitre)
	texte="""<b><i>3.1. Niveau de la formation:</i></b><br/>
	Située au sein des études menant au grade de licence.<br/>
	Niveau bac + 2 / 120 crédits ECTS<br/>
	<b><i>3.2. Durée officielle du programme de formation:</i></b><br/>
	La durée du programme est de 2 ans.<br/>
	<b><i>3.3. Conditions d’accès:</i></b><br/>
	Entrée sélective après le baccalauréat s’effectuant dans le cadre d’une procédure nationale d’admission.<br/>
	Cf: <a href="http://www.parcoursup.fr" color="blue">http://www.parcoursup.fr</a>"""
	p6=Paragraph(texte,style)
	texte="""4. Information sur les contenus et les résultats obtenus"""
	p7=Paragraph(texte,styleTitre)
	texte="""<b><i>4.1. Organisation des études:</i></b><br/>
	Plein temps, contrôle continu écrit et oral<br/>
	<b><i>4.2. Exigences du programme:</i></b><br/>
	La formation dispensée a pour objet de donner aux étudiants une compréhension approfondie des disciplines enseignées et une appréhension de leurs caractéristiques générales. Elle prend en compte leurs évolutions, leurs applications et la préparation à des démarches de recherche.
	Elle est définie par des programmes nationaux.<br/>
	<b><i>4.3. Précisions sur le programme:</i></b><br/>
	Voir relevé au verso et catalogue de cours<br/>
	<b><i>4.4. Échelle d’évaluation:</i></b><br/>
	L’évaluation prend en compte l’ensemble des travaux des étudiants. La qualité du travail, des résultats obtenus et des compétences acquises est exprimée par une mention conformément au tableau ci-dessous."""
	p8=Paragraph(texte,styleResume)
	texte="""<b><i>4.5. Classification de la formation:</i></b><br/>
	Une mention globale, portant sur l’ensemble du parcours et s’exprimant dans la même échelle qu’en 4.4 figure à la fin du relevé."""
	p9=Paragraph(texte,style)
	texte="5. Information sur la fonction de la qualification"
	p10=Paragraph(texte,styleTitre)
	texte="""<b><i>5.1. Accès à un niveau d’études supérieur:</i></b><br/>
	Accès par concours aux grandes écoles.<br/>
	Accès, par validation de parcours, à tout type d’établissement d’enseignement supérieur.<br/>
	<b><i>5.2. Statut  professionnel (si applicable):</i></b><br/>
	Sans objet"""
	p11=Paragraph(texte,style)
	texte="6. Informations complémentaires"
	p12=Paragraph(texte,styleTitre)
	texte="""<b><i>6.1. Informations complémentaires:</i></b><br/>
	Catalogue des cours et arrêtés ministériels définissant les programmes consultables sur :<br/>
	<a href="http://www.enseignementsup-recherche.gouv.fr/" color="blue">http://www.enseignementsup-recherche.gouv.fr/</a><br/>
	<b><i>6.2. Autres sources d’information:</i></b><br/>
	Pour toute information sur le dispositif CPGE consulter :<br/>
	<a href="http://www.enseignementsup-recherche.gouv.fr/" color="blue">http://www.enseignementsup-recherche.gouv.fr/</a>"""
	p13=Paragraph(texte,style)
	texte="7. Certification de l’attestation"
	p14=Paragraph(texte,styleTitre)
	texte="8. Informations sur le système national d’enseignement supérieur"
	p16=Paragraph(texte,styleTitre)
	p17=Paragraph("<br/> <br/>",style)
	for eleve,credit in zip(eleves,credits):
		if elev or credit and credit['ddn'] and credit['ine'] and credit['sem1']==30 and credit['sem2']==30: # si l'élève a bien toutes les infos/crédits
			if newpage:# si ce n'est pas la première page, on change de page
				pdf.showPage()
			pdf.y = pdf.format[1]-pdf.marge_y-1.8*cm
			I.drawOn(pdf,9*cm,pdf.y)
			pdf.y -= 10
			pdf.setFont("Times-Roman",7)
			pdf.drawCentredString(10.5*cm,pdf.y, "MINISTÈRE DE L'ÉDUCATION NATIONALE")
			pdf.y -= 8
			pdf.drawCentredString(10.5*cm,pdf.y, "DE l'ENSEIGNEMENT SUPÉRIEUR ET DE LA RECHERCHE")
			pdf.y -= 12
			pdf.setFont("Helvetica-Bold",11)
			pdf.drawCentredString(10.5*cm,pdf.y,"CLASSES PRÉPARATOIRES AUX GRANDES ÉCOLES")
			pdf.y -= 12
			pdf.setFont("Helvetica",11)
			pdf.drawCentredString(10.5*cm,pdf.y,"ANNEXE DESCRIPTIVE DE LA FORMATION")
			story=[p1]
			texte="<b><i>1.1. Nom:</i></b> {}<br/><b><i>1.2. Prénom:</i></b> {}<br/><b><i>1.3. Date de Naissance:</i></b> {}<br/><b><i>1.4. Lieu de Naissance:</i></b> {}<br/><b><i>1.5. N° INE:</i></b> {}".format(eleve.user.last_name.upper(),eleve.user.first_name.title(),"" if not eleve.ddn else eleve.ddn.strftime('%d/%m/%Y'),"" if not eleve.ldn else eleve.ldn.title(),eleve.ine)
			p2=Paragraph(texte,style)
			story.extend([p2,p3])
			texte="""<b><i>2.1. Nom de la formation:</i></b><br/>
			Classe préparatoire {} {} {}<br/>
			<b><i>2.2. Principaux domaines d’étude:</i></b><br/>
			{}<br/>
			<b><i>2.3. Nom et statut de l’institution gérant la formation:</i></b><br/>
			Ministère de l’enseignement supérieur et de la recherche
			Classes préparatoires aux grandes écoles<br/>
			<b><i>2.4. Nom et statut de l’établissement dispensant la formation:</i></b><br/>
			{}<br/>
			<b><i>2.5. Langue de formation:</i></b> français""".format(branche,filiere,"("+precision+")" if precision else "",domaine,Config.objects.get_config().nom_adresse_etablissement.replace("\n","<br/>").replace("\r","<br/>").replace("<br/><br/>","<br/>"))
			p4=Paragraph(texte,style)
			story.extend([p4,p5,p6,p7,p8,t1,p9])
			fl = Frame(cm, 1.5*cm, 9*cm, 23*cm , showBoundary=0, leftPadding=0, rightPadding=0, topPadding=0, bottomPadding=0)
			fl.addFromList(story,pdf)
			story=[p10,p11,p12,p13,p14]
			texte="""<b><i>7.1. Date:</i></b> {}<br/>
			<b><i>7.2. Signature:</i></b><br/><br/><br/><br/>
			<b><i>7.3. Fonction:</i></b> {}<br/>
			<b><i>7.4. Tampon ou cachet officiel:</i></b><br/><br/><br/><br/><br/><br/>""".format(datedujour,signataire)
			p15=Paragraph(texte,style)
			story.extend([p15,p16,p17,t2])
			fr = Frame(11*cm, 1.5*cm, 9*cm, 23*cm , showBoundary=0, leftPadding=0, rightPadding=0, topPadding=0, bottomPadding=0)
			fr.addFromList(story,pdf)
			if I2:
				I2.drawOn(pdf,16.2*cm,13.2*cm)
			pdf.showPage()
			pdf.y = pdf.format[1]-pdf.marge_y-12
			pdf.setFont('Helvetica-Bold',12)
			pdf.drawCentredString(10.5*cm,pdf.y,"RELEVÉ DE RÉSULTATS (classe {})".format(filiere + ('*' if etoile and classe.annee == 2 else '')))
			sem1,sem2 = NoteECTS.objects.notePDF(eleve)
			data=[["ENSEIGNEMENTS","Crédits ECTS","Mention"],["Premier semestre","",""]]
			sp=0 # variable qui va contenir la somme pondérée des notes en vue du calcul de la mention globale
			coeff = 0 # somme des coeffs pour vérifier si on en a 60 au total
			for note in sem1:
				data.append([note[0] + ("" if not note[1] else " ({})".format(note[1])),note[2],LIST_NOTES[note[4]]])
				sp+=note[2]*note[4]
				if note[4] !=5:
					coeff+=note[2]
			data.append(["Deuxième semestre","",""])
			for note in sem2:
				data.append([note[0] + ("" if not note[1] else " ({})".format(note[1])),note[3],LIST_NOTES[note[4]]])
				sp+=note[3]*note[4]
				if note[4] !=5:
					coeff+=note[3]
			LIST_STYLE = TableStyle([('GRID',(0,0),(-1,-1),.8,(0,0,0))
										,('SPAN',(0,1),(2,1))
										,('SPAN',(0,2+len(sem1)),(2,2+len(sem1)))
										,('FACE',(0,0),(-1,-1),'Helvetica-Bold')
										,('SIZE',(0,0),(-1,-1),8)
										,('SIZE',(0,1),(2,1),9)
										,('SIZE',(0,2+len(sem1)),(2,2+len(sem1)),9)
										,('SIZE',(0,0),(2,0),10)
										,('VALIGN',(0,0),(-1,-1),'MIDDLE')
										,('ALIGN',(0,2),(0,-1),'LEFT')
										,('ALIGN',(1,0),(2,-1),'CENTRE')
										,('ALIGN',(0,0),(2,1),'CENTRE')
										,('ALIGN',(0,2+len(sem1)),(2,2+len(sem1)),'CENTRE')
										,('BACKGROUND',(0,1),(2,1),'#DDDDDD')
										,('BACKGROUND',(0,2+len(sem1)),(2,2+len(sem1)),'#DDDDDD')])
			t=Table(data,colWidths=[13*cm,2.8*cm,2.5*cm],rowHeights=[.8*cm]*(3+len(sem1)+len(sem2)))
			t.setStyle(LIST_STYLE)
			w,h=t.wrapOn(pdf,0,0)
			pdf.y-=h+5
			pdf.x=(pdf.format[0]-w)/2
			t.drawOn(pdf,pdf.x,pdf.y)
			pdf.y-=20
			pdf.setFont('Helvetica-Bold',10)
			if coeff == 60:
				pdf.drawString(pdf.x,pdf.y,"Mention globale: {}".format(LIST_NOTES[int(sp/60+.5)]))
			else:
				pdf.setFillColor((1,0,0))
				pdf.drawString(pdf.x,pdf.y,"Pas de mention, il manque {} crédits".format(60-coeff))
				pdf.setFillColor((0,0,0))
			pdf.drawRightString(pdf.format[0]-pdf.x-15,pdf.y,"Cachet et signature")
			pdf.y-= 3.2*cm
			if I2:
				I2.drawOn(pdf,pdf.format[0]-2*pdf.marge_x-3*cm,pdf.y)
			newpage=True
	pdf.save()
	fichier = pdf.buffer.getvalue()
	pdf.buffer.close()
	response.write(fichier)
	return response
コード例 #48
0
ファイル: pdf.py プロジェクト: stephanekirsch/e-colle
def attestationects(form,elev,classe):
	"""renvoie l'attestation ects pdf de l'élève elev, ou si elev vaut None renvoie les attestations ects pdf de toute la classe classe en un seul fichier"""
	datedujour = form.cleaned_data['date'].strftime('%d/%m/%Y')
	filiere = form.cleaned_data['classe'].split("_")[0]
	signataire = form.cleaned_data['signature']
	annee = form.cleaned_data['anneescolaire']
	etoile = form.cleaned_data['etoile']
	signature = False
	if 'tampon' in form.cleaned_data:
		signature = form.cleaned_data['tampon']
	config=Config.objects.get_config()
	annee = "{}-{}".format(int(annee)-1,annee)
	response = HttpResponse(content_type='application/pdf')
	if elev is None:
		eleves = Eleve.objects.filter(classe=classe).order_by('user__last_name','user__first_name').select_related('user')
		nomfichier="ATTESTATIONS_{}.pdf".format(unidecode(classe.nom)).replace(" ","-")
		credits = NoteECTS.objects.credits(classe)[0]
	else:
		eleves=[elev]
		credits=[False]
		nomfichier=unidecode("ATTESTATION_{}_{}_{}.pdf".format(elev.classe.nom.upper(),elev.user.first_name,elev.user.last_name.upper())).replace(" ","-")
	response['Content-Disposition'] = "attachment; filename={}".format(nomfichier)
	pdf = easyPdf()
	pdf.marge_x = cm # 1cm de marge gauche/droite
	pdf.marge_y = 1.5*cm # 1,5cm de marge haut/bas
	I = Image(join(RESOURCES_ROOT,'marianne.jpg'))
	I.drawHeight = 1.8*cm
	I.drawWidth = 3*cm
	if signature and signataire == 'Proviseur':
		try:
			I2 = Image(join(RESOURCES_ROOT,'proviseur.png'))
		except Exception:
			try:
				I2 = Image(join(RESOURCES_ROOT,'proviseur.png'))
			except Exception:
				I2 = False
	elif signature and signataire == 'Proviseur adjoint':
		try:
			I2 = Image(join(RESOURCES_ROOT,'proviseuradjoint.png'))
		except Exception:
			try:
				I2 = Image(join(RESOURCES_ROOT,'proviseuradjoint.png'))
			except Exception:
				I2 = False
	else:
		I2 = False
	if I2:
		I2.drawHeight = 3*cm
		I2.drawWidth = 3*cm
	newpage = False
	for eleve,credit in zip(eleves,credits):
		if elev or credit and credit['ddn'] and credit['ine'] and credit['sem1']==30 and credit['sem2']==30: # si l'élève a bien toutes les infos/crédits
			if newpage:# si ce n'est pas la première page, on change de page
				pdf.showPage()
			pdf.y = pdf.format[1]-pdf.marge_y-1.8*cm
			I.drawOn(pdf,9*cm,pdf.y)
			pdf.y -= 10
			pdf.setFont("Times-Roman",7)
			pdf.drawCentredString(pdf.format[0]/2,pdf.y, "MINISTÈRE DE L'ÉDUCATION NATIONALE")
			pdf.y -= 8
			pdf.drawCentredString(pdf.format[0]/2,pdf.y, "DE l'ENSEIGNEMENT SUPÉRIEUR ET DE LA RECHERCHE")
			pdf.y -= 30
			pdf.setFont('Helvetica-Bold',14)
			pdf.drawCentredString(pdf.format[0]/2,pdf.y, "ATTESTATION DU PARCOURS DE FORMATION")
			pdf.y -= 30
			pdf.drawCentredString(pdf.format[0]/2,pdf.y, "EN")
			pdf.y -= 30
			pdf.drawCentredString(pdf.format[0]/2,pdf.y, "CLASSE PRÉPARATOIRE AUX GRANDES ÉCOLES")
			pdf.y -= 40
			pdf.setFont("Helvetica-Oblique",11)
			pdf.drawCentredString(pdf.format[0]/2,pdf.y, "Le recteur de l'académie de {}, Chancelier des universités,".format(config.academie))
			pdf.y -= 15
			pdf.drawCentredString(pdf.format[0]/2,pdf.y, "atteste que")
			pdf.y -= 40
			pdf.setFont("Helvetica",12)
			pdf.drawCentredString(pdf.format[0]/2,pdf.y, "{}".format(eleve))
			pdf.y -= 50
			pdf.setFont("Helvetica",11)
			pdf.drawString(2*cm,pdf.y, "né(e) le {} à {}".format(eleve.ddn.strftime('%d/%m/%Y'),eleve.ldn.title()))
			pdf.y -= 15
			pdf.drawString(2*cm,pdf.y, "n° INE: {}".format(eleve.ine))
			pdf.y -= 50
			pdf.setFont("Helvetica-Oblique",11)
			pdf.drawCentredString(pdf.format[0]/2,pdf.y, "a accompli un parcours de formation dans la filière {}".format(filiere + ('*' if etoile and eleve.classe.annee==2 else '')))
			pdf.y -= 50
			pdf.drawCentredString(pdf.format[0]/2,pdf.y, "Valeur du parcours en crédits du système ECTS :")
			pdf.setFont("Helvetica-Bold",16)
			pdf.drawString(15*cm,pdf.y,"60")
			pdf.y -= 50
			pdf.setFont("Helvetica-Oblique",11)
			pdf.drawCentredString(pdf.format[0]/2,pdf.y, "Mention globale obtenue :")
			pdf.setFillColor((1,0,0))
			pdf.setFont("Helvetica-Bold",13)
			pdf.drawCentredString(13*cm,pdf.y, "ABCDEF"[NoteECTS.objects.moyenneECTS(eleve)])
			pdf.y -= 50
			pdf.setFillColor((0,0,0))
			pdf.setFont("Helvetica",11)
			pdf.drawString(2*cm,pdf.y,"Année académique: {}".format(annee))
			pdf.y -= 15
			pdf.drawString(2*cm,pdf.y,config.nom_etablissement)
			pdf.y -= 30
			pdf.drawCentredString(pdf.format[0]/2,pdf.y,"Fait à {},".format(config.ville))
			pdf.y -= 15
			pdf.drawString(15*cm,pdf.y,"le {}".format(datedujour))
			pdf.y -= 15
			pdf.drawString(15*cm,pdf.y,"Pour le recteur,")
			pdf.y -= 15
			pdf.drawString(15*cm,pdf.y,"Le {}".format(signataire.lower()))
			pdf.y -= 3*cm
			pdf.x = pdf.format[0]-5*cm-2*pdf.marge_x
			if I2:
				I2.drawOn(pdf,pdf.x,pdf.y)
			pdf.setFont("Helvetica-Oblique",9)
			pdf.y=3*cm
			pdf.drawCentredString(pdf.format[0]/2,pdf.y,"Attestation délivrée en application des dispositions de l’article 8 du décret n° 94-1015")
			pdf.y-=12
			pdf.drawCentredString(pdf.format[0]/2,pdf.y,"du 23 novembre 1994 modifié par le décret n° 2007-692 du 3 mai 2007")
			pdf.y-=12
			pdf.drawCentredString(pdf.format[0]/2,pdf.y,"Le descriptif de la formation figure dans l’annexe jointe.")
			newpage = True
	pdf.save()
	fichier = pdf.buffer.getvalue()
	pdf.buffer.close()
	response.write(fichier)
	return response
コード例 #49
0
    def doPWSPDF(self, pdf, data, context):

        page_size = 11.0*inch

        ###
        ### PAGE 1 - the Letter
        ###

        logo_path = settings.STATIC_ROOT + 'reports/logo.png'
        drawing = Image(logo_path, 2.68*inch*0.66, 1.0*inch*0.66)
        drawing.drawOn(pdf, 0.75*inch, page_size-1.0*inch)

        letter_style = ParagraphStyle(name="letter_text",
                                      fontName="Courier")

        data['letter_url'] = settings.LETTER_URL

        letter_text = render_to_string('violations_letter.tmpl', data)
        letter_text = letter_text.replace('\n', '<br></br>')


        letter = Paragraph(letter_text, letter_style)

        aw = 5.5*inch
        ah = 8.5*inch
        w,h = letter.wrap(aw, ah)
        if (w <= aw) and (h <= ah):
            letter.drawOn(pdf, 1.5*inch, (page_size-h+2.0*inch)/2.0)
        else:
            pdf.drawString(1.5*inch, 5.0*inch, 'Could not render the letter because the page is too small.')

        pdf.showPage()

        ###
        ### PAGE 2 - The Violation Report
        ###

        text_width = 6.5*inch
        text_height = 9.0*inch
        top_line = page_size - 1.0*inch # 1 inch margin at top

        header_style = ParagraphStyle(name="header_text",
                                      fontName="Times-Roman")

        header_text = "<para align=center><b>SAFEWATER ATHENS - VIOLATIONS REPORT</b><br></br>Prepared for %s on %s<p></p></para>"

        ## FIXME date --vvvv
        header_text = header_text % (data.get('name'), 'March 15, 2013')
        header = Paragraph(header_text, header_style)
        w, h = header.wrap(text_width, text_height)
        top_line = top_line - h
        header.drawOn(pdf, (8.5*inch - w) / 2.0, top_line)
        top_line = top_line - 0.5 * inch

        vio_style = ParagraphStyle(name='violation_text', fontName="Courier")

        vio_intro_text = "The EPA has reported the following violations for your public water supply:<br></br><br></br><seqreset id='report'>"
        vio_intro = Paragraph(vio_intro_text, vio_style)
        w, h = vio_intro.wrap(text_width, text_height)
        top_line = top_line - h
        vio_intro.drawOn(pdf, (8.5*inch - w) / 2.0, top_line)
        top_line = top_line - 0.5 * inch

        for report in data.get('reports', []):

            vio_text = render_to_string('violations_listing.tmpl', report)
            vio_text = vio_text.replace('\n', '<br></br>')

            vio = Paragraph(vio_text, vio_style)

            vio_width, vio_height = vio.wrap(aw, ah)
            top_line = top_line - vio_height

            # If it won't fit on the page, then put it on the next one
            #
            if top_line < 1.0:
                pdf.showPage()
                top_line = page_size - 1.0*inch # 1 inch margin at top
                w, h = header.wrap(text_width, text_height)
                top_line = top_line - h
                header.drawOn(pdf, (8.5*inch - w) / 2.0, top_line)
                top_line = top_line - 0.5 * inch - vio_height

            vio.drawOn(pdf, 1.0*inch, top_line)

        pdf.showPage()
コード例 #50
0
ファイル: views.py プロジェクト: ambientsound/cash-generator
def pdf(request, guid):
    import settings
    import reportlab.pdfgen.canvas
    from reportlab.lib import pagesizes, units, colors, utils
    from reportlab.platypus import Paragraph, Image
    from reportlab.platypus.tables import Table, TableStyle
    from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet
    from django.contrib.humanize.templatetags.humanize import intcomma

    company = fact.models.Slot.company()
    invoice = get_object_or_404(fact.models.Invoice, pk=guid)
    if not invoice.date_posted or not invoice.date_due:
        return redirect(reverse('fact.views.detailed', kwargs={'guid':guid}))

    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=' + _('invoice') + '-' + invoice.id + '.pdf'
    p = reportlab.pdfgen.canvas.Canvas(response, pagesize=pagesizes.A4)
    width, height = pagesizes.A4
    font = 'Helvetica'

    # Load options and payment text
    options = fact.models.Option.opt_list(request.LANGUAGE_CODE)
    for key, value in options.iteritems():
        options['payment_text'] = options['payment_text'].replace('%' + key + '%', value)
    options['payment_text'] = options['payment_text'].replace('\n', '<br/>')

    # Right-hand stuff
    x = units.cm * 14;
    p.setFont(font + '-Bold', 18)
    p.drawString(x, height-(units.cm*4.5), _('Invoice %s') % invoice.id)
    p.setFont(font, 10)
    p.drawString(x, height-(units.cm*5.5), _('Invoice date: %s') % invoice.date_invoice.strftime('%d.%m.%Y'))
    p.drawString(x, height-(units.cm*6), _('Due date: %s') % invoice.date_due.strftime('%d.%m.%Y'))

    # Logo
    img = utils.ImageReader(settings.FACT_LOGO)
    iw, ih = img.getSize()
    aspect = ih / float(iw)
    img = Image(settings.FACT_LOGO, width=units.cm*4, height=units.cm*4*aspect)
    img.drawOn(p, x+(units.cm*1), height-(units.cm*2.25))

    # Left-hand header stuff
    x = units.cm * 2;
    p.setFont(font + '-Oblique', 8)
    p.drawString(x, height-(units.cm*1.25), company['name'])
    address = company['address'].split("\n")
    base = 1.65
    for a in address:
        p.drawString(x, height-(units.cm*base), a)
        base += 0.4


    # Recipient name and address
    y = units.cm*4.5
    base = 0.5
    customer = invoice.customer
    p.setFont(font, 10)
    p.drawString(x, height-y, customer.addr_name); y += units.cm*base
    p.drawString(x, height-y, customer.addr_addr1); y += units.cm*base
    p.drawString(x, height-y, customer.addr_addr2); y += units.cm*base
    p.drawString(x, height-y, customer.addr_addr3); y += units.cm*base
    p.drawString(x, height-y, customer.addr_addr4); y += units.cm*base
    y += units.cm*2

    # Main
    p.setFont(font + '-Bold', 14)
    p.drawString(x, height-y, _('Specification'))
    y += units.cm*1
    p.setFont(font, 10)
    fmt = '{0:.2f}'

    # Get our invoice entries, headers, etc
    style = TableStyle()
    invoice_entries = []
    headers = [_('Description'), _('Amount'), _('Type'), _('Unit price'), _('VAT'), _('Net')]
    style.add('FONT', (0,0), (-1,0), font + '-Bold')
    style.add('LINEBELOW', (0,0), (-1,0), 1, colors.black)
    for entry in invoice.entries:
        invoice_entries.append([
            entry.description,
            intcomma(fmt.format(entry.quantity)),
            _(entry.action),
            intcomma(fmt.format(entry.unitprice)),
            intcomma(fmt.format(entry.tax_percent)) + '%',
            intcomma(fmt.format(entry.net))
        ])
    style.add('LINEBELOW', (0, len(invoice_entries)), (-1, len(invoice_entries)), 1, colors.black)
    sums = []
    sums.append([_('Net'), '', '', '', '', intcomma(fmt.format(invoice.net))])
    sums.append([_('VAT'), '', '', '', '', intcomma(fmt.format(invoice.tax))])
    if invoice.payments.count() > 0:
        sums.append([_('Subtotal'), '', '', '', '', intcomma(fmt.format(invoice.gross))])
        style.add('LINEBELOW', (0, len(invoice_entries)+3), (-1, len(invoice_entries)+3), 1, colors.black)
        for payment in invoice.payments.all():
            sums.append([_('Paid %s') + payment.post_date.strftime('%d.%m.%Y'), '', '', '', '', intcomma(fmt.format(payment.amount))])
        ln = len(invoice_entries) + len(sums)
        style.add('LINEBELOW', (0, ln), (-1, ln), 1, colors.black)
    else:
        style.add('LINEBELOW', (0, len(invoice_entries)+2), (-1, len(invoice_entries)+2), 1, colors.black)
    sums.append([_('Amount due'), '', '', '', '', intcomma(fmt.format(invoice.due))])
    ln = len(invoice_entries) + len(sums)
    style.add('BACKGROUND', (0, ln), (-1, ln), colors.wheat)
    style.add('FONT', (0, ln), (-1, ln), font + '-Bold')
    style.add('LINEBELOW', (0, ln), (-1, ln), 2, colors.black)

    # Draw the table
    t = Table([headers] + invoice_entries + sums,
            ([units.cm*6.5, units.cm*1.75, units.cm*2, units.cm*2.5, units.cm*2, units.cm*2.25])
            )
    t.setStyle(style)
    w, h = t.wrapOn(p, units.cm*19, units.cm*8)
    y += h
    t.drawOn(p, x, height-y)

    # Bank account number
    stylesheet = getSampleStyleSheet()
    if invoice.notes:
        txt = invoice.notes + '<br/><br/>'
    else:
        txt = ''
    txt += options['payment_text']
    pr = Paragraph(txt, stylesheet['BodyText'])
    w, h = pr.wrapOn(p, units.cm*17, units.cm*6)
    y += pr.height + (units.cm*1)
    pr.drawOn(p, x, height-y)

    # Footer stuff
    p.setFont(font + '-BoldOblique', 8)
    p.drawString(x, units.cm*2.8, company['name'])
    p.setFont(font + '-Oblique', 8)
    p.drawString(x, units.cm*2.4, address[0])
    p.drawString(x, units.cm*2, address[1])

    p.drawString(units.cm*8, units.cm*2.4, 'Web: ' + company['url'])
    p.drawString(units.cm*8, units.cm*2, 'E-post: ' + company['email'])

    p.drawString(units.cm*14, units.cm*2.4, 'Telefon: ' + company['phone'])
    p.drawString(units.cm*14, units.cm*2, 'Org.nr: ' + company['id'])

    # Close the PDF object cleanly, and we're done.
    p.showPage()
    p.save()

    return response
コード例 #51
0
    def make_pdf(self, data, start_date, end_date, filename, emails):

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

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

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

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

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