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'))
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()
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()
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)
def get(self, request, *args, **kwargs): """ Returns the response containing a reportlab generated PDF. """ # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename=learningprogress_note_cards.pdf' # Create the PDF object, using the response object as its "file". pdf = canvas.Canvas(response) styles = getSampleStyleSheet() # Get all cards with their stories. cards = [] max_comment_length = 500 for usersectionrelation in self.get_queryset(): # Delete attributes from span tags. comment = BeautifulSoup(usersectionrelation.comment, 'html.parser') for tag in comment.find_all('span'): del tag.attrs # Parse the card. story = [] story.append(Paragraph( usersectionrelation.section.name, styles['Heading2'])) story.append(Paragraph( usersectionrelation.section.notes, styles['Normal'])) if len(str(comment)) <= max_comment_length: story.append(Paragraph( str(comment), styles['Normal'])) else: story.append(Paragraph( _('Sorry, your comment is too long.'), styles['Normal'])) cards.append(story) # Add cards to PDF object. width, height = A4 if len(cards) % 2 != 0: cards.append('') while True: for i in range(3): if len(cards) == 0: break h = height * 2/3 - height * 1/3 * i f1 = Frame(0, h, width/2, height * 1/3, showBoundary=1) f2 = Frame(width/2, h, width/2, height * 1/3, showBoundary=1) f1.addFromList(cards.pop(0), pdf) f2.addFromList(cards.pop(0), pdf) else: pdf.showPage() continue pdf.showPage() break # Close the PDF object cleanly and we're done. pdf.save() return response
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)
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 Marrakech: +212 6 89 91 77 20 """, styles['remarque'])], canvas) canvas.save()
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)
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)
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
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")
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()
def add_page4(self): w = self.m_width h = self.m_height frame = Frame(w / 4, h / 4, w / 2, h / 2, showBoundary=1) story = [] story.append(self.get_image('meso.png', width=w / 2)) frame.addFromList(story, self.m_canvas) self.m_canvas.showPage()
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()
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()
def get(self, request, *args, **kwargs): """ Returns the response containing a reportlab generated PDF. """ # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') response[ 'Content-Disposition'] = 'attachment; filename=learningprogress_note_cards.pdf' # Create the PDF object, using the response object as its "file". pdf = canvas.Canvas(response) styles = getSampleStyleSheet() # Get all cards with their stories. cards = [] max_comment_length = 500 for usersectionrelation in self.get_queryset(): story = [] story.append( Paragraph(usersectionrelation.section.name, styles['Heading2'])) story.append( Paragraph(usersectionrelation.section.notes, styles['Normal'])) if len(usersectionrelation.comment) <= max_comment_length: story.append( Paragraph(usersectionrelation.comment, styles['Normal'])) else: story.append( Paragraph(_('Sorry, your comment is too long.'), styles['Normal'])) cards.append(story) # Add cards to PDF object. width, height = A4 if len(cards) % 2 != 0: cards.append('') while True: for i in range(3): if len(cards) == 0: break h = height * 2 / 3 - height * 1 / 3 * i f1 = Frame(0, h, width / 2, height * 1 / 3, showBoundary=1) f2 = Frame(width / 2, h, width / 2, height * 1 / 3, showBoundary=1) f1.addFromList(cards.pop(0), pdf) f2.addFromList(cards.pop(0), pdf) else: pdf.showPage() continue pdf.showPage() break # Close the PDF object cleanly and we're done. pdf.save() return response
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)
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 )
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 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'))
def _generate_addressfield(c, styles, name, address, city): addressfield = [] backaddress = [Paragraph("AStA KIT Adenauerring 7, 76131 Karlsruhe", styles['Bullet'])] addressfield.append(Paragraph("Test", styles['Normal'])) f1 = Frame(2.5*cm, height-(2.7+0.5)*cm, 8*cm, 0.5*cm, showBoundary=1) f2 = Frame(2.5*cm, height-(2.7+0.5+4)*cm, 8*cm, (2.73+1.27)*cm, showBoundary=1) f1.addFromList(backaddress,c) f2.addFromList(addressfield,c) return c
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)
def write(self, outputFile): """Writes the modified pdf to a file. This method merges the original pdf with all of the added text fields together to create the final modified pdf. Text fields are written over top of the original pdf. Args: outputFile (str or file): Output file to write to. Can be string path or any file-like object. Returns: None """ # iterate through original pdf pages output = PdfFileWriter() for pagenum in range(self.pdf.numPages): existing_page = self.pdf.getPage(pagenum) # insert text fields if any for this page if len(self[pagenum]) > 0: mediaBox = self.pdf.getPage(pagenum).mediaBox pagesize = (mediaBox[2] - mediaBox[0], mediaBox[3] - mediaBox[1]) packet = BytesIO() canvas = Canvas(packet, pagesize=pagesize) if self.boxes: canvas.setStrokeColorRGB(*self.boxes) for field in self[pagenum]: frame = Frame(field.x1, field.y1, field.width, field.height, *field.padding, showBoundary=bool(self.boxes)) style = field.style or self.style story = [Paragraph(field.text, style)] story_inframe = KeepInFrame(field.width, field.height, story) frame.addFromList([story_inframe], canvas) canvas.save() packet.seek(0) new_pdf = PdfFileReader(packet) existing_page.mergePage(new_pdf.getPage(0)) output.addPage(existing_page) # write the final pdf to the file if isinstance(outputFile, basestring): outputFile = open(outputFile, "wb") output.write(outputFile) outputFile.close() else: output.write(outputFile)
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
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 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")
def write_tile(values=None, conversion_cost=None, front_img=None, back_img=None, pos=None, canvas=None): styles = getSampleStyleSheet() styleN = styles['Normal'] styleN.spaceBefore = 10 styleN.spaceAfter = 10 styleN.textColor = black styleH = styles['Heading1'] styleH.textColor = black styleH.alignment = 1 styleN.alignment = 1 canvas.saveState() canvas.rect(spacer + pos[0] * 47 * mm, 5 * mm + pos[1] * 94 * mm, 47 * mm, 94 * mm, fill=0, stroke=1) #canvas.drawImage(front_img, spacer + pos[0] * 47 * mm, 5 * mm + pos[1] * 94 * mm + 47 * mm, 47 * mm, 47 * mm) #if back_img is not None: #canvas.drawImage(back_img, spacer + pos[0] * 47 * mm, 5 * mm + pos[1] * 94 * mm, 47 * mm, 47 * mm) f = Frame(spacer + pos[0] * 47 * mm, pos[1] * 94 * mm - 5 * mm, 47 * mm, 47 * mm, showBoundary=0) if values is not None: table = Table(values, style=[('TEXTCOLOR', (0, 0), (1, 2), black), ('SIZE', (0, 0), (1, 2), 14)]) f.addFromList([table], canvas) f = Frame(spacer + pos[0] * 47 * mm, pos[1] * 94 * mm + 35 * mm, 47 * mm, 47 * mm, showBoundary=0) if conversion_cost is not None: f.addFromList([Paragraph('%s' % conversion_cost, styleH)], canvas) canvas.restoreState() if pos == (2, 2): canvas.showPage() pos = (0, 0) else: if pos[1] == 2: pos = (pos[0] + 1, 0) else: pos = (pos[0], pos[1] + 1) return pos
def render_card_pdf(card, filename): # set up styles regular = ParagraphStyle('default') regular.fontName = 'Helvetica' regular.fontSize = 9 regular.leading = 11 small = ParagraphStyle('default') small.fontName = 'Helvetica' small.fontSize = 7 small.leading = 9 large = ParagraphStyle('default') large.fontName = 'Helvetica' large.fontSize = 11 large.leading = 13 text = [] # generate content address_template = Template(address_format) # return address text.extend([Paragraph(address_template.render(Context({ 'name': card.sender_name, 'address1': card.sender_address1, 'address2': card.sender_address2, 'city': card.sender_city, 'state': card.sender_state, 'zip': card.sender_zip, })), small), Spacer(10, 10)]) text.append(Paragraph(strip_tags(card.message).replace('\n', '<br />'), regular)) text.extend([Spacer(10, 10), HR(0.5), Spacer(10, 10)]) text.append(Paragraph('The Sunlight Foundation is a non-partisan non-profit that uses cutting-edge technology and ideas to make government transparent and accountable. Visit SunlightFoundation.com to learn more.', small)) canv = Canvas(filename) canv.setPageSize((6.25 * inch, 4.5 * inch)) f = Frame(0.375 * inch, 0.75 * inch, 3.125 * inch, 3.375 * inch, showBoundary=0) f.addFromList(text, canv) address = Frame(3.75 * inch, 1 * inch, 2 * inch, 1.5 * inch, showBoundary=0) address.addFromList([Paragraph(address_template.render(Context({ 'name': card.recipient_name, 'address1': card.recipient_address1, 'address2': card.recipient_address2, 'city': card.recipient_city, 'state': card.recipient_state, 'zip': card.recipient_zip, })), large)], canv) canv.save()
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()
def populate_pdf_form(template_file, message_class): """ Read in a PDF with form fields and apply the string contents of the messageDict dictionary to the cooresponding form fields. """ template = PdfReader(template_file) data = io.BytesIO() pdf = canvas.Canvas(data) for page in template.Root.Pages.Kids: for field in page.Annots: label = field.T key = message_class.data_map.get(label[1:-1], '') if 'value' in key: value = str(key.get('value', 'Test')) else: value = "TEST" if 'padding_top' in key: padding_top = key.get('padding_top', '') else: padding_top = message_class.defaults.get('padding_top', '') styles = message_class.styles box_sides = box_sides_in(field.Rect) left = min(box_sides[0], box_sides[2]) bottom = min(box_sides[1], box_sides[3]) width = box_sides[2] - box_sides[0] height = box_sides[3] - box_sides[1] form_field = Frame(left, bottom, width, height, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=padding_top, showBoundary=0) story = [Paragraph(value, styles['default'])] story_inframe = KeepInFrame(width, height, story) form_field.addFromList([story_inframe], pdf) pdf.showPage() pdf.save() data.seek(0) return data
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()
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()
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()
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)
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)
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()
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)
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()
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()
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()
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()
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()
def makedoc(somedata, depart, month, half, headers, footers, tstyle, canv, colW=None, rowH=None, TableAlign=None, FrameX=20, FrameY=430, FrameW=575 - 20, FrameH=320): """ somedata: The Table data to display in main frame. depart: The name to display on top left. month: The name of month to display at top left. half: The part of month to display at top left. (1-15, 15-end, nothing) headers: The header names of the data in table. footers: The sums etc to show at the last row of table. tstyle: The tablestyle, where to draw grid etc. canv: The reportlab Canvas on which to draw all elements. """ # Letter is width : 612, Height: 792 # A4 is width : 595.2755, Height: 841.8897 myCanvas = canv myCanvas.saveState() myCanvas.setFont('Helvetica', 9) myCanvas.setLineWidth(.3) width, height = A4 makeHeader(myCanvas, depart, month, half) MainFrame = Frame(FrameX, FrameY, FrameW, FrameH, showBoundary=0, id="MainFrame") tabledata = somedata tabledata.insert(0, headers) tabledata.extend(footers) MainFrameTable = Table(tabledata, colW, rowH, style=tstyle, hAlign=TableAlign) MainFrame.addFromList([MainFrameTable], myCanvas) myCanvas.restoreState()
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'))
def draw_image_svg(c, rect, sheet, img, **kwargs): from svglib.svglib import svg2rlg from reportlab.graphics import renderPDF, renderPM from reportlab.platypus import Image c.saveState() rect = dict(rect) for key, val in rect.items(): if 'w' in key: rect[key] = rect[key] * sheet[0] elif 'h' in key: rect[key] = rect[key] * sheet[1] # KWARGS DATA VALIDATION # kwarg_list = {'l_pad': 0, 'r_pad': 0, 'b_pad': 0, 't_pad': 0, 'bbox': 0} valid = False ans = '' if len(kwargs) > 5: ans = 'Only 5 kwargs may be specified' elif not (set(kwargs) <= set(kwarg_list)): ans = 'One of the params introduced is not expected' else: valid = True # END DATA VALIDATION # if valid == True: for key, value in kwargs.items(): kwarg_list[key] = kwargs[key] rect['w_l'] += kwarg_list['l_pad'] rect['h_b'] += kwarg_list['b_pad'] rect['w_c'] -= (kwarg_list['r_pad'] + kwarg_list['l_pad']) rect['h_c'] -= (kwarg_list['t_pad'] + kwarg_list['b_pad']) drawing = svg2rlg(img) Img = Image(drawing, width=rect['w_c'], height=rect['h_c']) f = Frame(rect['w_l'], rect['h_b'], rect['w_c'], rect['h_c'], showBoundary=kwarg_list['bbox'], leftPadding=0, rightPadding=0, bottomPadding=0, topPadding=0) story = [Img] f.addFromList(story, c) c.restoreState()
def test(filename): # Convert HTML to "Reportlab Story" structure story = pisa.pisaStory(""" <h1>Sample</h1> <p>Hello <b>World</b>!</p> """ * 20).story # Draw to Canvas c = Canvas(filename) f = Frame(inch, inch, 6 * inch, 9 * inch, showBoundary=1) f.addFromList(story, c) c.save() # Show PDF pisa.startViewer(filename)
def add_page5(self): w = self.m_width h = self.m_height frame = Frame(0, 0, w / 4, h - 4 * cm, showBoundary=1) story = [] styles = getSampleStyleSheet() style = styles["Code"] style.alignment = TA_LEFT lines = data.split("\n") for l in lines: story.append(Paragraph(l, style)) frame.addFromList(story, self.m_canvas) self.m_canvas.showPage()
def createFrame(self, text, width=2 * inch, height=2 * inch, drawBorder=False, textJustify='left', frameJustify='left', fontSize=14, fontName=None, space=None, shift=True): #Set the defaults if fontName is None: fontName = self.fonts[0] if space is None: space = fontSize #Create paragraph but put in list of story story = [] story.append( self.createParagraph(text, return_para=True, fontSize=fontSize, fontName=fontName, justify=textJustify)) #Shift vertically if we need to if shift: self.shiftPos(height + space) #Worry about box justification if frameJustify == 'left': start = self.pos[0] elif frameJustify == 'right': start = self.pos[0] + self.mwidth - width elif frameJustify == 'center': start = self.pos[0] + self.mwidth / 2 - width / 2 else: logger.error( "Error in sheets.createFrame...frameJustify has invalid input") if drawBorder: f = Frame(start, self.pos[1], width, height, showBoundary=1) else: f = Frame(start, self.pos[1], width, height, showBoundary=0) #Create frame on page f.addFromList(story, self.c)
def drawPage(c, page, title, info=False): width, height = landscape(A4) TOP = 35 if BIG: width, height = landscape(A1) TOP = 100 if info: drawSummaryBox(width - 90, 100) employees = page.employees roots = [e for e in employees if e.level == page.maxlevel] mw = 0 for e in roots: w, h = calcBoxEmpTree(e) mw += w x = 20 uw = (width - 40) / mw for e in roots: w, h = calcBoxEmpTree(e) drawEmployees(c, e, x, height - TOP, uw * w, height - TOP) x += uw * w f = Frame(0, height - 35, width, 20, leftPadding=1, bottomPadding=1, rightPadding=1, topPadding=1, showBoundary=0) lines = [] lines.append(Paragraph(title, styleTitle)) f.addFromList(lines, c) # stats lc = [0] * (page.maxlevel + 1) for e in employees: if not e.visible: continue lc[e.level] += 1 c.showPage()
def add_text(self, text): items = [ Paragraph(text, ParagraphStyle(name='Normal', fontSize=3, leading=0)) ] f = Frame(self.x, self.y - 6, 50, 10, showBoundary=0, leftPadding=1, bottomPadding=0, rightPadding=0, topPadding=0) f.addFromList(items, self.canvas)
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=_baseFontName, 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)
def create(self): styleN = styles['Normal'] styleN.alignment = TA_LEFT story = [] story.append(Paragraph(self.note, styleN)) if np.mod(self.pos, 2): col = 1 row = (self.pos - 1) / 2 + 1 else: col = 2 row = self.pos / 2 f = Frame(((col - 1) * 4 + 0.15) * inch, (7.5 - (row - 1) * 3.5) * inch, 4. * inch, 3.25 * inch, showBoundary=BOUND) f.addFromList(story, self.c)
def getPDF(): url = request.args.get("url") description = request.args.get("desc") image = ImageReader(url) c = canvas.Canvas('data/output.pdf', pagesize=letter) c.drawImage(image, 100, 325, width=400, height=400, mask='auto') frame1 = Frame(0.25 * inch, 0.25 * inch, 8 * inch, 4 * inch, showBoundary=1) styles = getSampleStyleSheet() para = [Paragraph("Description: " + description, styles['Normal'])] para_inframe = KeepInFrame(8 * inch, 8 * inch, para) frame1.addFromList([para_inframe], c) c.save() return send_from_directory('data', "output.pdf")
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'))
def regular_page(c, title, fig_path): """ Creates regular page. title -- string, title of figure fig_path -- string, path to figure c -- canvas """ # display title # c.setFont("Helvetica-Bold", 20, leading=None) styles = getSampleStyleSheet() info = [] info.append(Paragraph(title, styles["Title"])) f = Frame(65, 670, 515, 100, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0, id=None, showBoundary=0) f.addFromList(info, c) # c.drawCentredString(325, 700, title) #display box with image c.setStrokeColorRGB(0.3, 0.4, 0.2) c.setFillColorRGB(0.3, 0.4, 0.2) c.rect(120, 270, 400, 400, stroke=0, fill=0) c.drawImage(fig_path, 120, 280, width=390, height=390, mask=None, preserveAspectRatio=True) # ## check if this is faster for func images: # ## c.drawInlineImage(self, image, x, y, width=None, height=None) watermark(c) footer(c, 0) side_bar(c)
def drawGroup(self, group): from svglib.document import Layer if isinstance(group, Layer): canvas = getattr(self, '_canvas', None) elements = [] for node in group.getContents(): elements.append(node) frame = Frame(0, 0, self._drawing.width, self._drawing.height, id=str(uuid.uuid4())) frame.id = 'TestLayer' frame.addFromList(elements, canvas) else: return super().drawGroup(group)
def main(): parser = argparse.ArgumentParser(description='Print inventory tags') parser.add_argument('-a', '--address', dest='address', help='set the path of the address to use', default="./address.txt") parser.add_argument('-i', '--inventory', dest='inventory', help='set the path of the inventory to use', default="./inventory.csv") parser.add_argument('-o', '--output', dest='output', help='set the path of the pdf to output', default="./inventory.pdf") args = parser.parse_args() instruments = instruments_from_csv(args.inventory) tag_width = 69 * mm tag_height = 98 * mm rows = 3 cols = 3 tag_index = 0 page = 0 canvas = Canvas(args.output, pagesize=A4) canvas.setFont('Courier', 16) for instrument in instruments: if not instrument.print_please(): continue if tag_index % (rows * cols) == 0: if page == 0: page = 1 else: canvas.showPage() page += 1 tag_index = 0 inst_text = text_from_instrument(instrument) col = tag_index % cols row = math.floor(tag_index / cols) x = col * tag_width y = row * tag_height parts = [] tag = Frame(x, y, tag_width, tag_height, showBoundary=1) parts.append(Paragraph(replace_new_lines(address(args.address)), address_style())) parts.append(Paragraph(replace_new_lines(inst_text), body_style())) tag.addFromList(parts, canvas) tag_index += 1 canvas.save()
def create(self): styleN = styles['Normal'] styleN.alignment = TA_CENTER story = [] self.c.setFillColor(white) story.append(self.c.rect(0, 0, 4. * inch, 3.25 * inch, fill=1)) if np.mod(self.pos, 2): col = 1 row = (self.pos - 1) / 2 + 1 else: col = 2 row = self.pos / 2 f = Frame(((col - 1) * 4 + 0.15) * inch, (7.5 - (row - 1) * 3.5) * inch, 4. * inch, 3.25 * inch, showBoundary=BOUND) f.addFromList(story, self.c)