def drawOnePage(pdf, records):
	# all in inches
	margin = 0.25
	printable_width = 7.5
	each_printable_height = 8.0 / NUM_PER_PAGE


	for i, record in enumerate(records):
		# see reportlab-userguide.pdf page 62.
		story = []
		# story.append(Paragraph(str(record['Idea']), heading))
		# story.append(Spacer(0,.5*inch))

		story.append(Spacer(0,.05*inch))
		style = colorizeCategory(record['Type'])
		story.append(Paragraph(str(record['Type']), style))
		story.append(Spacer(0,.1*inch))

		story.append(Paragraph(valFor(record, 'Text'), heading))
		
		#debugging colors i don't want and need to exclude
		# story.append(Paragraph(str(style.textColor), italic))
		
		# story.append(Paragraph(valFor(record, 'Bucket'), italic))
		# story.append(Paragraph(str(record['Internal / External']), italic))
		# story.append(Paragraph(valFor(record, 'JTBD'), italic))
		# story.append(Paragraph(valFor(record, 'Total Votes'), smallItalic))

		# reportlab are dimensions from bottom left position.
		#x, y = the bottom left corner of this part of the page to print on.
		x = margin * inch
		y = (i * each_printable_height + margin)*inch
		f = Frame(x, y + margin*i*inch, printable_width*inch, each_printable_height*inch, showBoundary=1)
		f.addFromList(story, pdf)
	pdf.showPage()
Ejemplo n.º 2
0
    def drawFrame(self,canvas,func,
                      x,y,
                      textWidth,availableHeight,vAlign="TOP"):
        story = self.document.makeStory(func, textWidth)
        if story is not None:
            height = 0
            for e in story:
                unused,h = e.wrap(textWidth,availableHeight)
                height += h
                availableHeight -= h

            if vAlign == "BOTTOM":
                pass
            elif vAlign == "MIDDLE":
                y -= (height/2)
            elif vAlign == "TOP":
                y -= height

            canvas.saveState()
            f = Frame(x,y,
                         textWidth,height,
                         leftPadding=0,
                         rightPadding=0,
                         bottomPadding=0,
                         topPadding=0)
                         #showBoundary=True)
            f.addFromList(story,canvas)
            canvas.restoreState() 
Ejemplo n.º 3
0
 def make_notice(self, participant, mapping, notice_template,
                 destination_dir=None):
     mapping.update({
         'unique_id': participant.unique_id.encode('utf-8'),
         })
     body = []
     styles = getSampleStyleSheet()
     styleN = styles['Normal']
     styleN.fontName = 'Linux Libertine'
     if notice_template is not None:
         notice = notice_template.safe_substitute(mapping)
         xmldoc = ET.fromstring(notice)
         for para in xmldoc.iter('para'):
             para_str = ET.tostring(para, encoding="utf-8", method="xml")
             body.append(Paragraph(para_str, styleN))
     destination_filename = participant.unique_id + ".pdf"
     destination = destination_filename
     if destination_dir:
         destination = os.path.join(destination_dir, destination_filename)
     c = canvas.Canvas(destination, pagesize=A4)
     c.rect(WINDOW_ORIGIN_X, WINDOW_ORIGIN_Y, WINDOW_WIDTH, WINDOW_HEIGHT)
     address_window = c.beginText()
     c.setFont('Linux Libertine', 12)
     address_window.setFont('Linux Libertine', 12)
     address_window.setTextOrigin(WINDOW_ORIGIN_X + 0.5*cm,
                                  WINDOW_ORIGIN_Y + WINDOW_HEIGHT - 0.5*cm)
     address_window.textLine(participant.name)
     address_window.textLine(participant.address.street_number)
     address_window.textLine(participant.address.zip_code)
     address_window.textLine(str(participant.address.city))
     c.drawText(address_window)
     f = Frame(BODY_ORIGIN_X, BODY_ORIGIN_Y, BODY_WIDTH, BODY_HEIGHT,
               showBoundary=0)
     f.addFromList(body, c)
     return c
Ejemplo n.º 4
0
    def _header_footer(canvas, doc):
        # Save the state of our canvas so we can draw on it
        canvas.saveState()
        # canvas.setTitle("Shift export")
        styles = getSampleStyleSheet()
        styles.add(ParagraphStyle(name='NormalText', fontName='OpenSans-Regular', fontSize=10))
        styles.add(ParagraphStyle(name='BottomText', fontName='OpenSans-Regular', fontSize=8))
        styles.add(ParagraphStyle(name='Schluessel', alignment=TA_CENTER, fontName='OpenSans-Regular', fontSize=14))
        styles.add(ParagraphStyle(name='centered', alignment=TA_CENTER, fontName='OpenSans-Regular'))

        # Text that is found on the bottom of (right now..) every page!
        canvas.setFillColor(colors.lightgrey)
        canvas.rect(200, doc.bottomMargin, 125, 40, fill=True)
        frame1 = Frame(200, doc.bottomMargin, 125, 40, showBoundary=1, topPadding=10)

        story = [Paragraph('Schlüssel', styles['Schluessel'])]
        story_inframe = KeepInFrame(4 * inch, 8 * inch, story)
        frame1.addFromList([story_inframe], canvas)

        key_text = Paragraph("K Krank<br /><br />U Urlaub", styles['NormalText'])
        w, h = key_text.wrap(doc.width, doc.bottomMargin)
        key_text.drawOn(canvas, 200 + 125 + 5, doc.bottomMargin + 2.5 )

        note_text = Paragraph("* Tragen Sie in diese Spalte eines der folgenden Kürzel ein, wenn es für diesen "
                              "Kalendertag zutrifft", styles['BottomText'])
        w, h = note_text.wrap(doc.width, doc.bottomMargin)
        note_text.drawOn(canvas, doc.leftMargin + 5, doc.bottomMargin + 45)

        status_text = Paragraph("Stand: 10/2015", styles['BottomText'])
        w, h = status_text.wrap(doc.width, doc.bottomMargin)
        status_text.drawOn(canvas, doc.width - 5 * mm, doc.bottomMargin)

        # Release the canvas
        canvas.restoreState()
Ejemplo n.º 5
0
    def add_form(self, num_rows, form, print_object):
        cols = print_object.get_form_field_layout()
        field_aliases, field_widths = ['ID'], [5]
        field_aliases.extend([c.field.col_alias for c in cols])
        field_widths.extend([c.width for c in cols])
        field_widths = [n/100.0*self.inner_width for n in field_widths] #normalize
        x, y = self.origin_x, self.origin_y + self.qr_size
        width = self.inner_width
        height = self.inner_height - self.qr_size - 35

        data, rowheights, header_flowables = [], [39], []
        style = ParagraphStyle(name='Helvetica', fontName='Helvetica', fontSize=10)
        for a in field_aliases:
            header_flowables.append(Paragraph('<b>%s</b>' % a, style))
        data.append(header_flowables)
        for n in range(0, num_rows):
            data.append(['' for n in field_widths])
            rowheights.append(39)

        t=Table(data, field_widths, rowheights)
        GRID_STYLE = TableStyle([
            ('GRID', (0,0), (-1,-1), 0.25, colors.black),
            ('FONT', (0,0), (-1,-1), 'HandSean'),
            ('BOX',(0,0),(-1,-1),2,colors.black)
        ])
        t.setStyle(GRID_STYLE)
        frame = Frame(x, y, width, height, showBoundary=0, leftPadding=0,
                      bottomPadding=0, rightPadding=0, topPadding=0)
        frame.addFromList([t], self.canvas)
Ejemplo n.º 6
0
 def add_form(self, num_rows, form, is_mini_form=False):
     cols = form.get_fields(print_only=True)
     field_aliases, field_widths = ['ID'], [5]
     field_aliases.extend([c.col_alias for c in cols])
     field_widths.extend([c.display_width for c in cols])
     field_widths = [n/100.0*self.inner_width for n in field_widths] #normalize
     x, y = self.origin_x, self.origin_y + self.qr_size
     width = self.inner_width
     height = self.inner_height - self.qr_size - 35
     if is_mini_form:
         height = Units.pixel_to_point(300) #only render a 300-pixel tall form
     
     data, rowheights, header_flowables = [], [39], []
     style = ParagraphStyle(name='Helvetica', fontName='Helvetica', fontSize=10)
     for a in field_aliases:
         header_flowables.append(Paragraph('<b>%s</b>' % a, style))
     data.append(header_flowables)
     for n in range(0, num_rows):
         data.append(['', '', '', ''])
         rowheights.append(39)
 
     t=Table(data, field_widths, rowheights)
     GRID_STYLE = TableStyle([
         ('GRID', (0,0), (-1,-1), 0.25, colors.black),
         ('FONT', (0,0), (-1,-1), 'HandSean'),
         ('BOX',(0,0),(-1,-1),2,colors.black)
     ])
     t.setStyle(GRID_STYLE)
     frame = Frame(x, y, width, height, showBoundary=0, leftPadding=0,
                   bottomPadding=0, rightPadding=0, topPadding=0)
     frame.addFromList([t], self.canvas)
Ejemplo n.º 7
0
def draw_summary_frame(canvas, summary, text_color, show_boundary):
    """
    Frame mit der Summary des Tickets zeichnen
    :param canvas:
    :param summary: Summary als Text
    :param text_color: Farbe für den Text
    :param show_boundary: Rahmen des Frames zeichnen?
    :return:
    """
    style = ParagraphStyle(name='Normal',
                           fontName='Helvetica',
                           fontSize=30,
                           leading=30,
                           alignment=TA_CENTER,
                           textColor=text_color)

    frame_width = 390
    frame_height = 170
    elements = list()
    paragraph = Paragraph(html.escape(summary), style)
    text_height = paragraph.wrap(frame_width, frame_height)[1]
    elements.append(paragraph)

    top_padding = (frame_height - text_height) / 2
    if top_padding <= 20:
        top_padding = 0

    frame = Frame(15, 70, frame_width, frame_height,
                  showBoundary=show_boundary,
                  topPadding=top_padding)
    frame.addFromList(elements, canvas)
Ejemplo n.º 8
0
def generer_coupons(output_file, coupon):
    """

    :param output_file: File
    :param coupon: Coupon
    :return:
    """
    # Styles
    styles = StyleSheet()
    styles.add_style('normal', fontName='Helvetica', fontSize=14)
    styles.add_style('normal-centered', fontName='Helvetica', fontSize=14,
                     alignment=TA_CENTER)
    styles.add_style('normal-bold', fontName='Helvetica-bold', fontSize=14)
    styles.add_style('grand', fontName='Helvetica', fontSize=18)
    styles.add_style('grand-bold', fontName='Helvetica-bold', fontSize=18)
    styles.add_style('petit', fontName='Helvetica', fontSize=12)
    styles.add_style('petit-bold', fontName='Helvetica-bold', fontSize=12)
    styles.add_style('titre', fontName='Helvetica-Bold', fontSize=15)
    styles.add_style('centered', alignment=TA_CENTER)
    styles.add_style('remarque', fontName='Helvetica-Oblique', fontSize=11)
    styles.add_style('gros-numero', fontName='Helvetica-Bold', fontSize=36)
    styles.add_style('right-aligned', alignment=TA_RIGHT)
    canvas = Canvas(output_file, pagesize=PAGESIZE)
    draw_coupon(canvas, styles, coupon.nom_participant, coupon.noms_invites,
                coupon.infos_depart_arrivee.depart_date,
                coupon.infos_depart_arrivee.depart_de,
                'depart', coupon.nb_personnes)
    draw_coupon(canvas, styles, coupon.nom_participant, coupon.noms_invites,
                coupon.infos_depart_arrivee.arrivee_date,
                coupon.infos_depart_arrivee.arrivee_a,
                'arrivee', coupon.nb_personnes)
    
    page_width, page_height = PAGESIZE
    frame_height = 10 * cm
    frame = Frame(COUPON_MARGIN_SIDE, calc_coupon_y('depart') - frame_height,
                  page_width - COUPON_MARGIN_SIDE * 2, frame_height)
    frame.addFromList([Paragraph(u"""<br/><br/><u>Veuillez noter que les transferts en 
    navette ne s'effectuent que dans les conditions suivantes:</u><br/><br/>     
        À votre arrivée, les transferts en navette organisés des aéroports de 
        Casablanca et de Marrakech sont uniquement à destination du lieu de 
        l’Assemblée générale, le Palais des Congrès de l'hôtel Mogador Agdal 2.
        <br/><b>Ces transferts ne sont disponibles que du 6 au 10 mai 2017.</b>
        <br/><br/>
        À votre départ, les transferts en navette oganisés à destination des 
        aéroports de Casablanca et de Marrakech se feront au même point qu'à 
        l'arrivée à l'hôtel Mogador Agdal 2.<br/>
        <b>Ces transferts ne sont disponibles que du 12 au 15 mai 2017.</b>
        <br/><br/>
        Aucun autre arrêt n'est prévu durant ces trajets.
        Si vous ne logez pas au Mogador Agdal 2, vous devez assurer, à vos 
        frais, votre déplacement entre votre hôtel et le lieu de l’Assemblée 
        générale.
        <br/><br/>
        <b>Adresse du Mogador Agdal 2:</b> Zone Touristique Agdal, Route d'Ourika, 
        Marrakech 40000, Maroc
        <br/><br/>
        <b>En cas de problème à l'arrivée, veuillez contacter:</b> <br/>Casablanca: 
        +212 6 89 91 77 19 &nbsp; &nbsp; &nbsp; Marrakech: +212 6 89 91 77 20
    """, styles['remarque'])], canvas)
    canvas.save()
Ejemplo n.º 9
0
 def add_items(items, showBoundary=False):
     f = Frame(c.x(0), c.y(0), c.width(1), c.height(1),
               showBoundary=showBoundary,
               leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0)
     f.addFromList(items, canvas)
     if items:
         raise Exception("Does not fit - items left")
Ejemplo n.º 10
0
    def render(self, canvas, context):
        canvas.rect(self.left_margin, self.bottom_margin,
                    self.box_width, self.box_height,
                    stroke=1, fill=1)

        data = [
            ('Last name:', context['student']['last_name']),
            ('Name:', context['student']['first_name']),
            ('Teacher:', '{} {}'.format(context['teacher']['last_name'],
                                        context['teacher']['first_name'])),
            ('ID:', context['student']['id']),
            ('School:', context['school']),
        ]

        t = Table(data, (30 * mm, self.box_width - 32 * mm),
                  [(self.box_height - 3 * mm) / len(data)] * len(data))
        s = TableStyle([
            ('FONTSIZE', (0, 0), (-1, -1), 8),
            ('LEFTPADDING', (0, 0), (0, -1), 13),
            ('BACKGROUND', (0, 0), (-1, -1), colors.white),
        ])
        t.setStyle(s)
        f = Frame(self.left_margin, self.bottom_margin,
                  self.box_width, self.box_height,
                  leftPadding=1 * mm, rightPadding=1 * mm,
                  topPadding=2.5 * mm, bottomPadding=0 * mm)
        f.addFromList([t], canvas)
Ejemplo n.º 11
0
def _generate_fromfield(c, styles, name, referat, email, logo):
    addressbox = []
    addressbox.append(Paragraph("Allgemeiner Studierendenausschuss", styles['Normal']))
    addressbox.append(Paragraph("Adenauerring 7\n76131 Karlsruhe",styles['Normal']))
    addressbox.append(Paragraph("<a href='Test'>Test</a>", styles['Normal']))
    f = Frame(width - (5+1)*cm, height - (3.2+7.5)*cm, 5*cm, 7.5*cm, showBoundary=1)
    f.addFromList(addressbox, c)
    return c
def test1():
    c  = Canvas('figures.pdf')
    f = Frame(inch, inch, 6*inch, 9*inch, showBoundary=1)
    v = PlatPropFigure1()
    v.captionTextColor = toColor('blue')
    v.captionBackColor = toColor('lightyellow')
    f.addFromList([v],c)
    c.save()
Ejemplo n.º 13
0
	def draw(self,canvas):
		f = Frame(self.startx, self.starty - self.height + 10, self.width, self.height)
		styles = getSampleStyleSheet()
		styleN = styles['Normal']
		styleN.fontSize = self.fontsize
		styleN.leading = int(1.1 * self.fontsize)
		data = []
		data.append(Paragraph(self.string, styleN))
		f.addFromList(data,canvas)
    def __init__(self, x1, y1, width,height, leftPadding=6, bottomPadding=6,
            rightPadding=6, topPadding=6, id=None, showBoundary=0,
            overlapAttachedSpace=None,_debug=None,background=None):

        Frame.__init__(self, x1, y1, width, height, leftPadding,
            bottomPadding, rightPadding, topPadding, id, showBoundary,
            overlapAttachedSpace, _debug)

        self.background = background
Ejemplo n.º 15
0
 def cabecera(self, canvas):
     origen = Frame(self.MARGEN, A4[1] - 1.5 * cm,
         A4[0] - (2 * self.MARGEN), 1 * cm,
         id='cabecera', showBoundary=self.mostrar)
     story = []
     story.append(Paragraph(self.header, self.estilos['cabecera']))
     origen.addFromList(story, canvas)
     canvas.line(x1=self.MARGEN, y1=A4[1] - 1.2 * cm,
         x2=A4[0] - (self.MARGEN), y2=A4[1] - 1.2 * cm)
Ejemplo n.º 16
0
def drawInfoBox(c, t,  x, y):
    lines = []
    c.setFillColor(HexColor('#E8E8E8'))
    c.setStrokeColor(HexColor('#E8E8E8'))
    c.rect(x - boxw / 2, y, boxw, boxh / 3.0, fill=1)
    f = Frame(x - boxw / 2, y, boxw, boxh / 3.0, leftPadding=1, bottomPadding=1, rightPadding=1, topPadding=1, showBoundary=1)
    lines.append(Paragraph(t, styleT))
    f.addFromList(lines,c)
    c.setStrokeColor(HexColor('#000000'))
Ejemplo n.º 17
0
 def getPreformatted ( self, c, x, y, w, h, style, info, mm_mode = 1 ) :
   """ formatieren Bereich zurueckgeben """
   lInfo = []
   lInfo.append(XPreformatted( info, style))
   if mm_mode == 1 :
     f = Frame ( x, y, w, h, showBoundary=0 )
   else :
     f = Frame ( x*mm, y*mm, w*mm, h*mm, showBoundary=0 )
   f.addFromList ( lInfo, c )
Ejemplo n.º 18
0
    def createPdf(self, imageGenerator = None):
        if imageGenerator:
            mapImage = imageGenerator.createMapImage()
        else:
            mapImage = None

        (self.filehandle,self.filename) = tempfile.mkstemp(suffix='.pdf')
        c = canvas.Canvas(self.filename)
        port_width,port_height = letter
        land_width = port_height
        land_height = port_width
        c.setPageSize([land_width,land_height])
        # choose some colors
        c.setStrokeColorRGB(0.5,0.5,0.5)
        c.setFillColorRGB(0.95,0.95,0.95)
        # draw a rectangle
        c.rect(0.45*inch,0.45*inch,10.1*inch,6.6*inch, fill=1)
        # Add the image
        if mapImage:
            c.drawImage(mapImage,0.5*inch,0.5*inch,10.0*inch,6.5*inch)
            
        c.setFont("Helvetica", 24)
        c.setFillColorRGB(0,0,0)
        c.drawString(0.5*inch, 7.5*inch,
            self.fields['title'] or "Untitled")

        description = self.fields['description'] or ""
        styles = getSampleStyleSheet()
        styleN = styles['Normal']
        descriptionFlowable = [Paragraph(description,styleN)]
        f = Frame(5*inch,7.25*inch,4*inch,1*inch,showBoundary=0)
        f.addFromList(descriptionFlowable,c)
        #descTextObj = c.beginText()
        #descTextObj.setTextOrigin(7.5*inch,8*inch)
        #descTextObj.setFont("Helvetica", 12)
        #descTextObj.textLines(description)
        #c.drawText(descTextObj)

        if self.imagefilename:
            logoImage = ImageReader(self.imagefilename)
            c.drawImage(logoImage,9.25*inch,7.25*inch,1.25*inch,1*inch,
                preserveAspectRatio=True, anchor="nw")
        
        # define a large font
        c.setFont("Helvetica", 14)
        c.setFillColorRGB(1,1,1)
        # Layers to draw
        layers = self.fields['oldata']['mapLayers']
        layerNames = ""
        for layer in layers:
            layerNames = layerNames + ' ' + layer['name']
        #c.drawString(3.5*inch, 5*inch, "Map Layers Passed Down")
        c.showPage()
        c.save()
        self.data = c.getpdfdata()
        return (self.filename, self.data)
Ejemplo n.º 19
0
 def getParagraph ( self, c, x, y, w, h, style, info, mm_mode = 1 ) :
   """ formatieren Bereich zurueckgeben """
   lInfo = []
   lInfo.append(Paragraph(info, style, encoding="utf-8"))
   if mm_mode == 1 :
     f = Frame ( x, y, w, h, showBoundary=0 )
   else :
     f = Frame ( x*mm, y*mm, w*mm, h*mm, showBoundary=0 )
   f.addFromList ( lInfo, c )
   return f
Ejemplo n.º 20
0
def framePie(pdf, obj):
    # Recuadro controlado
    pdf.setStrokeColorRGB(0, 0, 0)
    f = Frame(margXizq, margYtop - 700, 230, 80)
    f.drawBoundary(pdf)

    pdf.setFont("Helvetica", 11)
    pdf.rect(margXizq, margYtop - 640, 230, 0.5, 1, 1)
    pdf.setFont("Helvetica-Bold", 11)
    pdf.drawString(margXizq + 6, margYtop - 635, u"Controlado")

    # Recuadro Recibido
    pdf.setStrokeColorRGB(0, 0, 0)
    f = Frame(margXizq, margYtop - 785, 230, 80)
    f.drawBoundary(pdf)

    pdf.setFont("Helvetica", 11)
    pdf.rect(margXizq, margYtop - 725, 230, 0.5, 1, 1)
    pdf.setFont("Helvetica-Bold", 11)
    pdf.drawString(margXizq + 6, margYtop - 720, u"Recibido")

    # Recuadro Autorizado
    pdf.setStrokeColorRGB(0, 0, 0)
    f = Frame(margXizq+240, margYtop - 700, 230, 80)
    f.drawBoundary(pdf)

    pdf.setFont("Helvetica", 11)
    pdf.rect(margXizq+240, margYtop - 640, 230, 0.5, 1, 1)
    pdf.setFont("Helvetica-Bold", 11)
    pdf.drawString(margXizq + 246, margYtop - 635, u"Autorizado")
Ejemplo n.º 21
0
def einsatzfax_pdf(request, id):
    """
    Creates a pdf of an einsatz ready for printing
    """
    try:
        # TODO: create pdf from Einsatz
        einsatz = Einsaetze.objects.get(id=id)
        # Create the HttpResponse object with the appropriate PDF headers.
        response = HttpResponse(mimetype='application/pdf')
        response['Content-Disposition'] = 'attachment; filename=einsatzfax.pdf' 

        # Create the PDF object, using the response object as its "file" in DIN A4 format
        p = canvas.Canvas(response,pagesize=A4)

	# A4 width and height
	breite, hoehe = A4
	# Define the styles
	styleHeader = ParagraphStyle('Header', fontName='Helvetica', fontSize=36, leading=40, spaceAfter=40, alignment=TA_LEFT)
	styleText = ParagraphStyle('Text', fontName='Helvetica', fontSize=16, leading=20, alignment=TA_LEFT)
	styleLine = ParagraphStyle('Line', fontName='Helvetica', fontSize=16, leading=20, alignment=TA_LEFT, textColor=HexColor(0xFFFFFF))
	# Creating a list, which contains the content
	content = []
	# Create the frame where the content will be placed
	f = Frame(1*cm,1*cm,breite-(2*cm),hoehe-(2*cm))

	# Draw things on the PDF. Here's where the PDF generation happens.
        # See the ReportLab documentation for the full list of functionality.
        
	# Generate content
        meldeb = Meldebilder.objects.get(id = einsatz.meldebild_id)
        alarm = Alarmstufen.objects.get(stufe = meldeb.stufe_id)
	content.append(Paragraph(alarm.stufe + " " + meldeb.beschreibung, styleHeader))
	content.append(Paragraph(einsatz.strasse + " " + einsatz.nummer1 + " " + einsatz.nummer2 + " " + einsatz.nummer3, styleText))
	content.append(Paragraph(str(einsatz.plz) + " " + einsatz.ort, styleText))
	content.append(Paragraph("a", styleLine))
	if einsatz.objekt:
		content.append(Paragraph("Objekt: " + einsatz.objekt, styleText))
	if einsatz.melder:
		content.append(Paragraph("Melder: " + einsatz.melder, styleText))
	if einsatz.meldertel:
		content.append(Paragraph("Meldertelefon: " + einsatz.meldertel, styleText))
	if einsatz.einsatzerzeugt:
		content.append(Paragraph("Meldezeitpunkt: " + str(einsatz.einsatzerzeugt), styleText))
	content.append(Paragraph("a", styleLine))
	content.append(Paragraph(einsatz.bemerkung, styleText))

	# Add content
	f.addFromList(content,p)

        # Close the PDF object cleanly, and we're done.
        p.showPage()
        p.save()
        return response
    except Einsaetze.DoesNotExist:
        return render(request, "infoscreen_screen/einsatzfax/einsatzfax_pdf.xml")
Ejemplo n.º 22
0
  def frame(self,story,width='100%',height='100%',left=0,bottom=0,top=None,right=None):
    ''' create a zone that will contain flowable elements '''

    self.saveState()
    
    width  = checkPercent(width, self.width)
    height = checkPercent(height, self.height)
    x,y    = self.placement(width,height,left,bottom,top,right)
    f      = Frame(x,y,width,height)
    f.addFromList(story,self)
    self.restoreState()
Ejemplo n.º 23
0
 def test02(self):
    "What happens if a Frame gets full?"
    c = Canvas('test02.pdf')
    "create a very small frame:"
    f = Frame(inch, inch, inch, inch, showBoundary=1)
    f.addFromList(self.story,c)
    """
    The Frame takes from the list all elemens that fit into the Frame.
    """
    self.assertEqual(len(self.story),1)
    c.save()
Ejemplo n.º 24
0
    def drawOn(self, canv):
        # make a frame
        frame = Frame(self.x, self.y, self.width, self.height)
        frame.showBoundary = self.showBoundary

        # build a story for the frame
        story = []
        for thingy in self.content:
            # ask it for any flowables
            story.append(thingy.getFlowable())
        # draw it
        frame.addFromList(story, canv)
Ejemplo n.º 25
0
def myUsingFrames():
    styleSheet = getSampleStyleSheet()
    styleN = styleSheet['Normal']
    styleH = styleSheet['Heading1']
    story = []

    story.append(Paragraph('This is a heading:: ŐŐŐŐŐÚÚÚÜÜÜ', styleH, encoding='utf8'))
    story.append(Paragraph('This is <i>normal</i> paragraph:: ŐŐŐŐŐÚÚÚÜÜÜ', styleN, encoding='utf8'))
    c = Canvas("usingframes.pdf")
    f = Frame(inch, inch, 6*inch, 9*inch, showBoundary=1)
    f.addFromList(story,c)
    c.save()
Ejemplo n.º 26
0
def addInfoPage(conn, scriptParams, c, panels_json):

    base_url = None
    if 'Webclient_URI' in scriptParams:
        base_url = scriptParams['Webclient_URI']
    pageWidth = scriptParams['Page_Width']
    pageHeight = scriptParams['Page_Height']

    # Need to sort panels from top (left) -> bottom of Figure
    panels_json.sort(key=lambda x: int(x['y']) + x['y'] * 0.01)

    imgIds = set()
    styles = getSampleStyleSheet()
    styleN = styles['Normal']
    styleH = styles['Heading1']
    story = []
    scalebars = []

    story.append(Paragraph("Figure Images", styleH))

    def addPara(lines):
        text = "<br />".join(lines)
        attrs = "spaceBefore='15' spaceAfter='15'"
        para = "<para %s>%s</para>" % (attrs, text)
        story.append(Paragraph(para, styleN))

    # Go through sorted panels, adding paragraph for each unique image
    for p in panels_json:
        iid = p['imageId']
        # list unique scalebar lengths
        if 'scalebar' in p and p['scalebar']['length'] not in scalebars:
            scalebars.append(p['scalebar']['length'])
        if iid in imgIds:
            continue    # ignore images we've already handled
        imgIds.add(iid)
        thumbSrc = getThumbnail(conn, iid)
        thumb = "<img src='%s' width='25' height='25' valign='middle' />" % thumbSrc
        line = [thumb]
        line.append(p['name'])
        img_url = "%s?show=image-%s" % (base_url, iid)
        line.append("<a href='%s' color='blue'>%s</a>" % (img_url, img_url))
        addPara([" ".join(line)])

    if len(scalebars) > 0:
        story.append(Paragraph("Scalebars", styleH))
        sbs = [str(s) for s in scalebars]
        addPara(["Scalebars: %s microns" % " microns, ".join(sbs)])

    f = Frame(inch, inch, pageWidth-2*inch, pageHeight-2*inch)
    f.addFromList(story, c)
    c.save()
Ejemplo n.º 27
0
def frameDetalle(pdf, idOrden):
  f = Frame(10,55, 570, 437)
  f.drawBoundary(pdf)

  encabezado = ('CANT.', 'MATERIAL')
  # Detalle de tabla con 20 renglones
  # Recorre PedidoItem (linea por producto)
  detalle = []
  for qs in PedidoItem.objects.filter(pedido=idOrden).order_by('pk'):
      descripcion = qs.producto.descripcion + ' ' + qs.sAclaracion
      if (len(descripcion) <= 102):
          detalle += [(qs.sCantidad +' '+ qs.unidades.descripcionCorta, descripcion)]
      else:
          detalle += [(qs.sCantidad +' '+ qs.unidades.descripcionCorta, descripcion[:102])]
          if (len(descripcion[102:240]) <= 102):
              detalle += [('', descripcion[102:240])]
          else:
              detalle += [('', descripcion[102:240])]
              detalle += [('', descripcion[240:300])]

  # Recorre PedidoItemConcepto (linea por concepto)
  for qs in PedidoItemConcepto.objects.filter(pedido=idOrden).order_by('pk'):
      descripcion = qs.sDescripcion
      if (len(descripcion) <= 102):
          detalle += [(qs.sCantidad +' '+ qs.unidades.descripcionCorta, descripcion)]
      else:
          detalle += [(qs.sCantidad +' '+ qs.unidades.descripcionCorta, descripcion[:102])]
          if (len(descripcion[102:240]) <= 102):
              detalle += [('', descripcion[102:240])]
          else:
              detalle += [('', descripcion[102:240])]
              detalle += [('', descripcion[240:300])]

  while len(detalle) < 23:
      detalle = detalle + [('', '')]
      detalle_orden = Table([encabezado] + detalle, colWidths=[2 * cm, 17.95 * cm])

      detalle_orden.setStyle(TableStyle(
          [
            # La primera fila(encabezados) va a estar centrada
            ('ALIGN', (0, 0), (1, 0), 'CENTER'),
            # Los bordes de todas las celdas serán de color negro y con un grosor de 1
            ('GRID', (0, 0), (-1, -1), 1, colors.black),
            # El tamaño de las letras de cada una de las celdas será de 10
            ('FONTSIZE', (0, 0), (-1, -1), 10),
          ]
      ))
  # Establecemos el tamaño de la hoja que ocupará la tabla
  detalle_orden.wrapOn(pdf, 800, 600)
  # Definimos la coordenada donde se dibujará la tabla
  detalle_orden.drawOn(pdf, 12, 57)
Ejemplo n.º 28
0
def text_to_pdf(text, output, lines_per_page=66):
    c = Canvas(output, pagesize=letter)
    style = ParagraphStyle ( "default_style", fontName="Courier-Bold", fontSize=10, leading=11.1, alignment=TA_LEFT, allowWidows=1, allowOrphans=1 )
    lines = text.splitlines()
    while lines:
        group = lines[:lines_per_page]
        lines = lines[lines_per_page:]
        newtext = "<br/>".join ( escape(l) for l in group )
        story = [Paragraph(newtext, style)]
        f = Frame(0.5*inch, 0.25*inch, 7.5*inch, 10.5*inch)
        f.addFromList(story, c)
        assert len(story) == 0
        c.showPage()
    c.save()
Ejemplo n.º 29
0
    def draw_header(self, canv, doc):
        canv.saveState()
        header_height = self.wrap_y(self.header)
        top = self.pagesize[1] - self.topMargin

        frame = Frame(self.leftMargin,
                      top - header_height,
                      self.width,
                      header_height,
                      leftPadding=0,
                      bottomPadding=0,
                      topPadding=0,
                      rightPadding=0)
        frame.addFromList(self.header, canv)
        canv.restoreState()
Ejemplo n.º 30
0
def frameCabecera(pdf, obj):
    beneficiario = obj.beneficiario()
    if type(beneficiario) is User:
        strBeneficiario = beneficiario.first_name + ', ' + beneficiario.last_name
    else:
        strBeneficiario = beneficiario.__str__()
    motivo = obj.motivo.__str__()
    if getattr(obj.beneficiario(), 'cuit', None) is None:
        usr = ExtendUser.objects.get(pk=obj.beneficiario().pk)
        cdn = str(usr.dni)
    else:
        cdn = str(obj.beneficiario().cuit)
    # Recuadro
    pdf.setStrokeColorRGB(0, 0, 0)
    f = Frame(margXizq, margYtop-185, 540, 170)
    f.drawBoundary(pdf)
    # titulo
    pdf.setFont("Helvetica-Bold", 13)
    pdf.drawString(margXizq*7, margYtop-45, u"ORDEN DE PAGO Nº ")
    pdf.drawString(margXizq*11+12, margYtop-45, str(obj.id).zfill(5))
    # Tabla Cabecera
    p0 = Paragraph('''<b>Beneficiario:</b>''', stylesheet['Normal'])
    p1 = Paragraph('''<b>Cuit/DNI:</b>''', stylesheet['Normal'])
    p2 = Paragraph('''<b>Recibo:</b>''', stylesheet['Normal'])
    p3 = Paragraph('''<b>Motivo:</b>''', stylesheet['Normal'])
    data = [[p0, strBeneficiario], [p1, cdn], [p2, ' '], [p3, motivo]]
    t1 = Table(data, colWidths=[3 * cm, 5 * cm])
    t1.setStyle(TableStyle(
        [
            # La primera fila(encabezados) va a estar centrada
            # ('ALIGN', (0, 0), (3, 0), 'CENTER'),
            # Los bordes de todas las celdas serán de color negro y con un grosor de 1
            ('LINEBELOW', (1, 0), (1, 3),  1, colors.black),
            # El tamaño de las letras de cada una de las celdas será de 10
            # ('FONTSIZE', (0, 0), (-1, -1), 10),
        ]
    ))

    pdf.rect(margXizq, margYtop-145, 540, 1, 1, 1)

    p4 = Paragraph('''<b>SON PESOS: </b>''', stylesheet['Normal'])
    data2 = [[p4, importe.toText()]]
    t2 = Table(data2, colWidths=[3 * cm, 5 * cm])

    t1.wrapOn(pdf, 800, 600)
    t2.wrapOn(pdf, 800, 600)
    t1.drawOn(pdf, margXizq+15, margYtop-135)
    t2.drawOn(pdf, margXizq+15, margYtop-175)
Ejemplo n.º 31
0
def savePdfReport( fileName, attImage ):
    # ATENÇÃO: Necessário ter instalado o módulo reportlab
    from reportlab.pdfgen.canvas import Canvas
    from reportlab.lib.styles import getSampleStyleSheet
    from reportlab.lib.units import inch
    from reportlab.platypus import Paragraph, Frame, Image
    styles = getSampleStyleSheet()
    styleN = styles['Normal']
    styleH = styles['Heading1']
    story = []
    story.append(Paragraph("EPM Data Analysis Report",styleH))
    story.append(Paragraph("Relatório gerado a partir do EPM Studio - Dataset Analysis", styleN))
    story.append(Paragraph(" ", styleN))
    im = Image(attImage, width=4*inch, height=3.02*inch)
    im.hAlign = 'CENTER'
    story.append(im)
    c = Canvas( fileName )
    f = Frame(inch, inch, 6*inch, 9*inch, showBoundary=1)
    f.addFromList(story,c)
    c.save()
    def create_report(self, buff=None):
        def get_method(section):
            try:
                method = getattr(self, "_section_" + section)
            except AttributeError:
                raise Exception("Section method not found: " + section)
            return method

        def page_number(canv, doc):
            page_num = Paragraph(
                str(doc.page),
                extend_style(styles["rc-aawp-main-content"],
                             alignment=TA_CENTER,
                             fontSize=8),
            )
            page_num.wrapOn(canv, self.page_size[0], 0)
            page_num.drawOn(canv, 0, 4.8 * mm)

        if not buff:
            buff = io.BytesIO()

        story = []
        for section in self.sections:
            elems = get_method(section)()
            for elem in elems:
                story.append(elem)

        page_t = PageTemplate('normal', [
            Frame(
                self.page_margin[0],
                self.page_margin[1],
                self.page_size[0] - self.page_margin[0] * 2,
                self.page_size[1] - self.page_margin[1] * 2,
                leftPadding=0,
                bottomPadding=0,
                rightPadding=0,
                topPadding=0,
            )
        ],
                              onPage=page_number)
        doc_t = BaseDocTemplate(
            buff,
            pagesize=letter,
            title=self.title,
            author=self.author,
            leftMargin=self.page_margin[0],
            rightMargin=self.page_margin[0],
            topMargin=self.page_margin[1],
            bottomMargin=self.page_margin[1],
        )
        doc_t.addPageTemplates(page_t)
        doc_t.build(story)
        buff.seek(0)
        return buff
Ejemplo n.º 33
0
def demo1(canvas):
    frame = Frame(
        2 * inch,  # x
        4 * inch,  # y at bottom
        4 * inch,  # width
        5 * inch,  # height
        showBoundary=1  # helps us see what's going on
    )
    bodyStyle = ParagraphStyle('Body',
                               fontName='Times-Roman',
                               fontSize=24,
                               leading=28,
                               spaceBefore=6)
    para1 = Paragraph('Spam spam spam spam. ' * 5, bodyStyle)
    para2 = Paragraph('Eggs eggs eggs. ' * 5, bodyStyle)
    mydata = [para1, para2]

    #this does the packing and drawing.  The frame will consume
    #items from the front of the list as it prints them
    frame.addFromList(mydata, canvas)
Ejemplo n.º 34
0
    def add_footer_to_document(self):
        first_page_frame = Frame(self.doc.leftMargin,
                                 self.doc.bottomMargin + 50,
                                 self.doc.width,
                                 self.doc.height,
                                 id='first_frame')
        next_page_frame = Frame(self.doc.leftMargin,
                                self.doc.bottomMargin + 50,
                                self.doc.width,
                                self.doc.height,
                                id='last_frame')

        first_template = PageTemplate(id='first',
                                      frames=first_page_frame,
                                      onPage=self.footer)
        next_template = PageTemplate(id='next',
                                     frames=next_page_frame,
                                     onPage=self.footer)
        self.doc.addPageTemplates([first_template, next_template])
        self.story.append(NextPageTemplate(['*', 'next']))
    def draw(self, output, story):
        from reportlab.platypus import BaseDocTemplate, Frame, PageTemplate

        PAGE_SIZE = A4
        MARGIN_SIZE = 15 * mm
        doc = BaseDocTemplate(output, pagesize=PAGE_SIZE, leftMargin=MARGIN_SIZE, rightMargin=MARGIN_SIZE,
                              topMargin=MARGIN_SIZE, bottomMargin=MARGIN_SIZE)
        main_frame = Frame(MARGIN_SIZE, MARGIN_SIZE, PAGE_SIZE[0] - 2 * MARGIN_SIZE, PAGE_SIZE[1] - 2 * MARGIN_SIZE,
                           leftPadding=0, rightPadding=0, bottomPadding=0, topPadding=0, id='main_frame')
        main_template = PageTemplate(id='main_template', frames=[main_frame])
        doc.addPageTemplates([main_template])
        doc.build(story)
Ejemplo n.º 36
0
    def set_footer(self, canvas, doc):
        if not self.has_footer():
            return

        f = Frame(  # (x1,y1) <-- lower left corner
            x1=doc.leftMargin,
            y1=doc.bottomMargin - self.footer_height,
            width=doc.
            width,  # doc.width = doc.pagesize[1] - doc.leftMargin - doc.rightMargin
            height=self.footer_height,
            leftPadding=1,
            bottomPadding=1,
            rightPadding=1,
            topPadding=1,
            id=None,
            showBoundary=0,
            overlapAttachedSpace=None,
            _debug=None,
        )
        f.addFromList(
            self._get_header_or_footer_story("footer", canvas, doc)[:], canvas)
Ejemplo n.º 37
0
 def __init__(self):
     super().__init__(pagesize=pagesizes.A4,
                      frames=Frame(
                          x1=self.margins,
                          y1=self.margins,
                          width=pagesizes.A4[0] - self.margins * 2,
                          height=pagesizes.A4[1] - self.margins * 2,
                          leftPadding=0,
                          bottomPadding=0,
                          rightPadding=0,
                          topPadding=0,
                      ))
Ejemplo n.º 38
0
    def get_frames(self, doc):
        from reportlab.platypus import Frame

        self.frame = Frame(doc.leftMargin, doc.bottomMargin,
                           doc.width,
                           doc.height,
                           leftPadding=0,
                           rightPadding=0,
                           topPadding=0,
                           bottomPadding=0,
                           id='normal')
        return [self.frame]
Ejemplo n.º 39
0
 def __init__(self, id, pageSize=A4):
     self.pageWidth = pageSize[0]
     self.pageHeight = pageSize[1]
     self.pageWidth = pageSize[0]
     self.pageHeight = pageSize[1]
     frame2 = Frame(2.54 * cm,
                    1.25 * cm,
                    self.pageWidth - 2 * 2.54 * cm,
                    self.pageHeight - 2.54 * cm - 1.25 * cm -
                    (title_1_style.fontSize * 2),
                    id='Normal')
     PageTemplate.__init__(self, id, [frame2])  # note lack of onPage
Ejemplo n.º 40
0
def build_pdf(filename, flowables):
    doc = BaseDocTemplate(filename)
    doc.addPageTemplates([
        PageTemplate(frames=[
            Frame(doc.leftMargin,
                  doc.bottomMargin,
                  doc.width,
                  doc.height,
                  id=None),
        ]),
    ])
    doc.build(flowables)
Ejemplo n.º 41
0
 def __init__(self, id, pageSize=A4):
     self.pageWidth = pageSize[0]
     self.pageHeight = pageSize[1]
     self.pageWidth = pageSize[0]
     self.pageHeight = pageSize[1]
     frame3 = Frame(2.54 * cm,
                    1.25 * cm,
                    self.pageWidth - 2 * 2.54 * cm,
                    self.pageHeight - 2.54 * cm - 1.25 * cm - 1.75 * cm -
                    (title_1_style.fontSize * 2) - logo_height,
                    id='Credits')
     PageTemplate.__init__(self, id, [frame3])  # note lack of onPage
Ejemplo n.º 42
0
 def __init__(self, pdf_template_filename, name=None):
     frames = [
         Frame(0.85 * inch, 0.5 * inch, PAGE_WIDTH - 1.15 * inch,
               PAGE_HEIGHT - (1.5 * inch))
     ]
     PageTemplate.__init__(self, name, frames)
     # use first page as template
     page = PdfReader(pdf_template_filename).pages[0]
     self.page_template = pagexobj(page)
     # Scale it to fill the complete page
     self.page_xscale = PAGE_WIDTH / self.page_template.BBox[2]
     self.page_yscale = PAGE_HEIGHT / self.page_template.BBox[3]
 def init_reportlab(self, save_to_file=True):
     self.styles = getSampleStyleSheet()
     self.buff = BytesIO()
     self.doc = BaseDocTemplate(os.path.join(self.output_path, self.filename) if save_to_file else self.buff,
                                pagesize=self.page_format,
                                leftMargin=self.page_margin * cm,
                                rightMargin=self.page_margin * cm,
                                topMargin=self.page_margin * cm,
                                bottomMargin=self.page_margin * cm,
                                showBoundary=0,
                                allowSplitting=1)
     # define styles for paragraphs
     self.styles.add(ParagraphStyle(
         'Header',
         fontSize=self.font_size,
         fontName=self.font_name,
         spaceBefore=self.space_before,
         spaceAfter=self.space_after,
         leading=self.font_size,
         alignment=TA_CENTER
     ))
     self.styles.add(ParagraphStyle(
         'Move_Text',
         fontSize=self.font_size,
         fontName=self.font_name,
         spaceBefore=self.space_before,
         spaceAfter=self.space_after,
         leading=self.font_size,
     ))
     # TODO: Add more Layouts
     if False:
         pass
     elif self.page_layout == 'two_col':
         frame_width = self.doc.width / 2 - self.col_gap / 2 * cm
         frame1 = Frame(self.doc.leftMargin, self.doc.bottomMargin, frame_width, self.doc.height, id='col1')
         frame2 = Frame(self.doc.leftMargin + frame_width + self.col_gap * cm, self.doc.bottomMargin, frame_width, self.doc.height, id='col2')
         self.doc.addPageTemplates([PageTemplate(id='twoCol', frames=[frame1, frame2])])
         # Set board dimensions relative to the two column layout
         self.board_length = 0.8 * frame_width / cm  # in cm
         self.tile_length = self.board_length / 8  # in cm
Ejemplo n.º 44
0
def exportToPDF(alltext):

	styles = getSampleStyleSheet()
	styleN = styles['Normal']
	styleH = styles['Heading1']
	# Cited from https://www.reportlab.com/docs/reportlab-userguide.pdf
	body = ParagraphStyle(fontName='Times', fontSize=12, name="TOCHeading1",
 			firstLineIndent=40, leading=16,spaceAfter = 6, spaceBefore = 6)
	heading = ParagraphStyle(fontName='Times-Bold', fontSize=16, name="TOCHeading1",
			leading=16,spaceAfter = 12, spaceBefore = 6, alignment=1)
	heading1 = ParagraphStyle(fontName='Times-Bold', fontSize=14, name="TOCHeading1",
			firstLineIndent=10, leading=16,spaceAfter = 12, spaceBefore = 6)
	heading2 = ParagraphStyle(fontName='Times-Bold', fontSize=12, name="TOCHeading1",
			firstLineIndent=15, leading=16,spaceAfter = 12, spaceBefore = 6)
	story = []

	# add some flowables
	title = Paragraph("Work Log",heading)
	story.append(title)

	modeList = sort.filterByMode(alltext,usefulMode = [0,1,2])
	for i in range(len(modeList)):
		# drawString mode
		modeName = user.mode[i]
		p = Paragraph(modeName,heading1)
		story.append(p)
		d = filterByTime(modeList[i])
		# drawString day
		for key in d:
			k = str(key)[1:-1]
			story.append(Paragraph(k,heading2))
			story.extend(drawTime(d[key], body))

	c = canvas.Canvas("Work.pdf", pagesize=letter)
	c.setLineWidth(.3)
	c.setFont('Helvetica', 12)

	f = Frame(inch, inch, 7*inch, 9*inch)
	f.addFromList(story,c)
	c.save()
Ejemplo n.º 45
0
    def test01(self):
        """A Frame consumes the story while rendering.
      But this can be avoided by using list(story)
      """
        c = Canvas('test01.pdf')
        f = Frame(inch, inch, 2 * inch, 9 * inch, showBoundary=1)
        f.addFromList(list(self.story), c)
        self.assertEqual(len(self.story), 2)

        f = Frame(4 * inch, inch, 2 * inch, 9 * inch, showBoundary=1)
        f.addFromList(self.story, c)
        self.assertEqual(len(self.story), 0)

        c.save()
Ejemplo n.º 46
0
    def setStyleSheet(self, aStyleSheet):
        self.style = aStyleSheet

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

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

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

        self.doc.setDefaultTemplate(self.orientation)
Ejemplo n.º 47
0
def build_pdf(filename, content):
    doc = BaseDocTemplate(filename, showBoundary=0)
    # doc.watermark = 'Draft'
    doc.addPageTemplates([
        PageTemplate(frames=[
            Frame(doc.leftMargin,
                  doc.bottomMargin,
                  doc.width,
                  doc.height,
                  id=None),
        ]),
    ])
    doc.build(content, canvasmaker=NumberedCanvas)
Ejemplo n.º 48
0
def addFrame(x1,
             y1,
             width,
             height,
             leftPadding=6,
             bottomPadding=6,
             rightPadding=6,
             topPadding=6,
             id=None,
             showBoundary=0):
    #creates a Frame object
    return Frame(x1, y1, width, height, leftPadding, bottomPadding,
                 rightPadding, topPadding, id, showBoundary)
Ejemplo n.º 49
0
def main1():
    file = "base3.html"
    # file = "fe_data0.html"
    f = open(file, "r")
    st = f.read()
    elements = []
    makePDF(st, elements)

    doc = SimpleDocTemplate("test.pdf", pagesize=letter)
    frame = Frame(15, 15, 580, 760, id='col1', showBoundary=1)  # 610x790
    Page = PageTemplate(id='col1', frames=[frame])
    doc.addPageTemplates([Page])
    doc.build(elements)
Ejemplo n.º 50
0
def run():
    styles = getSampleStyleSheet()
    styleN = styles['Normal']
    styleH = styles['Heading1']
    story = []

    story.append(Paragraph('I2of5', styleN))
    story.append(I2of5(1234, xdim=inch * 0.02, checksum=0))
    story.append(Paragraph('MSI', styleN))
    story.append(MSI(1234, xdim=inch * 0.02))
    story.append(Paragraph('Codabar', styleN))
    story.append(Codabar("A012345B", xdim=inch * 0.02))
    story.append(Paragraph('Code 11', styleN))
    story.append(Code11("01234545634563"))
    story.append(Paragraph('Code 39', styleN))
    story.append(Standard39("A012345B%R"))
    story.append(Paragraph('Extended Code 39', styleN))
    story.append(Extended39("A012345B}"))
    story.append(Paragraph('Code93', styleN))
    story.append(Standard93("CODE 93"))
    story.append(Paragraph('Extended Code93', styleN))
    story.append(Extended93("L@@K! Code 93 :-)"))  #, xdim=0.005 * inch))
    story.append(Paragraph('Code 128', styleN))
    c = Code128("AB-12345678")  #, xdim=0.005 * inch)
    #print 'WIDTH =', (c.width / inch), 'XDIM =', (c.xdim / inch)
    #print 'LQ =', (c.lquiet / inch), 'RQ =', (c.rquiet / inch)
    story.append(c)
    story.append(Paragraph('USPS FIM', styleN))
    story.append(FIM("A"))
    story.append(Paragraph('USPS POSTNET', styleN))
    story.append(POSTNET('78247-1043'))
    story.append(Paragraph('Label Size', styleN))
    story.append(XBox((2.0 + 5.0 / 8.0) * inch, 1 * inch, '1x2-5/8"'))
    story.append(Paragraph('Label Size', styleN))
    story.append(XBox((1.75) * inch, .5 * inch, '1/2x1-3/4"'))
    c = Canvas('out.pdf')
    f = Frame(inch, inch, 6 * inch, 9 * inch, showBoundary=1)
    f.addFromList(story, c)
    c.save()
Ejemplo n.º 51
0
 def __init__(self, *args, **kwargs):
     self.has_title_page = kwargs.pop('has_title_page', False)
     frame = Frame(
         left_margin, bottom_margin, frame_width, frame_height,
         id='normal',
         leftPadding=0, topPadding=0, rightPadding=0, bottomPadding=0
     )
     pageTemplates = [
         PageTemplate(id='standard', frames=[frame])
     ]
     BaseDocTemplate.__init__(
         self, pageTemplates=pageTemplates, *args, **kwargs
     )
Ejemplo n.º 52
0
    def build_card_for_entry(self, canvas, entry):
        """Create a card for the given backlog item."""
        assignee = entry["assignee"]
        rank = entry["rank"]

        card_color, first_line_style = self.get_first_line_style(assignee)
        rank_style = self.get_rank_style(rank, assignee, first_line_style)

        frame_content = []

        table_data = self.get_table_data(entry, first_line_style, rank_style)

        card_frame = Frame(self.start_x,
                           self.start_y,
                           width=14.5 * layout_units.cm,
                           height=8.5 * layout_units.cm,
                           showBoundary=0)

        card_style = TableStyle([
            ('BACKGROUND', (0, 0), (1, 0), card_color),
            ('VALIGN', (0, 0), (1, 0), "MIDDLE"),
            ('BOTTOMPADDING', (0, 0), (1, 0), 14),
            ('VALIGN', (0, 1), (-1, -1), "TOP"),
            ('INNERGRID', (0, 0), (-1, -1), 0.9, reportlab_colors.black),
            ('BOX', (0, 0), (-1, -1), 0.9, reportlab_colors.black)
        ])
        table = Table(
            data=table_data,
            colWidths=[2.7 * layout_units.cm, 11.3 * layout_units.cm],
            rowHeights=[
                1.2 * layout_units.cm, 3.4 * layout_units.cm,
                2.1 * layout_units.cm, 1.2 * layout_units.cm
            ])
        table.setStyle(card_style)

        frame_content.append(table)
        card_frame.addFromList(frame_content, canvas)

        self.get_new_card_position(canvas)
Ejemplo n.º 53
0
 def _get_first_page_frames(self, doc):
     footer_length = 3.5 * len(self.invoice.footer_text.split('\n')) * mm
     return [
         Frame(doc.leftMargin,
               doc.bottomMargin,
               doc.width,
               doc.height - 95 * mm,
               leftPadding=0,
               rightPadding=0,
               topPadding=0,
               bottomPadding=footer_length,
               id='normal')
     ]
Ejemplo n.º 54
0
def writepdf(number, effort, times, p, jpg, canvas):
    for frmt in range(times):
        styles = getSampleStyleSheet()
        styleN = styles['Normal']
        styleN.spaceBefore = 10
        styleN.spaceAfter = 10
        styleH = styles['Heading1']
        styleH.alignment = 1
        styleN.alignment = 1
        story = []
        for i in range(5):
            story.append(Paragraph('<br/>', styleH))
        if effort:
            story.append(Paragraph('%i' % number, styleH))
            story.append(Paragraph('Harvest %i000 calories' % number, styleN))
        else:
            story.append(
                Paragraph('<font color="blue">%i</font>' % number, styleH))

        canvas.saveState()
        f = Frame(spacer + p[0] * width,
                  spacer + p[1] * height,
                  width,
                  height,
                  showBoundary=1)
        f.addFromList(story, canvas)
        canvas.restoreState()
        if jpg:
            canvas.showPage()
        elif p == (3, 3):
            canvas.showPage()
            p = (0, 0)
        else:
            if p[1] == 3:
                p = (p[0] + 1, 0)
            else:
                p = (p[0], p[1] + 1)

    return p
Ejemplo n.º 55
0
def portfolio_return_block(df: pd.DataFrame, block_position: BlockPosition):
    """Формирует блок pdf-файла с информацией доходности портфеля и индекса

    В левой части располагается табличка, а в правой части диаграмма
    """
    block_header = Paragraph('Portfolio Return', BLOCK_HEADER_STYLE)
    table = make_pdf_table(df)
    frame = Frame(block_position.x,
                  block_position.y,
                  block_position.width * LEFT_PART_OF_BLOCK,
                  block_position.height,
                  leftPadding=0,
                  bottomPadding=0,
                  rightPadding=0,
                  topPadding=6,
                  showBoundary=0)
    frame.addFromList([block_header, table], block_position.canvas)
    image = make_plot(df, block_position.width * (1 - LEFT_PART_OF_BLOCK),
                      block_position.height)
    image.drawOn(block_position.canvas,
                 block_position.x + block_position.width * LEFT_PART_OF_BLOCK,
                 block_position.y)
Ejemplo n.º 56
0
 def CreateTemplateFrames(self):
     return [
         Frame(self.nLeft,
               self.nBottom,
               self.pageWidth - (self.nLeft + self.nRight),
               0.65 * self.pageHeight - self.nBottom,
               id='chcover',
               leftPadding=0,
               bottomPadding=0,
               rightPadding=0,
               topPadding=0,
               showBoundary=0)
     ]
Ejemplo n.º 57
0
 def controlPage(self) -> None:
     # ==================== Card Back ========================
     # Draw on the canvas
     f = Frame(INCH / 2, INCH / 2, self.width - INCH, self.height - INCH)
     tlist = f.split(self.controlTable, self.canvas)
     while len(tlist) > 0:
         f.addFromList(tlist, self.canvas)
         self.canvas.showPage()
         # Not exactly sure why a new fram is needed here ¯\_(ツ)_/¯
         f = Frame(INCH / 2, INCH / 2, self.width - INCH,
                   self.height - INCH)
Ejemplo n.º 58
0
def squeeze_text_into_box(canvas,
                          text,
                          x0,
                          y0,
                          x1,
                          y1,
                          units=inch,
                          style=default_style,
                          escape=True):
    if escape:
        text = escape_html(text).replace('\n', '<br/>')
    frame = Frame(x0 * units,
                  y0 * units, (x1 - x0) * units, (y1 - y0) * units,
                  leftPadding=2,
                  rightPadding=2,
                  topPadding=0,
                  bottomPadding=4,
                  showBoundary=0)
    current_style = style
    current_size = style.fontSize
    while True:
        story = [Paragraph(text, current_style)]
        frame.addFromList(story, canvas)
        if len(story) == 0:
            break  # Story empty, so all text was successfully flowed into frame
        if current_size > 6:
            current_size -= 1
        elif current_size > 3:
            current_size -= 0.5
        elif current_size > 1:
            current_size -= 0.1
        else:
            raise Exception(
                "Could not squeeze text into box, even with a font size of 1 point."
            )
        current_style = ParagraphStyle("temp_style",
                                       parent=style,
                                       fontSize=current_size,
                                       leading=current_size)
Ejemplo n.º 59
0
def drawBox(c, e, x, y):

    c.setFillColorRGB(1, 1, 1)

    for cl in colors:
        if cl[0] and e.location.upper() != cl[0]:
            continue
        if cl[1] and e.startdate.upper() != cl[1]:
            continue
        if cl[2] and e.status.upper() != cl[2]:
            continue
        c.setFillColor(HexColor(cl[3]))

        break

    c.setStrokeColor(HexColor('#E8E8E8'))
    c.rect(x - boxw / 2, y - boxh / 2, boxw, boxh, fill=1)
    f = Frame(x - boxw / 2,
              y - boxh / 2,
              boxw,
              boxh,
              leftPadding=1,
              bottomPadding=1,
              rightPadding=1,
              topPadding=3,
              showBoundary=1)
    f2 = Frame(x - boxw / 2,
               y - boxh + 21,
               boxw,
               11,
               leftPadding=1,
               bottomPadding=1,
               rightPadding=2,
               topPadding=3,
               showBoundary=0)

    lines = []

    if e.startdate.upper() == 'OPEN':
        lines.append(Paragraph('OPEN-' + e.status, styleH))
    else:
        lines.append(Paragraph(e.name, styleH))

    lines.append(Paragraph(e.title, styleN))
    lines2 = []
    lines2.append(Paragraph(e.desk, styleB))
    f2.addFromList(lines2, c)
    f.addFromList(lines, c)
    c.setStrokeColor(HexColor('#000000'))
Ejemplo n.º 60
0
def gen_pdf(request, template=None):
    h_orientacion = 'Titulo_' + template.header_id.orientacion
    f_orientacion = 'Footer_' + template.footer_id.orientacion
    response, buff = init_pdf_doc()
    doc = SimpleDocTemplate(
        buff,
        pagesize=letter,
        rightMargin=40,
        leftMargin=40,
        topMargin=60,
        bottomMargin=18,
    )
    t = []
    #cambiar el path a relativo - se usa full path para desarrollo
    #path relativo
    # archivo_imagen2 = settings.MEDIA_ROOT+'/header/logo/login.png'
    #full path
    header_tmp = template.header_id.header
    content1 = str(header_tmp).replace('\n', '<br />\n')
    print(content1)
    header = Paragraph(content1, get_styles_customs(h_orientacion))
    logo = settings.MEDIA_ROOT + '/' + str(template.header_id.logo)
    imagen = Image(logo, width=80, height=60, hAlign='RIGHT')
    t.append(imagen)
    t.append(header)
    t.append(Paragraph('Rp./', get_styles_customs('Titulo2_I')))
    legend = request.POST.get('descripcion')
    content = str(legend).replace('\n', '<br />\n')

    t.append(
        Paragraph(content,
                  get_styles_customs('Normal_' + template.orientacion)))

    frame = Frame(doc.leftMargin,
                  doc.bottomMargin,
                  doc.width,
                  doc.height,
                  id='normal')
    header_content = Paragraph(template.footer_id.footer,
                               get_styles_customs(f_orientacion))
    template = PageTemplate(id='test',
                            frames=frame,
                            onPage=partial(header_footer,
                                           content=header_content))
    doc.addPageTemplates([template])

    doc.build(t)
    response.write(buff.getvalue())
    buff.close()

    return response