def generateNumberedPages(numPages, pageSize, orientation, bgColor, outPath): "Generate a 10 page document with one big number per page." if orientation == "landscape": pageSize = landscape(pageSize) canv = Canvas(outPath, pagesize=pageSize) for i in range(numPages): canv.setFont("Helvetica", 500) text = "%s" % i if i % 2 == 0: canv.setStrokeColor(bgColor) canv.setFillColor(bgColor) canv.rect(0, 0, pageSize[0], pageSize[1], stroke=True, fill=True) canv.setFillColor(black) elif i % 2 == 1: canv.setStrokeColor(black) canv.setFillColor(black) canv.rect(0, 0, pageSize[0], pageSize[1], stroke=True, fill=True) canv.setFillColor(bgColor) if orientation == "portrait": canv.drawCentredString(pageSize[0]/2.0, pageSize[1]*0.3, "%s" % i) elif orientation == "landscape": canv.drawCentredString(pageSize[0]/2.0, pageSize[1]*0.21, "%s" % i) canv.showPage() canv.save()
def __init__( self, index: str, title: str = None, number_pages: bool = True, page_label_coords: tuple = (50, 3), rotate_landscape_pics: bool = True, evidentiary_disputes: str = None, ): """ This creates a bare-bones exhibit with only a cover sheet. You can then populate it by running add_doc() one or more times. """ # make a canvas write a cover page like "EXHIBIT 101" canvas = Canvas("never_save_to_this_path.pdf") canvas.setPageSize(pagesizes.letter) canvas.setFont("Helvetica", 32) x, y = canvas._pagesize[0] / 2, canvas._pagesize[1] / 7 canvas.drawCentredString(x, y, f"EXHIBIT {index}") canvas.showPage() # set this exhibit's various variables self.canvas: Canvas = canvas self.documents: list = [] self.index: str = index self.title: str = title self.evidentiary_disputes: str = evidentiary_disputes self.number_pages: bool = number_pages self.rotate_landscape_pics: bool = rotate_landscape_pics self.page_label_coords: tuple = page_label_coords self.page_count: int = 0
def test_06_fontsize(self): from reportlab.lib.pagesizes import A4 from reportlab.pdfgen.canvas import Canvas from reportlab.lib.units import inch from reportlab.lib.colors import red, magenta c = Canvas('demo.pdf', pagesize=A4) c.translate(inch, inch) c.setFont("Times-Roman", 20) c.setFillColor(red) c.saveState() c.drawCentredString(2.75 * inch, 2.5 * inch, "Font size excmples") c.setFillColor(magenta) size = 7 x = 2.3 * inch y = 1.3 * inch for line in range(7): c.setFont("Helvetica", size) c.drawRightString(x, y, "%s points" % size) c.drawString(x, y, "test") y = y - size * 1.2 size = size + 1.5 c.restoreState() c.drawString(0, 0, "%s" % c.getAvailableFonts()) c.showPage() c.save()
def generateNumberedPages(numPages, pageSize, orientation, bgColor, outPath): "Generate a 10 page document with one big number per page." if orientation == "landscape": pageSize = landscape(pageSize) canv = Canvas(outPath, pagesize=pageSize) for i in range(numPages): canv.setFont("Helvetica", 500) text = u"%s" % i if i % 2 == 0: canv.setStrokeColor(bgColor) canv.setFillColor(bgColor) canv.rect(0, 0, pageSize[0], pageSize[1], stroke=True, fill=True) canv.setFillColor(black) elif i % 2 == 1: canv.setStrokeColor(black) canv.setFillColor(black) canv.rect(0, 0, pageSize[0], pageSize[1], stroke=True, fill=True) canv.setFillColor(bgColor) if orientation == "portrait": canv.drawCentredString(pageSize[0]/2.0, pageSize[1]*0.3, u"%s" % i) elif orientation == "landscape": canv.drawCentredString(pageSize[0]/2.0, pageSize[1]*0.21, u"%s" % i) canv.showPage() canv.save()
def draw_label(self, c: Canvas, col: int, row: int, redemption_code: str): x = self.left_margin + ( col + 0.5) * self.label_width + col * self.inner_margin y = self.page_height - self.top_margin - (row + 0.5) * self.label_height # Drawing label bounds helps when adjusting layout. Not for production. # self.draw_label_bounds(c, x, y) c.setFont("Courier-Bold", 13) c.drawString(x - 80, y + 14, redemption_code) c.setFont("Helvetica", 10) # Space to enter redemption month and day. p = c.beginPath() p.moveTo(x + 20, y + 12) p.lineTo(x + 45, y + 12) p.moveTo(x + 55, y + 12) p.lineTo(x + 80, y + 12) p.close() c.drawPath(p) c.drawCentredString(x + 15, y + 16, 'm:') c.drawCentredString(x + 50, y + 16, 'd:') # Space to enter redeemer's email address. p = c.beginPath() p.moveTo(x - 80, y - 14) p.lineTo(x + 80, y - 14) p.close() c.drawPath(p) c.drawCentredString(x, y - 24, 'email address')
def test(): """Test this.""" from reportlab.pdfgen.canvas import Canvas from reportlab.lib import pagesizes canvas = Canvas("labels.pdf", pagesize=pagesizes.A4) canvas.setFont("Helvetica", 30) (width, height) = pagesizes.A4 canvas.drawCentredString(width / 2.0, height - 4 * cm, "Sample LTO labels") xpos = xorig = 2 * cm ypos = yorig = 2 * cm colwidth = 10 * cm lineheight = 3.9 * cm count = 1234 BaseLTOLabel("RL", count, "3").drawOn(canvas, xpos, ypos) ypos += lineheight count += 1 BaseLTOLabel("RL", count, "3", border=0.0125).drawOn(canvas, xpos, ypos) ypos += lineheight count += 1 VerticalLTOLabel("RL", count, "3").drawOn(canvas, xpos, ypos) ypos += lineheight count += 1 VerticalLTOLabel("RL", count, "3", border=0.0125).drawOn(canvas, xpos, ypos) ypos += lineheight count += 1 VerticalLTOLabel("RL", count, "3", colored=True).drawOn(canvas, xpos, ypos) ypos += lineheight count += 1 VerticalLTOLabel("RL", count, "3", border=0.0125, colored=True).drawOn(canvas, xpos, ypos) canvas.showPage() canvas.save()
def test_06_fontsize(self): from reportlab.lib.pagesizes import A4 from reportlab.pdfgen.canvas import Canvas from reportlab.lib.units import inch from reportlab.lib.colors import red, magenta c = Canvas('demo.pdf', pagesize=A4) c.translate(inch, inch) c.setFont("Times-Roman", 20) c.setFillColor(red) c.saveState() c.drawCentredString(2.75*inch, 2.5*inch,"Font size excmples") c.setFillColor(magenta) size = 7 x = 2.3 * inch y = 1.3 * inch for line in range(7): c.setFont("Helvetica", size) c.drawRightString(x, y, "%s points" % size) c.drawString(x,y, "test") y = y-size*1.2 size = size+1.5 c.restoreState() c.drawString(0,0, "%s" % c.getAvailableFonts()) c.showPage() c.save()
def generate_pages(card_sizes,cards, filename="placecards.pdf", custom_font = None): pagesize = pagesizes.portrait( ( 8.5 * pagesizes.inch, 11 * pagesizes.inch)) pdf = Canvas(filename, pagesize=pagesize,pdfVersion=(1,4)) pdf.setAuthor('placecardboardgenerate.py') pdf.setSubject('wedding placecards') pdf.setTitle('Placecards for Wedding Reception') pdf.setKeywords(('wedding', 'placecards')) if custom_font is not None: pdf.setFont(custom_font,14)#FIXME don't hardcode font size adjusted_card_sizes = (card_sizes[0] * pagesizes.inch, card_sizes[1] * pagesizes.inch) card_printer = CardPrinter(pagesize,adjusted_card_sizes) (cardsPerRow,rowsPerPage) = (card_printer.cards_per_row, card_printer.cards_per_column) (page_width, page_height) = pagesize groupedCards = group_cards(cards, cardsPerRow, rowsPerPage) for (page_index,pageOfCards) in enumerate(groupedCards): if custom_font is not None: pdf.setFont(custom_font,14)#FIXME don't hardcode font size for (row_index,rowOfCards) in enumerate(pageOfCards): for (column_index,card) in enumerate(rowOfCards): card_printer.print_on_front_page(pdf,card,row_index, column_index) pdf.drawCentredString(page_width/2.0,20,"front of page %i" % (page_index + 1)) pdf.showPage() if custom_font is not None: pdf.setFont(custom_font,14)#FIXME don't hardcode font size for (row_index,rowOfCards) in enumerate(pageOfCards): for (column_index,card) in enumerate(rowOfCards): card_printer.print_on_back_page(pdf,card,row_index, column_index) pdf.drawCentredString(page_width/2.0,20,"back of page %i" % (page_index + 1)) pdf.showPage() pdf.save()
def pdf_insert_doi_using_pdfrw(req_content, doi): input_file = io.BytesIO(req_content) pdf_buffer = io.BytesIO() reader = PdfReader(input_file) pages = [pagexobj(p) for p in reader.pages] canvas = Canvas(pdf_buffer) for page_num, page in enumerate(pages, start=1): canvas.setPageSize((page.BBox[2], page.BBox[3])) canvas.doForm(makerl(canvas, page)) # Draw footer if page_num == 1: footer_text = "https://doi.org/{}".format(doi) canvas.saveState() canvas.setFont("Helvetica-Bold", 8) canvas.setFillColor(HexColor('#990100')) canvas.drawCentredString(page.BBox[2] / 2, 20, footer_text) canvas.restoreState() canvas.showPage() canvas.save() pdf_bytes = pdf_buffer.getbuffer() return pdf_bytes
def main(argv): global X, Y, Title if len(argv) != 2: print __doc__ sys.exit(2) c = Canvas(argv[1], pagesize=pageSize, pageCompression=0) c.setFont(fontName, fontSize) init() X = 0 Y = 0 execfile(argv[0], globals()) init() if Title: print "title", Title c.drawCentredString(pageSize[0] / 2, pageSize[1] - (margins.top * inch * 0.65), Title) X = startX Y = startY for chart in Charts: x = chart.fx y = chart.fy if not x and not y: x = X y = Y chart.draw(c, x, y) over() c.showPage() c.save()
def _on_other_page(self, canvas: Canvas, doc): canvas.saveState() canvas.setFont(self.font_regular, 8) for i, line in enumerate(self.invoice.footer_text.split('\n')[::-1]): canvas.drawCentredString(self.pagesize[0] / 2, 25 + (3.5 * i) * mm, line.strip()) canvas.restoreState()
def generateOfficePDF(self,response): #Attach name.pdf file to responses content disposition response['Content-Disposition'] = 'attachment; filename=office.pdf' #Create empty pdf document, hook pdf with response pdf = Canvas(response) #Get Todays Events brains = sorted(util.gatherTodaysEvents(self), key=attrgetter('location')) #so awesome, sorts on any attribute! brains = sorted(brains, key=attrgetter('start')) #even better a secondary sort. #Header: Title Information and Settings pdf.setFont("Helvetica-Bold", 12) pdf.setStrokeColorRGB(0, 0, 0) #sets Line/Rectangle Colors #Header Left Title if brains != None and len(brains) > 0: pdf.drawString(15, 810, DateTime(brains[0].start).strftime("%A, %B %d, %Y") + " Schedule") else: pdf.drawString(15, 810, "No Groups scheduled for " + datetime.datetime.now().strftime("%A, %B %d, %Y")) #Header Right Title pdf.drawRightString(575, 810, "GroupFinder") #Body: List of Groups and Settings index = 792 #Pixel Index, starting at the top of the pdf page page = 1 #Page Number for brain in brains: pdf.setFont("Helvetica", 12) pdf.setStrokeColorRGB(0, 0, 0) #sets Line/Rectangle Colors pdf.rect(10, index-20, 575, 30, stroke=1, fill=0) #Rectangle around each Group pdf.drawString(15, index-3, brain.Title) #Group Description l = self.locationLookup(brain.location) pdf.drawString(15, index-15, DateTime(brain.start).strftime("%I:%M %p") + " - " + DateTime(brain.end).strftime("%I:%M %p") + " in " + l['Name']) index -= 30 #Move Pixel Index downwards #Reach Bottom of page? Creates New Page. if index < 30: pdf.drawString(15, 5, "Page " + str(page))#add page number pages pdf.drawCentredString(300, 5, "Created on " + datetime.datetime.now().strftime("%m/%d/%Y at %I:%M %p")) page+=1 index = 792 pdf.showPage() #next page #add page number pages pdf.drawString(15, 5, "Page " + str(page)) #add date PDF was created pdf.drawCentredString(300, 5, "Created on " + datetime.datetime.now().strftime("%m/%d/%Y at %I:%M %p")) pdf.showPage() #next page, finalize last page. pdf.save() #save the pdf content return response #return response with hooked pdf.
def generateEntrancePDF(self,response): #Attach name.pdf file to responses content disposition response['Content-Disposition'] = 'attachment; filename=entrance.pdf' #Create empty pdf document, hook pdf with response pdf = Canvas(response) pdf.setFillColor(colors.black) #sets Line/Rectangle Colors pdf.roundRect(10, 755, 575, 75, 10, 1, 0) pdf.setFont("Helvetica-Bold", 40) pdf.setStrokeColorRGB(0, 0, 0) #sets Line/Rectangle Colors pdf.drawCentredString(300, 790, "GroupFinder") pdf.setFont("Helvetica-Bold", 20) pdf.drawString(15, 765, "The following spaces are reserved during scheduled hours") pdf.drawCentredString(300,725, datetime.datetime.now().strftime("%A, %B %d, %Y")) #Get Todays Events brains = sorted(util.gatherTodaysEvents(self), key=attrgetter('start','Title')) index = 700 i = 0 for brain in brains: pdf.rect(45, index-30, 510, 42, stroke=1, fill=0) #Schedule List Rectangles if util.isPublic(self,brain.id): title = brain.Title else: title = "Private Group" pdf.setFont("Helvetica-Bold", 17) pdf.drawString(50, index-5, DateTime(brain.start).strftime("%I:%M %p").lower() + " - " + DateTime(brain.end).strftime("%I:%M %p").lower() + " : " + title) pdf.setFont("Helvetica", 17) l = self.locationLookup(brain.location) pdf.drawString(50, index-25, "Location: " + l['Name'] + " - " + l['DirectionsShort']) index -= 42 i += 1 if i == 13: pdf.setFont("Helvetica", 17) pdf.drawCentredString(300, index-5, "See Website For More Study Groups!") break pdf.setFont("Helvetica-Bold", 28) pdf.drawCentredString(300, 90, "Use GroupFinder to Reserve a Study Space.") pdf.setFont("Helvetica", 24) pdf.drawCentredString(300, 60, "http://www.uwosh.edu/library/groupfinder") pdf = self.tableFooter(pdf) pdf.showPage() #next page, finalize last page. pdf.save() #save the pdf content return response #return response with hooked pdf.
def _on_other_page(self, canvas: Canvas, doc): canvas.saveState() canvas.setFont('OpenSans', 8) canvas.drawRightString(self.pagesize[0] - 20 * mm, 10 * mm, pgettext("invoice", "Page %d") % (doc.page,)) for i, line in enumerate(self.invoice.footer_text.split('\n')[::-1]): canvas.drawCentredString(self.pagesize[0] / 2, 25 + (3.5 * i) * mm, line.strip()) canvas.restoreState()
def firstPage(): from reportlab.pdfgen.canvas import Canvas c = Canvas("out/firstPage.pdf", landscape(A4)) c.drawImage('orange.jpg', 26.7 * cm, 1 * cm, width=2 * cm, height=2 * cm) c.drawImage('phoenix.jpg', 22.7 * cm, 14 * cm, width=6 * cm, height=6 * cm) c.setFont("Helvetica-Bold", 62) c.setFillColorRGB(1, 0.47, 0) c.drawString(2 * cm, 16 * cm, "Sprint Review") c.setFont("Helvetica-Bold", 38) c.drawCentredString(9 * cm, 14 * cm, "sprint N° 26") c.save()
def pdf_demo_8(file): c = Canvas(file, pagesize=A4) c.drawString(20 * mm, 250 * mm, "This is a paragraph with twenty sentences. " * 20) c.drawCentredString(105 * mm, 10 * mm, "Page 1") c.showPage() c.setStrokeColorRGB(0, 0.9, 0.5) c.drawCentredString(105 * mm, 10 * mm, "Page 2") c.line((105 - 2) * mm, 10 * mm, (105 + 2) * mm, 10 * mm) c.line(105 * mm, (10 - 2) * mm, 105 * mm, (10 + 2) * mm) c.save()
def watermark_fn(canvas: Canvas, doc: BaseDocTemplate): width, height = canvas._pagesize canvas.saveState() canvas.translate(width / 2, height / 2) canvas.rotate(45) canvas.setFont(paragraph_style.fontName, paragraph_style.fontSize) canvas.setFillColor(paragraph_style.textColor) alpha = getattr(paragraph_style, "alpha", 1.0) canvas.setFillAlpha(alpha) canvas.drawCentredString(0, 0, text) canvas.restoreState()
def pdf_demo_9(file): c = Canvas(file, pagesize=A4) x, y = 50 * mm, 280 * mm for font in c.getAvailableFonts(): c.setFont("Courier", 10) c.drawRightString(x - 5, y, font) c.setFont(font, 12) c.drawString(x + 5, y, "Quick brown fox jumped over the lazy dog") y -= 15 # Drop 15 point for each line c.setFont("Times-Italic", 10) c.drawCentredString(105 * mm, 10 * mm, "Page 1") c.save()
def genTestFile(path, numPages): "Generate a PDF doc with *very* big page numbers on all pages." size = landscape(A4) canv = Canvas(path, pagesize=size) for i in range(numPages): canv.setFont("Helvetica", size[1] * 1.2) x, y = size[0] / 2.0, size[1] * 0.1 text = u"%s" % i canv.drawCentredString(x, y, text) canv.showPage() canv.save()
def header(c: canvas.Canvas, info: dict, theme: dict, top=HEIGHT - MARGIN) -> float: #smaller font, italic, red c.setFont("Helvetica-Oblique", 10) setColor(c, theme['accent']) #linkedin - left c.drawString(MARGIN, top, info["Info"]["linkedin"]) c.linkURL("https://" + info["Info"]["linkedin"], (MARGIN, top, MARGIN + c.stringWidth(info["Info"]["linkedin"]), top + 10)) #github - right c.drawRightString(WIDTH - MARGIN, HEIGHT - MARGIN, info["Info"]["github"]) c.linkURL("https://" + info["Info"]["github"], (WIDTH - MARGIN - c.stringWidth(info["Info"]["github"]) - 3, top, WIDTH - MARGIN, top + 10)) #name setColor(c, theme['front']) top -= inch / 3 c.setFont("Helvetica-Bold", 20) c.drawRightString(WIDTH / 2 - 2, top, info["Info"]["name"][0]) #first setColor(c, theme['accent']) c.drawString(WIDTH / 2 + 2, top, info["Info"]["name"][1]) #last x1 = WIDTH / 2 - c.stringWidth(info["Info"]["name"][0]) x2 = WIDTH / 2 + c.stringWidth(info["Info"]["name"][1]) c.linkURL("https://" + info["Info"]["site"], (x1, top, x2, top + 20)) #contact info - center below name top -= 20 #size of name setColor(c, theme['front']) c.setFont("Helvetica", 10) contact = info["Info"]["email"] + " | " + info["Info"][ "phone-number"] + " | " + info["Info"]["site"] c.drawCentredString(WIDTH / 2, top, contact) #link site x2 = (WIDTH + c.stringWidth(contact)) / 2 x1 = x2 - c.stringWidth(info["Info"]["site"]) c.linkURL("https://" + info["Info"]["site"], (x1, top, x2, top + 10)) #link email x1 = (WIDTH - c.stringWidth(contact)) / 2 x2 = x1 + c.stringWidth(info["Info"]["email"]) c.linkURL("mailto:" + info["Info"]["email"], (x1, top, x2, top + 10)) #canvas.drawRightString(x, y, theme['front']), drawString(x, y, theme['front']) return top - inch / 20
def pdf( archivo, suNombre, suCedula, ): # Librerias from reportlab.lib.units import cm from reportlab.pdfgen.canvas import Canvas from reportlab.platypus import Frame, Image try: os.mkdir('pdfMakerArchivos') except OSError as e: if e.errno != errno.EEXIST: raise ruta_archivo = easygui.fileopenbox() # W = Ancho H = Alto del archivo w = 4000 h = 2250 # El lienzo del archivo c = Canvas("pdfMakerArchivos/" + archivo.get() + suNombre.get() + ".pdf", pagesize=(w, h)) c.setTitle(archivo.get()) # La imagen del certificado c.drawImage(ruta_archivo, 1, 1, width=w, height=h) # los datos del usuario certificado = suNombre.get() ci = "C.I: " + str(suCedula.get()) # Comandos para insertarlos y ubicarlos en el archivo c.setFont('Helvetica-Bold', 150) c.drawCentredString(w / 2, 1350, certificado) c.setFont('Helvetica', 100) c.drawCentredString(w / 2, 1230, ci) #Guardar el archivo c.save() if os.path.isfile("pdfMakerArchivos/" + str(archivo.get()) + str(suNombre.get()) + ".pdf"): #Mesaje de todo correcto messagebox.showinfo( title="pdfMaker ha creado el archivo: " + str(archivo.get()), message="El certificado a sido creado para: " + str(certificado)) else: #Mensaje de algo salio mal messagebox.showwarning( title="Error: 404 Not Found ", message="El archivo no se a creado correctamente")
def __create_pdf_template(self, filepath, img1, img2, pagesize): canvas = Canvas(filepath, pagesize=pagesize) canvas.setFont("Times-Roman", 40) title = self.__title title_magic_offset_y = 50 title_x = A3[0] / 2 title_y = A3[1] - title_magic_offset_y canvas.drawCentredString(title_x, title_y, title) canvas.drawImage(img1, 150, 600) canvas.drawImage(img2, 150, 100) return canvas
def dumpttf(fn, fontName=None, verbose=0): """dump out known glyphs from a ttf file""" import os if not os.path.isfile(fn): raise IOError('No such file "%s"' % fn) from reportlab.pdfbase.pdfmetrics import registerFont, stringWidth from reportlab.pdfbase.ttfonts import TTFont from reportlab.pdfgen.canvas import Canvas if fontName is None: fontName = os.path.splitext(os.path.basename(fn))[0] dmpfn = "%s-ttf-dump.pdf" % fontName ttf = TTFont(fontName, fn) K = list(ttf.face.charToGlyph.keys()) registerFont(ttf) c = Canvas(dmpfn) W, H = c._pagesize titleFontSize = 30 # title font size titleFontName = "Helvetica" labelFontName = "Courier" fontSize = 10 border = 36 dx0 = stringWidth("12345: ", fontName, fontSize) dx = dx0 + 20 dy = 20 K.sort() y = 0 page = 0 for i, k in enumerate(K): if y < border: if page: c.showPage() page += 1 y = H - border - titleFontSize c.setFont(titleFontName, titleFontSize) c.drawCentredString(W / 2.0, y, "TrueType Font %s Page %d" % (fontName, page)) y -= 0.2 * titleFontSize + dy x = border c.setFont(labelFontName, 10) c.drawString(x, y, "%5.5x:" % k) c.setFont(fontName, 10) c.drawString(x + dx0, y, chr(k).encode("utf8")) x += dx if x + dx > W - border: x = border y -= dy c.showPage() c.save() if verbose: print('Font %s("%s") has %d glyphs\ndumped to "%s"' % (fontName, fn, len(K), dmpfn))
def dumpttf(fn, fontName=None, verbose=0): '''dump out known glyphs from a ttf file''' import os if not os.path.isfile(fn): raise IOError('No such file "%s"' % fn) from reportlab.pdfbase.pdfmetrics import registerFont, stringWidth from reportlab.pdfbase.ttfonts import TTFont from reportlab.pdfgen.canvas import Canvas if fontName is None: fontName = os.path.splitext(os.path.basename(fn))[0] dmpfn = '%s-ttf-dump.pdf' % fontName ttf = TTFont(fontName, fn) K = ttf.face.charToGlyph.keys() registerFont(ttf) c = Canvas(dmpfn) W, H = c._pagesize titleFontSize = 30 # title font size titleFontName = 'Helvetica' labelFontName = 'Courier' fontSize = 10 border = 36 dx0 = stringWidth('12345: ', fontName, fontSize) dx = dx0 + 20 dy = 20 K.sort() y = 0 page = 0 for i, k in enumerate(K): if y < border: if page: c.showPage() page += 1 y = H - border - titleFontSize c.setFont(titleFontName, titleFontSize) c.drawCentredString(W / 2.0, y, 'TrueType Font %s Page %d' % (fontName, page)) y -= 0.2 * titleFontSize + dy x = border c.setFont(labelFontName, 10) c.drawString(x, y, '%5.5x:' % k) c.setFont(fontName, 10) c.drawString(x + dx0, y, unichr(k).encode('utf8')) x += dx if x + dx > W - border: x = border y -= dy c.showPage() c.save() if verbose: print 'Font %s("%s") has %d glyphs\ndumped to "%s"' % (fontName, fn, len(K), dmpfn)
def _generate_pattern(image, flip=True): template = image_ops.generate_template(image, flip=flip) image_buf = BytesIO() template.save(image_buf, format="PNG") bead_counts = image_ops.count_beads(image) # Start PDF data = BytesIO() # bottomup is forced because reportlab treats images that way? # Or we could flip the image ourselves and still specify the bottom # right corner? canvas = Canvas(data, bottomup=1, pagesize=letter) # page 1: packing list and instructions y = 10 * inch color_count = len(bead_counts.keys()) column = 0 left_margin = 0.5 * inch for index, color_name in enumerate(sorted(bead_counts.keys())): if column == 0 and index >= color_count / 2.0: column = 1 left_margin = 4.25 * inch y = 10 * inch count = bead_counts[color_name] color_file = color_name.replace(" ", "_") + ".png" canvas.drawInlineImage( f"data/color_images/bitmap/{color_file}", x=left_margin+0.5*inch, y=y-0.04*inch, width=0.2*inch, height=0.2*inch ) canvas.drawCentredString(left_margin+0.25*inch, y, str(count)) canvas.drawString(left_margin+0.75*inch, y, color_name) y -= 0.2 * inch canvas.showPage() # page 2: template canvas.drawInlineImage( template, x=0.25*inch, y=0.5*inch, width=8*inch, height=10*inch, ) canvas.showPage() # Finalize and return canvas.save() data.seek(0) return data.read()
def test0(self): "A basic document drawing some strings" # if they do not have the Japanese font files, go away quietly from reportlab.pdfbase.cidfonts import UnicodeCIDFont, findCMapFile pdfmetrics.registerFont(UnicodeCIDFont('STSong-Light')) c = Canvas(outputfile('test_multibyte_chs.pdf')) c.setFont('Helvetica', 30) c.drawString(100,700, 'Simplified Chinese Font Support') c.setFont('Helvetica', 10) c.drawString(100,680, 'Short sample: "China - Zhang Ziyi" (famous actress)') # the two typefaces hBoxText('\u4e2d\u56fd - \u7ae0\u5b50\u6021', c, 100, 660, 'STSong-Light', ) c.setFont('Helvetica',10) c.drawCentredString(297, 36, 'Page %d' % c.getPageNumber()) c.showPage() ## # full kuten chart in EUC ## c.setFont('Helvetica', 18) ## c.drawString(72,750, 'Characters available in GB 2312-80, EUC encoding') ## y = 600 ## enc = 'GB_EUC_H' ## for row in range(1, 95): ## KutenRowCodeChart(row, 'STSong-Light',enc).drawOn(c, 72, y) ## y = y - 125 ## if y < 50: ## c.setFont('Helvetica',10) ## c.drawCentredString(297, 36, 'Page %d' % c.getPageNumber()) ## c.showPage() ## y = 700 ## c.save() if VERBOSE: print('saved '+outputfile('test_multibyte_chs.pdf'))
def test0(self): "A basic document drawing some strings" # if they do not have the Japanese font files, go away quietly from reportlab.pdfbase.cidfonts import UnicodeCIDFont, findCMapFile pdfmetrics.registerFont(UnicodeCIDFont('STSong-Light')) c = Canvas(outputfile('test_multibyte_chs.pdf')) c.setFont('Helvetica', 30) c.drawString(100,700, 'Simplified Chinese Font Support') c.setFont('Helvetica', 10) c.drawString(100,680, 'Short sample: "China - Zhang Ziyi" (famous actress)') # the two typefaces hBoxText(u'\u4e2d\u56fd - \u7ae0\u5b50\u6021', c, 100, 660, 'STSong-Light', ) c.setFont('Helvetica',10) c.drawCentredString(297, 36, 'Page %d' % c.getPageNumber()) c.showPage() ## # full kuten chart in EUC ## c.setFont('Helvetica', 18) ## c.drawString(72,750, 'Characters available in GB 2312-80, EUC encoding') ## y = 600 ## enc = 'GB_EUC_H' ## for row in range(1, 95): ## KutenRowCodeChart(row, 'STSong-Light',enc).drawOn(c, 72, y) ## y = y - 125 ## if y < 50: ## c.setFont('Helvetica',10) ## c.drawCentredString(297, 36, 'Page %d' % c.getPageNumber()) ## c.showPage() ## y = 700 ## c.save() if VERBOSE: print 'saved '+outputfile('test_multibyte_chs.pdf')
def generate_shows_pdf(): """Build the pdf of all the shows Returns ------- string Url of the string """ # get the list of shows list_of_shows_details = get_list_of_all_shows() # get today in iso format today = date.today().isoformat() # concat file name and file path file_name = "show_report_" + today + ".pdf" file_path = "flaskr/static/exports/pdf/" + file_name # set w and h of the A4 paper width, height = A4 # init canvas pdf = Canvas(file_path) # set document title pdf.setTitle(file_name) # Set pdf Title pdf.setFont("Courier-Bold", 16) pdf.drawString(200, 770, "Shows report on " + today) # set sub title pdf.setFont("Courier-Bold", 14) pdf.drawCentredString(100, 720, "Show Type") pdf.drawCentredString(280, 720, "Show Name") pdf.drawCentredString(460, 720, "Director Name") pdf.setFont("Courier-Bold", 10) # building a table for returned shows data = [] # prepare shows data for show_details in list_of_shows_details: data.append([ show_details['show_type'], show_details['show_name'], show_details['director_name'] ]) # apply it to the table table = Table(data, colWidths=[2.4 * inch] * 3) table.wrapOn(pdf, width, height) table.drawOn(pdf, 75, 640) # save it pdf.save() return "static/exports/pdf/" + file_name
def sort_markers( canvas: Canvas, underlay: UnderlayDefinition, marker: GlueMarkDefinition ): pdfmetrics.registerFont(marker.font) canvas.setFont(marker.font.face.filename, marker.font_size) canvas.setStrokeColorRGB(*marker.marker_color) for ix in range(1, underlay.page_count.x): x_outer = mm_to_points( ix * (underlay.page_size.x - underlay.overlap) + underlay.overlap / 2, underlay.dpi, ) for iy in range(underlay.page_count.y): y_center = mm_to_points( (iy * (underlay.page_size.y - underlay.overlap)) + (underlay.page_size.y / 2), underlay.dpi, ) marker_num = ( ix - 1 + ((underlay.page_count.y - 1 - iy) * (underlay.page_count.x - 1)) ) marker_label = marker.label_x[marker_num % len(marker.label_x)] canvas.drawCentredString( x_outer - marker.font_size / 2, y_center - marker.font_size / 2, marker_label, ) canvas.drawCentredString( x_outer + marker.font_size / 2, y_center - marker.font_size / 2, marker_label, ) for ix in range(underlay.page_count.x): x_center = mm_to_points( ix * (underlay.page_size.x - underlay.overlap) + underlay.page_size.x / 2, underlay.dpi, ) for iy in range(1, underlay.page_count.y): y_bottom = mm_to_points( ( (iy * (underlay.page_size.y - underlay.overlap)) + underlay.overlap / 2 ), underlay.dpi, ) marker_num = ix + ((underlay.page_count.y - iy - 1) * underlay.page_count.x) marker_label = marker.label_y[marker_num % len(marker.label_y)] canvas.drawCentredString( x_center, y_bottom + marker.font_size / 2, marker_label ) canvas.drawCentredString( x_center, y_bottom - marker.font_size / 2, marker_label )
def main(): data = list(load_jsonl("s-1596527291.086862.jsonl")) groups = group_data(data) bio = io.BytesIO() doc = Canvas(bio, pagesize=A4) dw, dh = doc._pagesize margin = 7.5 * mm n_x = 8 n_y = int(n_x * 1.618) per_page = n_x * n_y x_size = (dw - margin * 2) / n_x y_size = (dh - margin * 2) / n_y box_size = min(x_size, y_size) image_size = box_size - 5 * mm n_pages = 0 # groups.sort(key=lambda g: len(g["filenames"]), reverse=True) with tqdm.tqdm(groups) as prog: for total_i, group in enumerate(prog): page_i = total_i % per_page gy, gx = divmod(page_i, n_x) if not (gx or gy): # first item of a page n_pages += 1 prog.set_description(f"page {n_pages}") if total_i: doc.showPage() doc.setFont("Helvetica", 6.5) corner_x = margin + x_size * gx corner_y = margin + y_size * (n_y - 1 - gy) mid_x = corner_x + box_size / 2 mid_y = corner_y + box_size / 2 # doc.rect(corner_x, corner_y, box_size, box_size) ph = group["phash"] doc.drawImage( f"images/ph/{ph}.png", mid_x, mid_y + 2 * mm, image_size, image_size, anchorAtXY=True, preserveAspectRatio=True, ) doc.drawCentredString(mid_x, corner_y + 1 * mm, f'{ph} ({len(group["filenames"])})') doc.save() with open("silcrowsnest.pdf", "wb") as outf: outf.write(bio.getvalue())
def draw_tab(self, c: Canvas, tab_num: int, redemption_code: str) -> None: tab_width = (self.page_width - self.left_margin - self.right_margin) / self.num_tabs # (x,y) is bottom left corner of the tab: x = self.left_margin + (tab_num * tab_width) y = self.bottom_margin # Drawing tab bounds helps when adjusting layout. Not for production. #self.draw_tab_bounds(c, x, y, tab_width) self.draw_tab_guides(c, x, y, tab_width) c.saveState() c.translate(x + 0.5 * tab_width, y + 0.5 * self.tab_height) c.rotate(90) c.setFont("Helvetica", 13) c.drawString(-0.47 * self.tab_height, 0.1 * tab_width, "Free Membership!") c.setFont("Courier-Bold", 16) c.drawString(-0.47 * self.tab_height, -0.25 * tab_width, redemption_code) c.restoreState() return None c.setFont("Helvetica", 10) # Space to enter redemption month and day. p = c.beginPath() p.moveTo(x + 20, y + 12) p.lineTo(x + 45, y + 12) p.moveTo(x + 55, y + 12) p.lineTo(x + 80, y + 12) p.close() c.drawPath(p) c.drawCentredString(x + 15, y + 16, 'm:') c.drawCentredString(x + 50, y + 16, 'd:') # Space to enter redeemer's email address. p = c.beginPath() p.moveTo(x - 80, y - 14) p.lineTo(x + 80, y - 14) p.close() c.drawPath(p) c.drawCentredString(x, y - 24, 'email address')
def get_doi_canvas(doi, width, height, license_url): packet = io.BytesIO() canvas = Canvas(packet, pagesize=(width, height)) footer_text = "https://doi.org/{}".format(doi) canvas.saveState() #canvas.setFont("Helvetica-Bold",8) canvas.setFont("Times-Roman", 8) #canvas.setFillColor(HexColor('#990100')) canvas.drawCentredString(int(width) / 2, 20, footer_text) if len(license_url.strip()) > 0: canvas.drawCentredString(int(width) / 2, 10, license_url) canvas.restoreState() canvas.showPage() canvas.save() packet.seek(0) new_pdf = PdfFileReader(packet) return new_pdf
def generate_key(verticalCardsCount,horizontalCardsCount,cards, filename="key.pdf", page_margins = 4 * (0.5 * pagesizes.inch, )): (page_margin_top, page_margin_left, page_margin_bottom, page_margin_right) = page_margins padding = 0.0625 * pagesizes.inch spaces = (verticalCardsCount * horizontalCardsCount) * [None,] for card in cards: spaces[card.position] = card pagesize = pagesizes.landscape( ( 8.5 * pagesizes.inch, 11 * pagesizes.inch)) pdf = Canvas(filename, pagesize=pagesize, pdfVersion=(1,4)) pdf.setAuthor('placecardboardgenerate.py') pdf.setSubject('wedding placecards key') pdf.setTitle('Key for Placecards for Wedding Reception') pdf.setKeywords(('wedding', 'placecards')) (page_width, page_height) = pagesize pdf.drawCentredString(page_width/2.0,20,"key of place cards") thumbnail_width = ((page_width - page_margin_left - page_margin_right) - (padding * (horizontalCardsCount - 1))) / horizontalCardsCount thumbnail_height = ((page_height - page_margin_top - page_margin_bottom) - (padding * (verticalCardsCount - 1))) / verticalCardsCount x_margin = page_margin_left x_offset = thumbnail_width + padding y_margin = page_margin_top y_offset = thumbnail_height + padding for row_index in range(verticalCardsCount): for column_index in range(horizontalCardsCount): position = (row_index * horizontalCardsCount) + column_index card = spaces[position] (card_x, card_y) = \ (x_margin + (x_offset * column_index),\ (page_height - thumbnail_height) - (y_margin + (y_offset * row_index))) if card is not None: pdf.drawImage(card.image, card_x, card_y, width = thumbnail_width, height = thumbnail_height) pdf.drawCentredString(card_x + thumbnail_width/2.0,card_y + thumbnail_height/2.0, str(card.position)) pdf.showPage() pdf.save()
def badge(): name = request.form['name'][:MAX_CHARS_PER_LINE] if 'name' in request.form else '' name2 = request.form['name2'][:MAX_CHARS_PER_LINE] if 'name2' in request.form else '' nick = request.form['nick'][:MAX_CHARS_PER_LINE] if 'nick' in request.form else '' community = request.form['community'][:MAX_CHARS_PER_LINE] if 'community' in request.form else '' pdf = BytesIO() c = Canvas(pdf, pagesize=(BADGE_W, BADGE_H)) c.translate(ORIGIN_X, ORIGIN_Y) ico_center = 7*mm offset = HEIGHT+2*mm c.setFillGray(0.66) c.setFont('Awesome', 42) c.drawCentredString(ico_center, offset-42*pica/12, '\uf007') c.setFont('Awesome', 38) c.drawCentredString(ico_center, offset-(2*42+40)*pica/12, '\uf1fa') c.drawCentredString(ico_center, offset-(2*42+2*40)*pica/12, '\uf041') txt_start = 15*mm c.setFillGray(0.0) c.setFont('LeagueGothic', 42) c.drawString(txt_start, offset-42*pica/12, name) c.drawString(txt_start, offset-2*42*pica/12, name2) c.setFont('LeagueGothic', 38) c.drawString(txt_start, offset-(2*42+40)*pica/12, nick) c.drawString(txt_start, offset-(2*42+2*40)*pica/12, community) evt_width = 38*pica/12 evt_start = WIDTH - evt_width img_width = 20*mm img_start = evt_start - img_width c.drawImage(path.join(path.dirname(__file__), 'images/ffrhein_logo_claim_line_rot.png'), img_start, 0, img_width, HEIGHT, mask=None, preserveAspectRatio=True, anchor='c') c.rotate(90) c.rect(0, -WIDTH, HEIGHT, evt_width, 0, 1) c.setFillGray(1.0) c.drawCentredString(HEIGHT/2, -WIDTH+MARGIN_R, 'routing days') c.showPage() c.save() _print(pdf.getvalue()) pdf.close() # response = make_response('Meh') # response.headers['Content-Type'] = 'text/plain' # return response return redirect('/badge/printing.html')
class DesignShirtsFromCalifornia: CHICAGO_HEADLINE=["ThoughtWorks Chicago", "Bringing it since 1992", "CHICAGO", "Rainey's People"] ADJECTIVES=["Awesomist", "Best looking", "Happiest", "Legendary", "Transparent", "Shiny", "Dangerous", "Fastest"] NOUNS=["Chicagoans", "Agilistas", "Wonderlic Masters", "Bears Fans"] ATTRIBUTION="Designed by ThoughtWorks in California" GIT_REF="Fork me on Github https://github.com/jawspeak/tw-california-tshirt-generator" def __init__(self, output_filename): self.pdf = Canvas(output_filename, pagesize = LETTER) # self.headlines = def draw(self): for image in glob.glob('awesomeness/*.[jpg|png|gif]*'): self._draw_page(image) self.pdf.save() def _draw_page(self, image): self.pdf.setFillColor(colors.black) # To have a higher resolution for printing export the image as a higter resolution image which is then reduced self.pdf.drawImage(image, 2.25 * inch, 3.7 * inch, width=300, height=300, preserveAspectRatio=True) height = 8 # print self.pdf.getAvailableFonts() self.pdf.setFont("Times-Bold", 28) random.shuffle(self.CHICAGO_HEADLINE, random.random) self.pdf.drawCentredString(4.25* inch, height*inch, self.CHICAGO_HEADLINE[0].encode('latin-1')) self.pdf.setFont("Times-Italic", 16) if len(image.split('=')) == 2: self.pdf.drawCentredString(4.25* inch, (height - 4.5)* inch, image.split('=')[1].split('.')[0].encode('latin-1')) else: random.shuffle(self.ADJECTIVES, random.random) random.shuffle(self.NOUNS, random.random) flattering_tagline = "Home of the %s %s!" % (', '.join(self.ADJECTIVES[:2]), self.NOUNS[0]) self.pdf.drawCentredString(4.25* inch, (height - 4.5)* inch, flattering_tagline.encode('latin-1')) self.pdf.setFont("Times-Italic", 10) self.pdf.drawCentredString(4.25 * inch, (height - 4.8) * inch, self.ATTRIBUTION) self.pdf.drawCentredString(4.25 * inch, (height - 4.95) * inch, self.GIT_REF) self.pdf.showPage()
def genTestFile(path, numPages): "Generate a PDF doc with *very* big page numbers on all pages." size = landscape(A4) canv = Canvas(path, pagesize=size) for i in range(numPages): canv.setFont("Helvetica", size[1]*1.2) x, y = size[0]/2.0, size[1]*0.1 text = u"%s" % i if i % 2 == 1: canv.setStrokeColor(black) canv.setFillColor(black) canv.rect(0, 0, size[0], size[1], fill=True) if i % 2 == 1: canv.setFillColor(white) else: canv.setFillColor(black) canv.drawCentredString(x, y, text) canv.showPage() canv.save()
def pdf_demo_10(file): c = Canvas(file, pagesize=A4) text = c.beginText() text.setTextOrigin(20 * mm, 277 * mm) text.setFont(psfontname="Times-Roman", size=12, leading=24) text.textOut("Text which stays on same line. ") text.textOut("More text. ") text.textLine("A line that will drop to next line. ") text.textLine( "A very long line with several sentences but no newline characters. " * 3) text.textLine( "A paragraph with several sentences and newline characters.\n" * 3) text.textLines( "This is text with fifty sentences and newline characters.\n" * 50) c.drawText(text) c.drawCentredString(105 * mm, 10 * mm, "Page 1") c.showPage() c.drawCentredString(105 * mm, 10 * mm, "Page 2") c.save()
def genTestFile(path, numPages): "Generate a PDF doc with *very* big page numbers on all pages." size = landscape(A4) canv = Canvas(path, pagesize=size) for i in range(numPages): canv.setFont("Helvetica", size[1]*1.2) x, y = size[0]/2.0, size[1]*0.1 text = "%s" % i if i % 2 == 1: canv.setStrokeColor(black) canv.setFillColor(black) canv.rect(0, 0, size[0], size[1], fill=True) if i % 2 == 1: canv.setFillColor(white) else: canv.setFillColor(black) canv.drawCentredString(x, y, text) canv.showPage() canv.save()
def render_bikes_to_pdf_with_reportlab(queryset, fields={}, title=None, subtitle=None): buf = io.BytesIO() canvas = Canvas( buf, pagesize=landscape(A4)) # W, H = landscape(A4) # 841.9, 595.27 logo = os.path.join(PROJECT_DIR, 'frontend', 'static', 'img/velafrica_RGB.jpg') # title page if title: canvas.setFont("Helvetica", 28) canvas.drawCentredString(text=title, x=841.9 / 2, y=300) if subtitle: canvas.setFont("Helvetica", 20) canvas.drawCentredString(text=subtitle, x=841.9 / 2, y=270) if title or subtitle: pdf_page_frame(canvas, logo) # bike pages for bike in queryset: draw_pdf_page( canvas=canvas, table=[ # label - value pairs for selected 'fields' (label, "{}".format(bike.__getattribute__(key))) for key, label in fields.items() if bike.__getattribute__(key) # if not blank ], extraordinary=bike.extraordinary, image=bike.image, logo=logo, title="A+ Bike") # Close the PDF object cleanly canvas.save() buf.seek(0) return buf.getvalue()
class AwardPrinter: def __init__(self, output_filename, background_image, page_renderer): self.background_image = background_image self.page_renderer = page_renderer self.pdf = Canvas(output_filename, pagesize = A4) def draw(self, students): for student in students: self._draw_page(student) self.pdf.save() def _draw_page(self, student): self.pdf.setFillColor(colors.black) # export the image as a higter resolution image 1280x920 recommended, which is then reduced # in size to have a higher resolution for printing self.pdf.drawImage(self.background_image, .1 * inch, .3 * inch, width=580, height=800, preserveAspectRatio=True) self.pdf.rotate(270) self.page_renderer(self, student) self.pdf.showPage() def _draw_award(self, student): name = student.split(',')[0].strip() award = student.split(',')[1].strip() self.pdf.setFont("Helvetica", 28) # play with these dimensions if you want to move around the text in the screen self.pdf.drawCentredString(-5.4 * inch, 4.5 * inch, name.encode('latin-1')) self.pdf.setFont("Helvetica", 18) # play with these dimensions if you want to move around the text in the screen self.pdf.drawCentredString(-5.4 * inch, 3.5 * inch, award) def _draw_certificate(self, student): name = student.split(',')[0].strip() self.pdf.setFont("Helvetica", 32) # play with these dimensions if you want to move around the text in the screen self.pdf.drawCentredString(-5.75 * inch, 5.5 * inch, name.encode('latin-1'))
def __create_pdf_template(self, filepath, img, countries, timespan, pagesize): canvas = Canvas(filepath, pagesize=pagesize) canvas.setFont("Helvetica", 20) title = self.__title subtitle = "(Generated: " + self.__subtitle title_magic_offset, subtitle_magic_offset, img_magic_offset = 70, 100, 650 title_x, title_y = A4[0] / 2, A4[1] - title_magic_offset subtitle_x, subtitle_y = A4[0] / 2, A4[1] - subtitle_magic_offset img_x, img_y = 0, A4[1] - img_magic_offset canvas.drawCentredString(title_x, title_y, title) canvas.setFont("Helvetica", 12) canvas.drawCentredString(subtitle_x, subtitle_y, subtitle) canvas.drawImage(img, img_x, img_y, A4[0], A4[1] / 2) countries_wrap = "\n".join(wrap(countries, 70)) countries_text = canvas.beginText(A4[0] - 450, A4[1] - 180) for line in countries_wrap.splitlines(False): countries_text.textLine(line.rstrip()) canvas.drawText(countries_text) timespan_end = ' - '.join(timespan) timespan = "Timespan: " + timespan_end canvas.drawCentredString(A4[0] / 2, A4[1] - 150, timespan) return canvas
class BadgePrinter: def __init__(self, registration_list, filename='Badges_rendered.pdf'): self.registration_list = registration_list self.pdf = Canvas(filename, pagesize = letter) def drawBadges(self): for six_registrants in self._chunkRegistrantsIntoSixes(): self._drawOnePage(six_registrants) self.pdf.save() def _drawOnePage(self, registrants): left_column_x = 2.25 right_column_x = 6.25 top_y = 9 middle_y = 6 bottom_y = 3 i = 0 for x in [left_column_x, right_column_x]: for y in [top_y, middle_y, bottom_y]: if i < len(registrants): self._drawOneNameBadge(x, y, registrants[i]) i += 1 self.pdf.showPage() def _drawOneNameBadge(self, x, y, registrant): self.pdf.setFillColor(colors.black) # self.pdf.setFont("Helvetica", 18) # self.pdf.drawImage("testing_logo.jpg", (x + 1.1) * inch, (y - .75) * inch) self.pdf.setFont("Helvetica", 19) self.pdf.drawCentredString(x * inch, y * inch, str(registrant.full_name.encode('latin-1'))) self.pdf.setFont("Helvetica", 12) self.pdf.drawCentredString(x * inch, (y - .25) * inch, str(registrant.home_office)) self.pdf.setFont("Helvetica", 8) self.pdf.drawCentredString(x * inch, (y - .5) * inch, str(registrant.job_role)) self.pdf.setFont("Helvetica", 6) self.pdf.setFillColor(colors.green) self.pdf.drawCentredString(x * inch, (y - .7) * inch, 'Test Engineering NYC Summit 2008') def _chunkRegistrantsIntoSixes(self): chunked = [] for i in range(0, len(self.registration_list), 6): chunked.append(self.registration_list[i:i + 6]) return chunked
def seating_map(request, seating_id): seating = get_object_or_404(Seating, pk=seating_id) lan = get_object_or_404(LAN, id=seating.lan.id) seats = list(Seat.objects.filter(seating=seating).order_by('placement')) response = HttpResponse(content_type='application/pdf') response[ 'Content-Disposition'] = 'attachment; filename=' + seating.title + '.pdf' page_size = pagesizes.A4 page_width, page_height = page_size page_width_center = page_width / 2 page_height_center = page_height / 2 p = PdfCanvas(response, pagesize=page_size) new_page = True y_offset = page_height_center for seat in seats: p.setFont('Times-Roman', 40) p.drawCentredString(page_width_center, y_offset + 310, lan.title) p.setFont('Times-Roman', 35) text = _(u'%(seating)s, seat %(seat)d') % { 'seating': seating.title, 'seat': seat.placement } p.drawCentredString(page_width_center, y_offset + 250, text) if seat.user: p.setFont('Helvetica', 40) occupant = unicode(seat.user) else: p.setFont('Helvetica', 40) occupant = _(u'(Available)') p.drawCentredString(page_width_center, y_offset + 150, occupant) if new_page: new_page = False y_offset = 0 else: new_page = True y_offset = page_height_center p.showPage() p.showPage() p.save() return response
def make_idt_overlay(dep_name, fund, amount, proj_amt=0, person_name=None, description=None): outfile = BytesIO() c = Canvas(outfile, pagesize=landscape(letter)) c.rotate(90) c.translate(0, -letter[0]) amount = float(amount) proj_amt = float(proj_amt) c.drawString(2.15 * inch, 6.25 * inch, "Lens and Lights") c.drawString(7.5 * inch, 6.25 * inch, str(date.today())) if dep_name: c.drawString(2.15 * inch, 6.75 * inch, str(dep_name)) if person_name: c.drawString(7.5 * inch, 6.75 * inch, str(person_name)) if description: c.drawString(0.6 * inch, 2.15 * inch, str(description)) # amounts on their side c.drawCentredString(4.3 * inch, 5.15 * inch, to_cash(amount + proj_amt)) c.drawCentredString(4.3 * inch, 3.45 * inch, to_cash(amount + proj_amt)) # their fund if fund and len(fund) == 3: # yes, it is actually spelled like that. Pip, pip, cherrio c.drawCentredString(0.9 * inch, 5.15 * inch, str(fund[0])) c.drawCentredString(1.75 * inch, 5.15 * inch, str(fund[1])) c.drawCentredString(2.6 * inch, 5.15 * inch, str(fund[2])) # amounts on our side if proj_amt: c.drawCentredString(8.65 * inch, 4.8 * inch, to_cash(proj_amt)) c.drawCentredString(8.65 * inch, 5.15 * inch, to_cash(amount)) c.drawCentredString(8.65 * inch, 3.45 * inch, to_cash(proj_amt + amount)) # our fund c.drawCentredString(5.25 * inch, 5.15 * inch, str(81720)) c.drawCentredString(6.1 * inch, 5.15 * inch, str(72810)) c.drawCentredString(6.95 * inch, 5.15 * inch, str(5910)) if proj_amt: c.drawCentredString(5.25 * inch, 4.8 * inch, str(83100)) c.drawCentredString(6.1 * inch, 4.8 * inch, str(72800)) c.drawCentredString(6.95 * inch, 4.8 * inch, str(5910)) c.save() outfile.flush() return outfile
class Reporter(object): def __init__(self,vapp): self.dataApp = vapp path = self.dataApp.repoPath + self.dataApp.rdataName + '.pdf' self.canvas = Canvas(path) self.page = 1 def header(self): self.canvas.setFont("Helvetica", 10) self.canvas.drawCentredString(4.135*inch, 10.74*inch, 'Copyright@2015 : ycroft.net') self.canvas.setFont("Helvetica", 11.5) self.canvas.line(1*inch, 10.69*inch, 7.27*inch, 10.69*inch) def footer(self): self.canvas.setFont("Helvetica", 11.5) self.canvas.line(1*inch, 1*inch, 7.27*inch, 1*inch) self.canvas.setFont("Helvetica", 10) self.canvas.drawCentredString(4.135*inch, 0.83*inch, '- '+str(self.page)+' -') def cover(self,coverInfo): dataName = coverInfo.get('dataName','no name') author = coverInfo.get('author','no name') version = coverInfo.get('version','unknown') self.header() self.footer() self.canvas.setFont("Helvetica-Bold", 40) self.canvas.drawCentredString(4.135*inch, 7.5*inch, 'Analysis Report') self.canvas.setFont("Helvetica", 20) self.canvas.drawCentredString(4.135*inch, 6.8*inch, 'for data \'' + dataName + '\'') self.canvas.setFont("Helvetica", 15) self.canvas.drawRightString(3.935*inch, 4.4*inch, 'author:') self.canvas.drawRightString(3.935*inch, 3.9*inch, 'date:') self.canvas.drawRightString(3.935*inch, 3.4*inch, 'version:') self.canvas.drawString(4.335*inch, 4.4*inch, author) self.canvas.drawString(4.335*inch, 3.9*inch, str(datetime.now().strftime('%a, %b %d %H:%M'))) self.canvas.drawString(4.335*inch, 3.4*inch, version) self.canvas.showPage() self.page += 1 def body(self): self.header() self.footer() sdataName = self.dataApp.sdataName rdataName = self.dataApp.rdataName imgPath = './spec_data/img/' self.canvas.setFont("Helvetica-Bold", 15) self.canvas.drawString(1.25*inch, 10*inch, 'I. Modulation Factors ') self.canvas.setFont("Helvetica", 12) self.canvas.drawString(1.5*inch, 9.7*inch, 'These factors are derived from the file \''+sdataName+'\'') self.canvas.drawInlineImage(imgPath + sdataName + '_cs0.jpg',1.25*inch,5.3*inch,5.77*inch,4.33*inch) self.canvas.drawInlineImage(imgPath + sdataName + '_cs1.jpg',1.25*inch,1.2*inch,5.77*inch,4.33*inch) self.canvas.showPage() self.page += 1 self.header() self.footer() self.canvas.drawInlineImage(imgPath + sdataName + '_cs2.jpg',1.25*inch,5.3*inch,5.77*inch,4.33*inch) self.canvas.drawInlineImage(imgPath + sdataName + '_cs3.jpg',1.25*inch,1.2*inch,5.77*inch,4.33*inch) self.canvas.showPage() self.page += 1 self.header() self.footer() self.canvas.setFont("Helvetica-Bold", 15) self.canvas.drawString(1.25*inch, 10*inch, 'II. Measured Data & FFT ') self.canvas.setFont("Helvetica", 12) self.canvas.drawString(1.5*inch, 9.7*inch, 'The data is derived from the file \''+rdataName+'\', and each fft channel has been filtered.') self.canvas.drawInlineImage(imgPath + rdataName + '_rd.jpg',1.25*inch,5.3*inch,5.77*inch,4.33*inch) self.canvas.drawInlineImage(imgPath + rdataName + '_fft.jpg',1.25*inch,1.2*inch,5.77*inch,4.33*inch) self.canvas.showPage() self.page += 1 self.header() self.footer() self.canvas.setFont("Helvetica-Bold", 15) self.canvas.drawString(1.25*inch, 10*inch, 'III. Modulation Signals ') self.canvas.setFont("Helvetica", 12) self.canvas.drawString(1.5*inch, 9.7*inch, 'These signals are derived by ifft on the corresponding channel.') self.canvas.drawInlineImage(imgPath + rdataName + '_fa0.jpg',1.25*inch,5.3*inch,5.77*inch,4.33*inch) self.canvas.drawInlineImage(imgPath + rdataName + '_fa1.jpg',1.25*inch,1.2*inch,5.77*inch,4.33*inch) self.canvas.showPage() self.page += 1 self.header() self.footer() self.canvas.drawInlineImage(imgPath + rdataName + '_fa2.jpg',1.25*inch,5.3*inch,5.77*inch,4.33*inch) self.canvas.drawInlineImage(imgPath + rdataName + '_fa3.jpg',1.25*inch,1.2*inch,5.77*inch,4.33*inch) self.canvas.showPage() self.page += 1 self.header() self.footer() self.canvas.setFont("Helvetica-Bold", 15) self.canvas.drawString(1.25*inch, 10*inch, 'IV. Stokes Vectors ') self.canvas.setFont("Helvetica", 12) self.canvas.drawString(1.5*inch, 9.7*inch, 'This can be figured out using modulation signals and modulation factors.') self.canvas.drawInlineImage(imgPath + rdataName + '_s0.jpg',1.25*inch,5.3*inch,5.77*inch,4.33*inch) self.canvas.drawInlineImage(imgPath + rdataName + '_s1.jpg',1.25*inch,1.2*inch,5.77*inch,4.33*inch) self.canvas.showPage() self.page += 1 self.header() self.footer() self.canvas.drawInlineImage(imgPath + rdataName + '_s2.jpg',1.25*inch,5.3*inch,5.77*inch,4.33*inch) self.canvas.drawInlineImage(imgPath + rdataName + '_s3.jpg',1.25*inch,1.2*inch,5.77*inch,4.33*inch) self.canvas.showPage() self.page += 1 self.header() self.footer() self.canvas.setFont("Helvetica-Bold", 15) self.canvas.drawString(1.25*inch, 10*inch, 'IV. Degree of Polarization ') self.canvas.setFont("Helvetica", 12) self.canvas.drawString(1.5*inch, 9.7*inch, 'This was figured out using four Stokes vectors.') self.canvas.drawInlineImage(imgPath + rdataName + '_dop.jpg',1.25*inch,5.3*inch,5.77*inch,4.33*inch) self.canvas.showPage() self.page += 1 self.header() self.footer() windows = self.dataApp.windows self.canvas.setFont("Helvetica-Bold", 15) self.canvas.drawString(1.25*inch, 10*inch, 'V. Data Analysis ') self.canvas.setFont("Helvetica", 12) self.canvas.drawString(1.5*inch, 9.7*inch, 'This was automatically generated by program.') self.canvas.drawString(1.5*inch, 9.0*inch, '-The number of the peaks recognized in `FFT` datagram:') self.canvas.drawString(2.0*inch, 8.7*inch, str(len(windows)) + ' peaks') self.canvas.drawString(1.5*inch, 8.4*inch, '-The range of the peaks recognized in `FFT` datagram:') for i in range(0,len(windows)): self.canvas.drawString(2.0*inch, (8.1-i*0.3)*inch, '[' + str(i)+ '] ' +str(windows[i][0])) self.canvas.drawString(3.9*inch, (8.1-i*0.3)*inch, '~ ' + str(windows[i][1])) self.canvas.showPage() self.page += 1 def gen(self): self.cover({ 'dataName' : self.dataApp.rdataName + '`C spec', 'author' : 'ycroft', 'version' : 'v0.1' }) self.body() self.canvas.save()
def generate_certificate(description_of_items,cost_of_items,amount,cost,qty,raise_for,request ): buffer = BytesIO() styleSheet = getSampleStyleSheet() style = styleSheet['Normal'] canv = Canvas('my_pdf.pdf') canv.setFillColorRGB(0, 0, 255) canv.setFont('Helvetica-Bold', 44, leading=None) canv.drawCentredString(102, 800, "INVOICE") canv.setFont('Helvetica-Bold', 8, leading=None) #canv.drawCentredString(38, 824, "From:") b = Company_credentials.objects.get(user=request.user) canv.setFillColorRGB(0, 0, 255) canv.drawCentredString(480, 826, b.company_name) canv.drawCentredString(480, 813, b.email) canv.drawCentredString(480, 801, b.country + ',' + b.phone_number) #canv.drawCentredString(480, 790, b.email) canv.setFillColorRGB(0, 0, 0) canv.drawCentredString(480, 790, "Raised on:" + str(datetime.date.today()) ) canv.line(0, 785, 800, 785) canv.setFont('Helvetica', 21, leading=None) canv.setFillColorRGB(0, 0, 255) canv.drawCentredString(68, 760, "Description:") canv.setFillColorRGB(0, 0, 0) canv.setFont('Helvetica-Bold', 14, leading=None) canv.drawCentredString(120, 730, "ITEMS") canv.drawCentredString(320, 730, "RATE") canv.drawCentredString(410, 730, "QTY") canv.drawCentredString(500, 730, "AMOUNT") canv.setFont('Helvetica', 8, leading=None) y_coordinate = 710 chaska = 0 length = len(description_of_items) for chaska in range(length): canv.drawCentredString(120, y_coordinate,description_of_items[chaska]) canv.drawCentredString(320, y_coordinate, str(cost_of_items[chaska])) canv.drawCentredString(410, y_coordinate, str(qty[chaska])) canv.drawCentredString(500, y_coordinate, '$' + str(amount[chaska])) y_coordinate = y_coordinate - 15 y_coordinate = y_coordinate - 25 canv.line(310, y_coordinate, 580, y_coordinate) canv.setFont('Helvetica-Bold', 12, leading=None) canv.drawCentredString(410, y_coordinate-16, "Total") canv.drawCentredString(500, y_coordinate-16, '$' + str(cost)) canv.setFillColorRGB(0,0,255) canv.setFont('Helvetica', 16, leading=None) canv.drawCentredString(55, y_coordinate-16, "Raised For:") canv.setFillColorRGB(0, 0, 0) P = Paragraph(raise_for, style) aW = 180 aH = y_coordinate-46 w, h = P.wrap(aW, aH) # find required space if w <= aW and h <= aH: P.drawOn(canv, 12, aH) aH = aH - h # reduce the available height canv.save() pdf = buffer.getvalue() buffer.close() return pdf
def generateTablesPDF(self, response): response['Content-Disposition'] = 'attachment; filename=tables.pdf' pdf = Canvas(response) pdf.setStrokeColorRGB(0, 0, 0) brains = sorted(util.gatherTodaysEvents(self), key=attrgetter('location','start')) # Organize for Double-Sided Printing... prev = None mainArray = [] #init subArray = [] #init for brain in brains: if prev == brain.location: mainArray[len(mainArray)-1].append(brain) else: subArray = [] #reset list subArray.append(brain) mainArray.append(subArray) prev = brain.location #remember past # PDF Pages initPage = False for sarr in mainArray: #for Handles Two-Sided Pages! for j in range(self.printableSides): if initPage: pdf.showPage() else: initPage = True l = self.locationLookup(sarr[0].location) # HEADER FOOTER ------------------------------------------------------------ pdf = self.tableHeader(pdf,l['Name'],l['Description']) #Setup Header pdf = self.tableInformation(pdf) #Setup Information pdf = self.tableLink(pdf) pdf = self.tableFooter(pdf) #Setup Footer index = 695 #reset index for new page i = 0 #Reset for new page pdf.setFont("Helvetica-Bold", 18) pdf.drawCentredString(300,715, datetime.datetime.now().strftime("%A, %B %d, %Y") + " Schedule") # BODY ------------------------------------------------------------ for brain in sarr: #Body: Schedule Side pdf.rect(45, index-10, 510, 20, stroke=1, fill=0) #Schedule List Rectangles pdf.setFont("Helvetica", 17) if util.isPublic(self,brain.id): title = brain.Title else: title = "Private Group" pdf.drawString(50, index-5, DateTime(brain.start).strftime("%I:%M %p").lower() + " - " + DateTime(brain.end).strftime("%I:%M %p").lower() + " : " + title) index -= 20 i += 1 if i == self.DEFAULT_TABLE_LIMIT_SIZE: pdf.drawCentredString(300, index-5, "More groups are scheduled after last posted time,") pdf.drawCentredString(300, index-24, "please see Checkout and Reserves Desk.") break pdf.showPage() pdf.save() return response
def test0(self): # if they do not have the font files or encoding, go away quietly try: from reportlab.pdfbase.cidfonts import CIDFont, findCMapFile findCMapFile('KSCms-UHC-H') except: #don't have the font pack. return silently return localFontName = 'HYSMyeongJo-Medium' c = Canvas(outputfile('test_multibyte_kor.pdf')) c.setFont('Helvetica', 30) c.drawString(100,700, 'Korean Font Support') c.setFont('Helvetica', 10) c.drawString(100,680, 'Short sample in Unified Hangul Coding (UHC)') hBoxText('\xB9\xD9\xC5\xC1\xC3\xBC (HYSMyeongJo-Medium)', c, 100, 660, 'HYSMyeongJo-Medium', 'KSCms-UHC-H') ## hBoxText('\xB9\xD9\xC5\xC1\xC3\xBC (HYGothic-Medium)', ## c, 100, 640, 'HYGothic-Medium', 'KSCms-UHC-H') pdfmetrics.registerFont(CIDFont('HYSMyeongJo-Medium','KSC-EUC-H')) c.setFont('Helvetica', 10) c.drawString(100,610, "Longer sample From Adobe's Acrobat web page in EUC:") sample = """\xbf\xad \xbc\xf6 \xbe\xf8\xb4\xc2 \xb9\xae\xbc\xad\xb4\xc2 \xbe\xc6\xb9\xab\xb7\xb1 \xbc\xd2\xbf\xeb\xc0\xcc \xbe\xf8\xbd\xc0\xb4\xcf\xb4\xd9. \xbb\xe7\xbe\xf7 \xb0\xe8\xc8\xb9\xbc\xad, \xbd\xba\xc7\xc1\xb7\xb9\xb5\xe5\xbd\xc3\xc6\xae, \xb1\xd7\xb7\xa1\xc7\xc8\xc0\xcc \xb8\xb9\xc0\xcc \xc6\xf7\xc7\xd4\xb5\xc8 \xbc\xd2\xc3\xa5\xc0\xda \xb6\xc7\xb4\xc2 \xc0\xa5 \xbb\xe7\xc0\xcc\xc6\xae\xb8\xa6 \xc0\xdb\xbc\xba\xc7\xcf\xb4\xc2 \xb0\xe6\xbf\xec Adobe\xa2\xe7 Acrobat\xa2\xe7 5.0 \xbc\xd2\xc7\xc1\xc6\xae\xbf\xfe\xbe\xee\xb8\xa6 \xbb\xe7\xbf\xeb\xc7\xd8\xbc\xad \xc7\xd8\xb4\xe7 \xb9\xae\xbc\xad\xb8\xa6 Adobe Portable Document Format (PDF) \xc6\xc4\xc0\xcf\xb7\xce \xba\xaf\xc8\xaf\xc7\xd2 \xbc\xf6 \xc0\xd6\xbd\xc0\xb4\xcf\xb4\xd9. \xb4\xa9\xb1\xb8\xb3\xaa \xb1\xa4\xb9\xfc\xc0\xa7\xc7\xd1 \xc1\xbe\xb7\xf9\xc0\xc7 \xc7\xcf\xb5\xe5\xbf\xfe\xbe\xee\xbf\xcd \xbc\xd2\xc7\xc1\xc6\xae\xbf\xfe\xbe\xee\xbf\xa1\xbc\xad \xb9\xae\xbc\xad\xb8\xa6 \xbf\xad \xbc\xf6 \xc0\xd6\xc0\xb8\xb8\xe7 \xb7\xb9\xc0\xcc\xbe\xc6\xbf\xf4, \xc6\xf9\xc6\xae, \xb8\xb5\xc5\xa9, \xc0\xcc\xb9\xcc\xc1\xf6 \xb5\xee\xc0\xbb \xbf\xf8\xba\xbb \xb1\xd7\xb4\xeb\xb7\xce \xc0\xc7\xb5\xb5\xc7\xd1 \xb9\xd9 \xb4\xeb\xb7\xce \xc7\xa5\xbd\xc3\xc7\xd2 \xbc\xf6 \xc0\xd6\xbd\xc0\xb4\xcf\xb4\xd9. Acrobat 5.0\xc0\xbb \xbb\xe7\xbf\xeb\xc7\xcf\xbf\xa9 \xc0\xa5 \xba\xea\xb6\xf3\xbf\xec\xc0\xfa\xbf\xa1\xbc\xad \xb9\xae\xbc\xad\xb8\xa6 \xbd\xc2\xc0\xce\xc7\xcf\xb0\xed \xc1\xd6\xbc\xae\xc0\xbb \xc3\xdf\xb0\xa1\xc7\xcf\xb4\xc2 \xb9\xe6\xbd\xc4\xc0\xb8\xb7\xce \xb1\xe2\xbe\xf7\xc0\xc7 \xbb\xfd\xbb\xea\xbc\xba\xc0\xbb \xc7\xe2\xbb\xf3\xbd\xc3\xc5\xb3 \xbc\xf6 \xc0\xd6\xbd\xc0\xb4\xcf\xb4\xd9. \xc0\xfa\xc0\xdb\xb1\xc7 © 2001 Adobe Systems Incorporated. \xb8\xf0\xb5\xe7 \xb1\xc7\xb8\xae\xb0\xa1 \xba\xb8\xc8\xa3\xb5\xcb\xb4\xcf\xb4\xd9. \xbb\xe7\xbf\xeb\xc0\xda \xbe\xe0\xb0\xfc \xbf\xc2\xb6\xf3\xc0\xce \xbb\xe7\xbf\xeb\xc0\xda \xba\xb8\xc8\xa3 \xb1\xd4\xc1\xa4 Adobe\xc0\xc7 \xc0\xe5\xbe\xd6\xc0\xda \xc1\xf6\xbf\xf8 \xbc\xd2\xc7\xc1\xc6\xae\xbf\xfe\xbe\xee \xba\xd2\xb9\xfd \xc0\xcc\xbf\xeb \xb9\xe6\xc1\xf6 """ tx = c.beginText(100,600) tx.setFont('HYSMyeongJo-Medium-KSC-EUC-H', 7, 8) tx.textLines(sample) tx.setFont('Helvetica', 10, 12) tx.textLine() tx.textLines("""This test document shows Korean output from the Reportlab PDF Library. You may use one Korean font, HYSMyeongJo-Medium, and a number of different encodings. The available encoding names (with comments from the PDF specification) are: encodings_kor = [ 'KSC-EUC-H', # KS X 1001:1992 character set, EUC-KR encoding 'KSC-EUC-V', # Vertical version of KSC-EUC-H 'KSCms-UHC-H', # Microsoft Code Page 949 (lfCharSet 0x81), KS X 1001:1992 #character set plus 8,822 additional hangul, Unified Hangul #Code (UHC) encoding 'KSCms-UHC-V', #Vertical version of KSCms-UHC-H 'KSCms-UHC-HW-H', #Same as KSCms-UHC-H, but replaces proportional Latin # characters with halfwidth forms 'KSCms-UHC-HW-V', #Vertical version of KSCms-UHC-HW-H 'KSCpc-EUC-H', #Macintosh, KS X 1001:1992 character set with MacOS-KH #extensions, Script Manager Code 3 'UniKS-UCS2-H', #Unicode (UCS-2) encoding for the Adobe-Korea1 character collection 'UniKS-UCS2-V' #Vertical version of UniKS-UCS2-H ] The following pages show all characters in the KS X 1001:1992 standard, using the encoding 'KSC-EUC-H' above. More characters (a LOT more) are available if you use UHC encoding or the Korean Unicode subset, for which the correct encoding names are also listed above. """) c.drawText(tx) c.setFont('Helvetica',10) c.drawCentredString(297, 36, 'Page %d' % c.getPageNumber()) c.showPage() # full kuten chart in EUC c.setFont('Helvetica', 18) c.drawString(72,750, 'Characters available in KS X 1001:1992, EUC encoding') y = 600 for row in range(1, 95): KutenRowCodeChart(row, 'HYSMyeongJo-Medium','KSC-EUC-H').drawOn(c, 72, y) y = y - 125 if y < 50: c.setFont('Helvetica',10) c.drawCentredString(297, 36, 'Page %d' % c.getPageNumber()) c.showPage() y = 700 c.save() if VERBOSE: print 'saved '+outputfile('test_multibyte_kor.pdf')
class BadgeGen(): def __init__(self, festival, output): self.canvas = Canvas(output, pagesize=landscape(A4)) self.canvas.setLineWidth(0.25) self.pagemargin = 20*mm self.rowheight = (A4[0] - self.pagemargin*2.0) self.colwidth = (A4[1] - self.pagemargin*2.0) self.index = 0 self.bps = 1 self.colour = None self.festival = festival self.logoimage = None if self.festival['logo']: self.logoimage = ImageReader(self.festival['logo']) (w, h) = self.logoimage.getSize() if w > h: # Wide image. self.logowidth = 60*mm self.logoheight = h*60*mm/w else: # Tall image. self.logoheight = 60*mm self.logowidth = w*60*mm/h else: self.logoheight = self.logowidth = 0 # Size the festival name to fit fontsize = 36 availableWidth = self.colwidth - self.logowidth - 12*mm while (self.canvas.stringWidth(self.festival["name"], "Times-Roman", fontsize) > availableWidth): fontsize -= 1 self.festname_fontsize = fontsize if self.logoimage: if self.canvas.stringWidth(self.festival["name"], "Times-Roman", fontsize) < (availableWidth - self.logowidth): # Centre text on whole badge self.festname_x = self.colwidth/2 else: # Centre text between logo and RHS self.festname_x = self.colwidth/2 + self.logowidth/2 self.festname_y = self.rowheight - self.logoheight/2 - fontsize/2 else: self.festname_x = self.colwidth/2 self.festname_y = self.rowheight - 3*mm - fontsize/2 def _setup_page(self): # Output the colour if needed. if self.colour and ((self.index % self.bps) == 0): self.canvas.setFont("Times-Bold", 14) self.canvas.drawCentredString(A4[0]/2, A4[1] - self.pagemargin/2 - 7, "To be printed on %s paper" % self.colour) def Render(self, data, colour=None): if self.index == 0: self._setup_page() elif (self.colour != colour) or (self.index % self.bps == 0): # Start a fresh page - either we finished the last one or these need a different colour. self.canvas.showPage() self.colour = colour self._setup_page() # Local copy of index within the page. index = self.index % self.bps # Work out the co-ordinates for this index left = (index % 1) * self.colwidth + self.pagemargin bottom = (1 - 1 - ((index // 1) % 1)) * self.rowheight + self.pagemargin width = self.colwidth height = self.rowheight # Draw a box around the whole badge #self.canvas.setLineWidth(0.25) #self.canvas.rect (left, bottom, width, height) # Draw the logo, 2mm in from the top left, in a box if self.logoimage: logobottom = bottom + height - self.logoheight - 2*mm self.canvas.drawImage(self.logoimage, left + 2*mm, logobottom, self.logowidth, self.logoheight, preserveAspectRatio=True, anchor='nw') # Add the festival name, to the right of the logo self.canvas.setFont("Times-Roman", self.festname_fontsize) self.canvas.drawCentredString(self.festname_x + left, self.festname_y + bottom, self.festival['name']) # Add the registration, just below the middle of the badge. fontsize = 96 reg = data['registration'] while (self.canvas.stringWidth(reg, "Times-Bold", fontsize) > (width - 4*mm)): fontsize -= 1 self.canvas.setFont("Times-Bold", fontsize) self.canvas.drawCentredString(left + width/2, (bottom + height/2)-(fontsize/2)-2*mm, reg) fontsize = 32 volname = data['name'] while (self.canvas.stringWidth(reg, "Times-Bold", fontsize) > (width - 4*mm)): fontsize -= 1 self.canvas.setFont("Times-Bold", fontsize) self.canvas.drawCentredString(left + width/2, (bottom + height/2 - 96)-(fontsize/2)-2*mm, volname) # Add the phone, centred, 3mm in from the bottom. self.canvas.setFont("Times-Roman", 16) self.canvas.drawCentredString(left + width/2, bottom+3*mm, data['phone']) dayslist = list(data['days']) dayslist = ["Y" if (x == "1") else "" for x in dayslist] tabledata = [['F', 'S', 'S', 'M', 'T', 'W', 'T', 'F', 'S', 'S', 'M'],dayslist] # Draw the table for the days on site t=Table(tabledata,5*mm, 5*mm) t.setStyle(TableStyle([ ('FONT',(0,0),(-1,-1),'Courier',8), ('ALIGN',(0,0),(-1,-1),'CENTER'), ('VALIGN',(0,0),(-1,-1),'MIDDLE'), ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('BOX', (0,0), (-1,-1), 0.25, colors.black), ])) w,h = t.wrap(5*mm,5*mm) t.drawOn(self.canvas,left + width - w, bottom+2*mm) # Increment the sheet self.index = index + 1 def Save(self): self.canvas.save()
class InvoiceTemplate(object): def __init__(self, filename, logo_filename=LOGO_FILENAME, from_address=Address(**settings.INVOICE_FROM_ADDRESS), to_address=None, project_name='', invoice_date=None, invoice_number='', terms=settings.INVOICE_TERMS, due_date=None, date_start=None, date_end=None, bank_name=settings.BANK_NAME, bank_address=Address(**settings.BANK_ADDRESS), account_number=settings.BANK_ACCOUNT_NUMBER, routing_number_ach=settings.BANK_ROUTING_NUMBER_ACH, routing_number_wire=settings.BANK_ROUTING_NUMBER_WIRE, swift_code=settings.BANK_SWIFT_CODE, applied_credit=None, subtotal=None, tax_rate=None, applied_tax=None, total=None, is_wire=False, is_prepayment=False): self.canvas = Canvas(filename) self.canvas.setFontSize(DEFAULT_FONT_SIZE) self.logo_filename = os.path.join(os.getcwd(), logo_filename) self.from_address = from_address self.to_address = to_address self.project_name = project_name self.invoice_date = invoice_date self.invoice_number = invoice_number self.terms = terms self.due_date = due_date self.date_start = date_start self.date_end = date_end self.bank_name = bank_name self.bank_address = bank_address self.account_number = account_number self.routing_number_ach = routing_number_ach self.routing_number_wire = routing_number_wire self.swift_code = swift_code self.applied_credit = applied_credit self.subtotal = subtotal self.tax_rate = tax_rate self.applied_tax = applied_tax self.total = total self.is_wire = is_wire self.is_prepayment = is_prepayment self.items = [] def add_item(self, description, quantity, unit_cost, subtotal, credits, total): self.items.append(PdfLineItem(description, quantity, unit_cost, subtotal, credits, total)) def get_pdf(self): self.draw_logo() self.draw_from_address() self.draw_to_address() self.draw_project_name() if not self.is_prepayment: self.draw_statement_period() self.draw_invoice_label() self.draw_details() if not self.is_wire or self.is_prepayment: self.draw_table() self.draw_footer() self.canvas.showPage() self.canvas.save() def draw_logo(self): self.canvas.drawImage(self.logo_filename, inches(0.5), inches(2.5), width=inches(1.5), preserveAspectRatio=True) def draw_text(self, string, x, y): text = self.canvas.beginText() text.setTextOrigin(x, y) for line in string.split('\n'): text.textLine(line) self.canvas.drawText(text) def draw_from_address(self): if self.from_address is not None: self.draw_text(unicode(self.from_address), inches(3), inches(11)) def draw_to_address(self): origin_x = inches(1) origin_y = inches(9.2) self.canvas.translate(origin_x, origin_y) left = inches(0) right = inches(4.5) top = inches(0.3) middle_horizational = inches(0) bottom = inches(-1.7) self.canvas.rect(left, bottom, right - left, top - bottom) self.canvas.setFillColorRGB(*LIGHT_GRAY) self.canvas.rect(left, middle_horizational, right - left, top - middle_horizational, fill=1) self.canvas.setFillColorRGB(*BLACK) self.draw_text("Bill To", left + inches(0.2), middle_horizational + inches(0.1)) if self.to_address is not None: self.draw_text(unicode(self.to_address), inches(0.1), inches(-0.2)) self.canvas.translate(-origin_x, -origin_y) def draw_project_name(self): origin_x = inches(1) origin_y = inches(7.4) self.canvas.translate(origin_x, origin_y) left = inches(0) middle_vertical = inches(1) right = inches(4.5) top = inches(0) bottom = inches(-0.3) self.canvas.rect(left, bottom, right - left, top - bottom) self.canvas.setFillColorRGB(*LIGHT_GRAY) self.canvas.rect(left, bottom, middle_vertical - left, top - bottom, fill=1) self.canvas.setFillColorRGB(*BLACK) self.canvas.drawCentredString(midpoint(left, middle_vertical), bottom + inches(0.1), "Project") self.canvas.drawString(middle_vertical + inches(0.2), bottom + inches(0.1), self.project_name) self.canvas.translate(-origin_x, -origin_y) def draw_statement_period(self): origin_x = inches(1) origin_y = inches(6.75) self.canvas.translate(origin_x, origin_y) self.canvas.drawString( 0, 0, "Statement period from %s to %s" % (self.date_start.strftime(USER_DATE_FORMAT) if self.date_start is not None else "", self.date_end.strftime(USER_DATE_FORMAT) if self.date_end is not None else "")) self.canvas.translate(-origin_x, -origin_y) def draw_invoice_label(self): self.canvas.setFontSize(size=24) self.canvas.drawString(inches(6.5), inches(10.8), "Invoice") self.canvas.setFontSize(DEFAULT_FONT_SIZE) def draw_details(self): origin_x = inches(5.75) origin_y = inches(9.5) self.canvas.translate(origin_x, origin_y) left = inches(0) right = inches(2) bottom = inches(0) top = inches(1.25) label_height = (top - bottom) / 6.0 label_offset = label_height * 0.8 content_offset = 1.5 * label_offset middle_x = midpoint(left, right) middle_y = midpoint(bottom, top) self.canvas.setFillColorRGB(*LIGHT_GRAY) self.canvas.rect(left, middle_y - label_height, right - left, label_height, fill=1) self.canvas.rect(left, top - label_height, right - left, label_height, fill=1) self.canvas.setFillColorRGB(*BLACK) self.canvas.rect(left, bottom, right - left, top - bottom) self.canvas.rect(left, bottom, 0.5 * (right - left), top - bottom) self.canvas.rect(left, bottom, right - left, 0.5 * (top - bottom)) self.canvas.drawCentredString(midpoint(left, middle_x), top - label_offset, "Date") self.canvas.drawCentredString(midpoint(left, middle_x), top - label_height - content_offset, str(self.invoice_date)) self.canvas.drawCentredString(midpoint(middle_x, right), top - label_offset, "Invoice #") self.canvas.drawCentredString(midpoint(middle_x, right), top - label_height - content_offset, self.invoice_number) self.canvas.drawCentredString(midpoint(left, middle_x), middle_y - label_offset, "Terms") self.canvas.drawCentredString(midpoint(left, middle_x), middle_y - label_height - content_offset, self.terms) self.canvas.drawCentredString(midpoint(middle_x, right), middle_y - label_offset, "Due Date") self.canvas.drawCentredString(midpoint(middle_x, right), middle_y - label_height - content_offset, str(self.due_date)) self.canvas.translate(-origin_x, -origin_y) def draw_table(self): origin_x = inches(0.5) origin_y = inches(6.2) self.canvas.translate(origin_x, origin_y) height = inches(2.9) description_x = inches(2.4) quantity_x = inches(3.15) rate_x = inches(3.9) subtotal_x = inches(5.1) credits_x = inches(6.3) total_x = inches(7.5) header_height = inches(0.3) self.canvas.rect(0, 0, total_x, -height) self.canvas.setFillColorRGB(*LIGHT_GRAY) self.canvas.rect(0, 0, total_x, header_height, fill=1) self.canvas.setFillColorRGB(*BLACK) self.canvas.line(description_x, header_height, description_x, -height) self.canvas.line(quantity_x, header_height, quantity_x, -height) self.canvas.line(rate_x, header_height, rate_x, -height) self.canvas.line(subtotal_x, header_height, subtotal_x, -height) self.canvas.line(credits_x, header_height, credits_x, -height) self.canvas.drawCentredString(midpoint(0, description_x), inches(0.1), "Product") self.canvas.drawCentredString(midpoint(description_x, quantity_x), inches(0.1), "Quantity") self.canvas.drawCentredString(midpoint(quantity_x, rate_x), inches(0.1), "Unit Cost") self.canvas.drawCentredString(midpoint(rate_x, subtotal_x), inches(0.1), "Subtotal") self.canvas.drawCentredString(midpoint(subtotal_x, credits_x), inches(0.1), "Credits Applied") self.canvas.drawCentredString(midpoint(credits_x, total_x), inches(0.1), "Total") coord_y = 0 for item_index in range(len(self.items)): if coord_y < -height: raise InvoiceError("Cannot fit line items on invoice") item = self.items[item_index] description = Paragraph(item.description, ParagraphStyle('', fontSize=12, )) description.wrapOn(self.canvas, description_x - inches(0.2), -header_height) coord_y -= description.height + inches(0.05) description.drawOn(self.canvas, inches(0.1), coord_y) self.canvas.drawCentredString( midpoint(description_x, quantity_x), coord_y, str(item.quantity) ) self.canvas.drawCentredString( midpoint(quantity_x, rate_x), coord_y, get_money_str(item.unit_cost) ) self.canvas.drawCentredString( midpoint(rate_x, subtotal_x), coord_y, get_money_str(item.subtotal) ) self.canvas.drawCentredString( midpoint(subtotal_x, credits_x), coord_y, get_money_str(item.credits) ) self.canvas.drawCentredString( midpoint(credits_x, total_x), coord_y, get_money_str(item.total) ) coord_y -= inches(0.1) self.canvas.line(0, coord_y, total_x, coord_y) self.canvas.translate(-origin_x, -origin_y) def draw_footer(self): from corehq.apps.domain.views import DomainBillingStatementsView self.canvas.setFillColorRGB(*LIGHT_GRAY) self.canvas.rect(inches(5), inches(1.65), inches(3), inches(0.5), fill=1) self.canvas.setFillColorRGB(*BLACK) self.canvas.drawString(inches(5.6), inches(3.05), "Subtotal:") self.canvas.drawString(inches(5.6), inches(2.75), "Tax (%0.2f%%):" % self.tax_rate) self.canvas.drawString(inches(5.6), inches(2.45), "Credit:") self.canvas.drawString(inches(5.2), inches(1.85), "Total:") self.canvas.drawCentredString(midpoint(inches(7.0), inches(8.0)), inches(3.05), get_money_str(self.subtotal)) self.canvas.drawCentredString(midpoint(inches(7.0), inches(8.0)), inches(2.75), get_money_str(self.applied_tax)) self.canvas.drawCentredString(midpoint(inches(7.0), inches(8.0)), inches(2.45), get_money_str(self.applied_credit)) self.canvas.drawCentredString(midpoint(inches(7.0), inches(8.0)), inches(1.85), get_money_str(self.total)) self.canvas.drawString(inches(5), inches(1.4), "Thank you for using CommCare HQ.") payment_description = ( "Payment Options:<br />" "<strong>Credit card payments</strong> are preferred and can be made online here: " "<link href='%(payment_page)s' color='blue'>%(payment_page)s</link><br />" "<br />" "<strong>ACH or Wire:</strong> If you make payment via ACH or Wire, please make sure to email " "<font color='blue'>%(invoicing_contact_email)s</font> " "so that we can match your payment to the correct invoice. Please include: " "Invoice #, Project Space, and payment date in the email. <br />" ) % { 'invoicing_contact_email': settings.INVOICING_CONTACT_EMAIL, 'payment_page': absolute_reverse(DomainBillingStatementsView.urlname, args=[self.project_name]), } payment_info = Paragraph(payment_description, ParagraphStyle('')) payment_info.wrapOn(self.canvas, inches(4.25), inches(0.9)) payment_info.drawOn(self.canvas, inches(0.5), inches(1.8)) ach_payment_text = ( "<strong>ACH payment</strong> (preferred over wire payment for transfer in the US):<br />" "Bank: %(bank_name)s " "Bank Address: %(bank_address)s " "Account Number: %(account_number)s " "Routing Number or ABA: %(routing_number_ach)s<br />" ) % { 'bank_name': self.bank_name, 'bank_address': self.bank_address, 'account_number': self.account_number, 'routing_number_ach': self.routing_number_ach, } wire_payment_text = ( "<strong>Wire payment</strong>:<br />" "Bank: %(bank_name)s " "Bank Address: %(bank_address)s " "Account Number: %(account_number)s " "Routing Number or ABA: %(routing_number_wire)s " "Swift Code: %(swift_code)s<br/>" ) % { 'bank_name': self.bank_name, 'bank_address': self.bank_address, 'account_number': self.account_number, 'routing_number_wire': self.routing_number_wire, 'swift_code': self.swift_code, } payment_info2 = Paragraph('\n'.join([ ach_payment_text, wire_payment_text, ]), ParagraphStyle('')) payment_info2.wrapOn(self.canvas, inches(4.25), inches(0.9)) payment_info2.drawOn(self.canvas, inches(0.7), inches(0.4))
class InvoiceTemplate(object): def __init__(self, filename, logo_filename=LOGO_FILENAME, from_address=Address(**settings.INVOICE_FROM_ADDRESS), to_address=None, project_name='', invoice_date=None, invoice_number='', terms=settings.INVOICE_TERMS, due_date=None, date_start=None, date_end=None, bank_name=settings.BANK_NAME, bank_address=Address(**settings.BANK_ADDRESS), account_number=settings.BANK_ACCOUNT_NUMBER, routing_number=settings.BANK_ROUTING_NUMBER, swift_code=settings.BANK_SWIFT_CODE, applied_credit=None, subtotal=None, tax_rate=None, applied_tax=None, total=None): self.canvas = Canvas(filename) self.canvas.setFontSize(DEFAULT_FONT_SIZE) self.logo_filename = os.path.join(os.getcwd(), logo_filename) self.from_address = from_address self.to_address = to_address self.project_name = project_name self.invoice_date = invoice_date self.invoice_number = invoice_number self.terms = terms self.due_date = due_date self.date_start = date_start self.date_end = date_end self.bank_name = bank_name self.bank_address = bank_address self.account_number = account_number self.routing_number = routing_number self.swift_code = swift_code self.applied_credit = applied_credit self.subtotal = subtotal self.tax_rate = tax_rate self.applied_tax = applied_tax self.total = total self.items = [] def add_item(self, description, quantity, unit_cost, subtotal, credits, total): self.items.append(PdfLineItem(description, quantity, unit_cost, subtotal, credits, total)) def get_pdf(self): self.draw_logo() self.draw_from_address() self.draw_to_address() self.draw_project_name() self.draw_statement_period() self.draw_invoice_label() self.draw_details() self.draw_table() self.draw_footer() self.canvas.showPage() self.canvas.save() def draw_logo(self): self.canvas.drawImage(self.logo_filename, inches(0.5), inches(2.5), width=inches(1.5), preserveAspectRatio=True) def draw_text(self, string, x, y): text = self.canvas.beginText() text.setTextOrigin(x, y) for line in string.split('\n'): text.textLine(line) self.canvas.drawText(text) def draw_from_address(self): if self.from_address is not None: self.draw_text(unicode(self.from_address), inches(3), inches(11)) def draw_to_address(self): origin_x = inches(1) origin_y = inches(9.2) self.canvas.translate(origin_x, origin_y) left = inches(0) right = inches(4.5) top = inches(0.3) middle_horizational = inches(0) bottom = inches(-1.7) self.canvas.rect(left, bottom, right - left, top - bottom) self.canvas.setFillColorRGB(*LIGHT_GRAY) self.canvas.rect(left, middle_horizational, right - left, top - middle_horizational, fill=1) self.canvas.setFillColorRGB(*BLACK) self.draw_text("Bill To", left + inches(0.2), middle_horizational + inches(0.1)) if self.to_address is not None: self.draw_text(unicode(self.to_address), inches(0.1), inches(-0.2)) self.canvas.translate(-origin_x, -origin_y) def draw_project_name(self): origin_x = inches(1) origin_y = inches(7.4) self.canvas.translate(origin_x, origin_y) left = inches(0) middle_vertical = inches(1) right = inches(4.5) top = inches(0) bottom = inches(-0.3) self.canvas.rect(left, bottom, right - left, top - bottom) self.canvas.setFillColorRGB(*LIGHT_GRAY) self.canvas.rect(left, bottom, middle_vertical - left, top - bottom, fill=1) self.canvas.setFillColorRGB(*BLACK) self.canvas.drawCentredString(midpoint(left, middle_vertical), bottom + inches(0.1), "Project") self.canvas.drawString(middle_vertical + inches(0.2), bottom + inches(0.1), self.project_name) self.canvas.translate(-origin_x, -origin_y) def draw_statement_period(self): origin_x = inches(1) origin_y = inches(6.75) self.canvas.translate(origin_x, origin_y) self.canvas.drawString( 0, 0, "Statement period from %s to %s" % (self.date_start.strftime("%d %B %Y") if self.date_start is not None else "", self.date_end.strftime("%d %B %Y") if self.date_end is not None else "")) self.canvas.translate(-origin_x, -origin_y) def draw_invoice_label(self): self.canvas.setFontSize(size=24) self.canvas.drawString(inches(6.5), inches(10.8), "Invoice") self.canvas.setFontSize(DEFAULT_FONT_SIZE) def draw_details(self): origin_x = inches(5.75) origin_y = inches(9.5) self.canvas.translate(origin_x, origin_y) left = inches(0) right = inches(2) bottom = inches(0) top = inches(1.25) label_height = (top - bottom) / 6.0 label_offset = label_height * 0.8 content_offset = 1.5 * label_offset middle_x = midpoint(left, right) middle_y = midpoint(bottom, top) self.canvas.setFillColorRGB(*LIGHT_GRAY) self.canvas.rect(left, middle_y - label_height, right - left, label_height, fill=1) self.canvas.rect(left, top - label_height, right - left, label_height, fill=1) self.canvas.setFillColorRGB(*BLACK) self.canvas.rect(left, bottom, right - left, top - bottom) self.canvas.rect(left, bottom, 0.5 * (right - left), top - bottom) self.canvas.rect(left, bottom, right - left, 0.5 * (top - bottom)) self.canvas.drawCentredString(midpoint(left, middle_x), top - label_offset, "Date") self.canvas.drawCentredString(midpoint(left, middle_x), top - label_height - content_offset, str(self.invoice_date)) self.canvas.drawCentredString(midpoint(middle_x, right), top - label_offset, "Invoice #") self.canvas.drawCentredString(midpoint(middle_x, right), top - label_height - content_offset, self.invoice_number) self.canvas.drawCentredString(midpoint(left, middle_x), middle_y - label_offset, "Terms") self.canvas.drawCentredString(midpoint(left, middle_x), middle_y - label_height - content_offset, self.terms) self.canvas.drawCentredString(midpoint(middle_x, right), middle_y - label_offset, "Due Date") self.canvas.drawCentredString(midpoint(middle_x, right), middle_y - label_height - content_offset, str(self.due_date)) self.canvas.translate(-origin_x, -origin_y) def draw_table(self): origin_x = inches(0.5) origin_y = inches(6.2) self.canvas.translate(origin_x, origin_y) height = inches(3.5) description_x = inches(2.4) quantity_x = inches(3.15) rate_x = inches(3.9) subtotal_x = inches(5.1) credits_x = inches(6.3) total_x = inches(7.5) header_height = inches(0.3) self.canvas.rect(0, 0, total_x, -height) self.canvas.setFillColorRGB(*LIGHT_GRAY) self.canvas.rect(0, 0, total_x, header_height, fill=1) self.canvas.setFillColorRGB(*BLACK) self.canvas.line(description_x, header_height, description_x, -height) self.canvas.line(quantity_x, header_height, quantity_x, -height) self.canvas.line(rate_x, header_height, rate_x, -height) self.canvas.line(subtotal_x, header_height, subtotal_x, -height) self.canvas.line(credits_x, header_height, credits_x, -height) self.canvas.drawCentredString(midpoint(0, description_x), inches(0.1), "Product") self.canvas.drawCentredString(midpoint(description_x, quantity_x), inches(0.1), "Quantity") self.canvas.drawCentredString(midpoint(quantity_x, rate_x), inches(0.1), "Unit Cost") self.canvas.drawCentredString(midpoint(rate_x, subtotal_x), inches(0.1), "Subtotal") self.canvas.drawCentredString(midpoint(subtotal_x, credits_x), inches(0.1), "Credits Applied") self.canvas.drawCentredString(midpoint(credits_x, total_x), inches(0.1), "Total") coord_y = 0 for item_index in range(len(self.items)): if coord_y < -height: raise InvoiceError("Cannot fit line items on invoice") item = self.items[item_index] description = Paragraph(item.description, ParagraphStyle('', fontSize=12, )) description.wrapOn(self.canvas, description_x - inches(0.2), -header_height) coord_y -= description.height + inches(0.05) description.drawOn(self.canvas, inches(0.1), coord_y) self.canvas.drawCentredString( midpoint(description_x, quantity_x), coord_y, str(item.quantity) ) self.canvas.drawCentredString( midpoint(quantity_x, rate_x), coord_y, get_money_str(item.unit_cost) ) self.canvas.drawCentredString( midpoint(rate_x, subtotal_x), coord_y, get_money_str(item.subtotal) ) self.canvas.drawCentredString( midpoint(subtotal_x, credits_x), coord_y, get_money_str(item.credits) ) self.canvas.drawCentredString( midpoint(credits_x, total_x), coord_y, get_money_str(item.total) ) coord_y -= inches(0.1) self.canvas.line(0, coord_y, total_x, coord_y) self.canvas.translate(-origin_x, -origin_y) def draw_footer(self): self.canvas.rect(inches(0.75), inches(1.3), inches(4), inches(0.5)) self.canvas.setFillColorRGB(*LIGHT_GRAY) self.canvas.rect(inches(5), inches(1.05), inches(3), inches(0.5), fill=1) self.canvas.setFillColorRGB(*BLACK) self.canvas.drawString(inches(5.6), inches(2.45), "Subtotal:") self.canvas.drawString(inches(5.6), inches(2.15), "Tax (%s%%):" % get_money_str(self.tax_rate)) self.canvas.drawString(inches(5.6), inches(1.85), "Credit:") self.canvas.drawString(inches(5.2), inches(1.25), "Total:") self.canvas.drawCentredString(midpoint(inches(7.0), inches(8.0)), inches(2.45), get_money_str(self.subtotal)) self.canvas.drawCentredString(midpoint(inches(7.0), inches(8.0)), inches(2.15), get_money_str(self.applied_tax)) self.canvas.drawCentredString(midpoint(inches(7.0), inches(8.0)), inches(1.85), get_money_str(self.applied_credit)) self.canvas.drawCentredString(midpoint(inches(7.0), inches(8.0)), inches(1.25), get_money_str(self.total)) self.canvas.drawString(inches(5), inches(0.8), "Thank you for using CommCare HQ.") footer_text = ("Payable by check or wire transfer. " "Wire transfer is preferred: " "Bank: %(bank_name)s " "Bank Address: %(bank_address)s " "Account Number: %(account_number)s " "Routing Number or ABA: %(routing_number)s " "Swift Code: %(swift_code)s") % { 'bank_name': self.bank_name, 'bank_address': self.bank_address, 'account_number': self.account_number, 'routing_number': self.routing_number, 'swift_code': self.swift_code, } payment_info = Paragraph(footer_text, ParagraphStyle('')) payment_info.wrapOn(self.canvas, inches(4), inches(0.9)) payment_info.drawOn(self.canvas, inches(0.75), inches(0.6))
def test0(self): "A basic document drawing some strings" # if they do not have the Japanese font files, go away quietly from reportlab.pdfbase.cidfonts import CIDFont, findCMapFile enc = 'ETenms-B5-H' try: findCMapFile(enc) except: #they don't have the font pack, return silently return pdfmetrics.registerFont(CIDFont('MSung-Light',enc)) c = Canvas(outputfile('test_multibyte_cht.pdf')) c.setFont('Helvetica', 24) c.drawString(100,700, 'Traditional Chinese Font Support') c.setFont('Helvetica', 10) c.drawString(100,680, 'Short sample: headline from Yahoo Hong Kong, 20 Oct 2001') c.setFont('MSung-Light-' + enc, 12) # this came from Yahoo Hong Kong leading story today message1 = '\xa5\xac\xae\xed\xbbP\xa6\xbf\xbfA\xa5\xc1\xa6b\xad\xba\xa6\xb8\xb7|\xad\xb1\xab\xe1\xa4@\xa6P\xa8\xa3\xb0O\xaa\xcc\xa1A\xa5L\xbb\xa1\xa1A\xa8\xe2\xa4H\xaa\xba\xad\xba\xa6\xb8\xb7|\xad\xb1\xabD\xb1`' message2 = '\xa6n\xa1A\xa8\xc3\xaa\xed\xa5\xdc\xb2@\xb5L\xba\xc3\xb0\xdd\xa4\xa4\xb0\xea\xa6b\xb3o\xad\xd3\xa5i\xa9\xc6\xaa\xba\xae\xc9\xa8\xe8\xa1A\xb7|\xbbP\xac\xfc\xb0\xea\xa4H\xa5\xc1\xaf\xb8\xa6b\xa4@\xb0_\xa1C' message3 = '\xA7\x41\xA6\x6E\xB6\xDC' c.drawString(100, 655, message1) c.drawString(100, 639, message2) hBoxText(message3 + ' MSung-Light' , c, 100, 600, 'MSung-Light', enc) #hBoxText(message3 + ' MHei-Medium', c, 100, 580, 'MHei-Medium', enc) c.setFont('Helvetica', 10) tx = c.beginText(100, 500) tx.textLines(""" This test document shows Traditional Chinese output from Reportlab PDF Library. You may use one Chinese font, MSung-Light, and a number of different encodings. The available encoding names (with comments from the PDF specification) are: encodings_cht = [ 'B5pc-H', # Macintosh, Big Five character set, Big Five encoding, # Script Manager code 2 'B5pc-V', # Vertical version of B5pc-H 'ETen-B5-H', # Microsoft Code Page 950 (lfCharSet 0x88), Big Five # character set with ETen extensions 'ETen-B5-V', # Vertical version of ETen-B5-H 'ETenms-B5-H', # Microsoft Code Page 950 (lfCharSet 0x88), Big Five # character set with ETen extensions; this uses proportional # forms for half-width Latin characters. 'ETenms-B5-V', # Vertical version of ETenms-B5-H 'CNS-EUC-H', # CNS 11643-1992 character set, EUC-TW encoding 'CNS-EUC-V', # Vertical version of CNS-EUC-H 'UniCNS-UCS2-H', # Unicode (UCS-2) encoding for the Adobe-CNS1 # character collection 'UniCNS-UCS2-V' # Vertical version of UniCNS-UCS2-H. ] The next 32 pages show the complete character set available in the encoding "ETen-B5-H". This is Big5 with the ETen extensions. ETen extensions are the most common extension to Big5 and include circled and roman numbers, Japanese hiragana and katakana, Cyrillic and fractions in rows C6-C8; and 7 extra characters and some line drawing characters in row F9. """) c.drawText(tx) c.setFont('Helvetica',10) c.drawCentredString(297, 36, 'Page %d' % c.getPageNumber()) c.showPage() # full Big5 code page c.setFont('Helvetica', 18) c.drawString(72,750, 'Characters available in Big 5') y = 500 for row in range(0xA1,0xFF): cc = Big5CodeChart(row, 'MSung-Light',enc) cc.charsPerRow = 16 cc.rows = 10 cc.codePoints = 160 cc.drawOn(c, 72, y) y = y - cc.height - 25 if y < 50: c.setFont('Helvetica',10) c.drawCentredString(297, 36, 'Page %d' % c.getPageNumber()) c.showPage() y = 600 c.save() if VERBOSE: print 'saved '+outputfile('test_multibyte_cht.pdf')
def get(self, request, *args, **kwargs): self.object = self.get_object() response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="{0}-{1}.pdf"'.format(self.object.registru.serie, self.object.numar_inregistrare) pdf = Canvas(response, pagesize = A4) import os from reportlab.lib.styles import getSampleStyleSheet from reportlab.platypus import Paragraph pdfmetrics.registerFont(TTFont("DejaVuSans-Bold", "/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans-Bold.ttf")) pdfmetrics.registerFont(TTFont("DejaVuSans", "/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf")) if self.object.registru.centru_local.antet: antet_path = os.path.join(settings.MEDIA_ROOT, "%s" % self.object.registru.centru_local.antet) pdf.drawInlineImage(antet_path, 2.5 * cm, 10.8 * cm, width=16. * cm, height=2.66 * cm) pdf.drawInlineImage(antet_path, 2.5 * cm, 24.5 * cm, width=16. * cm, height=2.66 * cm) pdf.setStrokeColorRGB(0, 0, 0) pdf.rect(2. * cm, 2. * cm, 17. * cm, 12. * cm) pdf.rect(2. * cm, 15.7 * cm, 17. * cm, 12 * cm) pdf.setStrokeColorRGB(0.5, 0.5, 0.5) pdf.setDash(1, 2) pdf.line(0 * cm, 14.85 * cm, 21. * cm, 14.85 * cm) pdf.setFont("DejaVuSans-Bold", 0.5 * cm, leading=None) pdf.drawCentredString(10.5 * cm, 9.5 * cm, u"Chitanță") pdf.drawCentredString(10.5 * cm, 23.2 * cm, u"Chitanță") text_serie = u"seria {0}, nr. {1} / {2}".format(self.object.registru.serie, self.object.numar_inregistrare, self.object.data_inregistrare.strftime("%d.%m.%Y")) pdf.setFont("DejaVuSans-Bold", 4. * cm, leading=None) pdf.setFillColorRGB(0.95, 0.95, 0.95) pdf.rotate(15) pdf.drawString(4.5 * cm, 2. * cm, u"COPIE") pdf.rotate(-15) pdf.setFillColorRGB(0, 0, 0) pdf.setFont("DejaVuSans", 0.35 * cm, leading=None) pdf.drawCentredString(10.5 * cm, 8.9 * cm, text_serie) pdf.drawCentredString(10.5 * cm, 22.6 * cm, text_serie) reprezinta = self.object.descriere if hasattr(self.object, "chitantacotizatie"): reprezinta = [] for p in self.object.chitantacotizatie.platacotizatietrimestru_set.all().order_by("index"): date_reprezinta = (p.trimestru.__unicode__(), p.suma, u"- parțial" if p.partial else "") reprezinta.append("{0} ({1} RON{2})".format(*date_reprezinta)) reprezinta = ", ".join(reprezinta) reprezinta = u"cotizație membru pentru {0}".format(reprezinta) date_chitanta = (self.object.platitor().__unicode__(), self.object.suma, suma2text(self.object.suma).strip(), reprezinta) text_chitanta = u"Am primit de la <strong>{0}</strong> suma de {1} lei, adică {2}, reprezentând {3}.".format(*date_chitanta) style_sheet = getSampleStyleSheet() style = style_sheet['Normal'] style.alignment = TA_JUSTIFY style.fontName = "DejaVuSans" style.leading = 0.85 * cm paragraph = Paragraph(text_chitanta, style) w, h = paragraph.wrap(15. * cm, 5. * cm) # print w, h paragraph.drawOn(pdf, 3. * cm, 5.5 * cm) paragraph.drawOn(pdf, 3. * cm, 19.2 * cm) pdf.drawString(12.5 * cm, 4.5 * cm, u"Casier,") pdf.drawString(12.5 * cm, 18.2 * cm, u"Casier, ") trezorier = self.object.registru.centru_local.ocupant_functie(u"Trezorier Centru Local") pdf.drawString(12.5 * cm, 3.8 * cm, trezorier.__unicode__()) pdf.drawString(12.5 * cm, 17.5 * cm, trezorier.__unicode__()) pdf.showPage() pdf.save() return response
def test0(self): "A basic document drawing some strings" # if they do not have the Japanese font files, go away quietly from reportlab.pdfbase.cidfonts import CIDFont, findCMapFile enc = 'GB-EUC-H' try: findCMapFile(enc) except: #they don't have the font pack, return silently return pdfmetrics.registerFont(CIDFont('STSong-Light',enc)) c = Canvas(outputfile('test_multibyte_chs.pdf')) c.setFont('Helvetica', 30) c.drawString(100,700, 'Simplified Chinese Font Support') c.setFont('Helvetica', 10) c.drawString(100,680, 'Short sample: "Reportlab is cool!" (or so we are told)') # the two typefaces hBoxText('\xce\xc4\xbd\xa1\xb5\xc3\xb5\xbd\xc1\xcb \xc4\xc7\xd5\xfd\xba\xc3\xb0\xa2 \xce\xd2 \xba\xdc\xcf\xb2\xbb\xb6. Cool!', c, 100, 660, 'STSong-Light', enc) c.setFont('Helvetica', 10) tx = c.beginText(100, 500) tx.textLines(""" This test document shows Simplified Chinese output from the Reportlab PDF Library. You may use one Chinese font, STSong-Light, and a number of different encodings. The available encoding names (with comments from the PDF specification) are: encodings_chs = [ 'GB-EUC-H', # Microsoft Code Page 936 (lfCharSet 0x86), GB 2312-80 # character set, EUC-CN encoding 'GB-EUC-V', # Vertical version of GB-EUC-H 'GBpc-EUC-H', # Macintosh, GB 2312-80 character set, EUC-CN encoding, # Script Manager code 2 'GBpc-EUC-V', # Vertical version of GBpc-EUC-H 'GBK-EUC-H', # Microsoft Code Page 936 (lfCharSet 0x86), GBK character # set, GBK encoding 'GBK-EUC-V', # Vertical version of GBK-EUC-V 'UniGB-UCS2-H', # Unicode (UCS-2) encoding for the Adobe-GB1 # character collection 'UniGB-UCS2-V' # Vertical version of UniGB-UCS2-H. ] The next few pages show the complete character set available in the encoding "GB-EUC-H". This is the GB 2312-80 character set. """) c.drawText(tx) c.setFont('Helvetica',10) c.drawCentredString(297, 36, 'Page %d' % c.getPageNumber()) c.showPage() # full kuten chart in EUC c.setFont('Helvetica', 18) c.drawString(72,750, 'Characters available in GB 2312-80, EUC encoding') y = 600 for row in range(1, 95): KutenRowCodeChart(row, 'STSong-Light',enc).drawOn(c, 72, y) y = y - 125 if y < 50: c.setFont('Helvetica',10) c.drawCentredString(297, 36, 'Page %d' % c.getPageNumber()) c.showPage() y = 700 c.save() if VERBOSE: print 'saved '+outputfile('test_multibyte_chs.pdf')
def test0(self): "A basic document drawing some strings" c = Canvas(outputfile('test_multibyte_jpn.pdf')) c.setFont('Helvetica', 30) c.drawString(100,700, 'Japanese Font Support') c.setStrokeColor(colors.red) #unicode font automatically supplies the encoding pdfmetrics.registerFont(UnicodeCIDFont('HeiseiMin-W3')) msg = u'\u6771\u4EAC : Unicode font, unicode input' self.hDraw(c, msg, 'HeiseiMin-W3', 100, 600) msg = u'\u6771\u4EAC : Unicode font, utf8 input'.encode('utf8') self.hDraw(c, msg, 'HeiseiMin-W3', 100, 575) # now try verticals - this is broken, not sure how to make it # work in post Unicode world. pdfmetrics.registerFont(CIDFont('HeiseiMin-W3','90ms-RKSJ-V')) c.setFont('HeiseiMin-W3-90ms-RKSJ-V', 16) c.drawString(450, 650, '\223\214\213\236 vertical Shift-JIS') height = c.stringWidth('\223\214\213\236 vertical Shift-JIS', 'HeiseiMin-W3-90ms-RKSJ-V', 16) c.rect(450-8,650,16,-height) pdfmetrics.registerFont(CIDFont('HeiseiMin-W3','EUC-V')) c.setFont('HeiseiMin-W3-EUC-V', 16) c.drawString(475, 650, '\xC5\xEC\xB5\xFE vertical EUC') height = c.stringWidth('\xC5\xEC\xB5\xFE vertical EUC', 'HeiseiMin-W3-EUC-V', 16) c.rect(475-8,650,16,-height) from reportlab.platypus.paragraph import Paragraph from reportlab.lib.styles import ParagraphStyle jStyle = ParagraphStyle('jtext', fontName='HeiseiMin-W3', fontSize=12, wordWrap="CJK" ) gatwickText = '\xe3\x82\xac\xe3\x83\x88\xe3\x82\xa6\xe3\x82\xa3\xe3\x83\x83\xe3\x82\xaf\xe7\xa9\xba\xe6\xb8\xaf\xe3\x81\xa8\xe9\x80\xa3\xe7\xb5\xa1\xe9\x80\x9a\xe8\xb7\xaf\xe3\x81\xa7\xe7\x9b\xb4\xe7\xb5\x90\xe3\x81\x95\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x84\xe3\x82\x8b\xe5\x94\xaf\xe4\xb8\x80\xe3\x81\xae\xe3\x83\x9b\xe3\x83\x86\xe3\x83\xab\xe3\x81\xa7\xe3\x81\x82\xe3\x82\x8b\xe5\xbd\x93\xe3\x83\x9b\xe3\x83\x86\xe3\x83\xab\xe3\x81\xaf\xe3\x80\x81\xe8\xa1\x97\xe3\x81\xae\xe4\xb8\xad\xe5\xbf\x83\xe9\x83\xa8\xe3\x81\x8b\xe3\x82\x8930\xe5\x88\x86\xe3\x81\xae\xe5\xa0\xb4\xe6\x89\x80\xe3\x81\xab\xe3\x81\x94\xe3\x81\x96\xe3\x81\x84\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82\xe5\x85\xa8\xe5\xae\xa2\xe5\xae\xa4\xe3\x81\xab\xe9\xab\x98\xe9\x80\x9f\xe3\x82\xa4\xe3\x83\xb3\xe3\x82\xbf\xe3\x83\xbc\xe3\x83\x8d\xe3\x83\x83\xe3\x83\x88\xe7\x92\xb0\xe5\xa2\x83\xe3\x82\x92\xe5\xae\x8c\xe5\x82\x99\xe3\x81\x97\xe3\x81\xa6\xe3\x81\x8a\xe3\x82\x8a\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82\xe3\x83\x95\xe3\x82\xa1\xe3\x83\x9f\xe3\x83\xaa\xe3\x83\xbc\xe3\x83\xab\xe3\x83\xbc\xe3\x83\xa0\xe3\x81\xaf5\xe5\x90\x8d\xe6\xa7\x98\xe3\x81\xbe\xe3\x81\xa7\xe3\x81\x8a\xe6\xb3\x8a\xe3\x82\x8a\xe3\x81\x84\xe3\x81\x9f\xe3\x81\xa0\xe3\x81\x91\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82\xe3\x81\xbe\xe3\x81\x9f\xe3\x80\x81\xe3\x82\xa8\xe3\x82\xb0\xe3\x82\xbc\xe3\x82\xaf\xe3\x83\x86\xe3\x82\xa3\xe3\x83\x96\xe3\x83\xab\xe3\x83\xbc\xe3\x83\xa0\xe3\x81\xae\xe3\x81\x8a\xe5\xae\xa2\xe6\xa7\x98\xe3\x81\xaf\xe3\x80\x81\xe3\x82\xa8\xe3\x82\xb0\xe3\x82\xbc\xe3\x82\xaf\xe3\x83\x86\xe3\x82\xa3\xe3\x83\x96\xe3\x83\xa9\xe3\x82\xa6\xe3\x83\xb3\xe3\x82\xb8\xe3\x82\x92\xe3\x81\x94\xe5\x88\xa9\xe7\x94\xa8\xe3\x81\x84\xe3\x81\x9f\xe3\x81\xa0\xe3\x81\x91\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82\xe4\xba\x8b\xe5\x89\x8d\xe3\x81\xab\xe3\x81\x94\xe4\xba\x88\xe7\xb4\x84\xe3\x81\x84\xe3\x81\x9f\xe3\x81\xa0\xe3\x81\x91\xe3\x82\x8b\xe3\x82\xbf\xe3\x82\xa4\xe3\x83\xa0\xe3\x83\x88\xe3\x82\xa5\xe3\x83\x95\xe3\x83\xa9\xe3\x82\xa4\xe3\x83\xbb\xe3\x83\x91\xe3\x83\x83\xe3\x82\xb1\xe3\x83\xbc\xe3\x82\xb8\xe3\x81\xab\xe3\x81\xaf\xe3\x80\x81\xe7\xa9\xba\xe6\xb8\xaf\xe3\x81\xae\xe9\xa7\x90\xe8\xbb\x8a\xe6\x96\x99\xe9\x87\x91\xe3\x81\x8c\xe5\x90\xab\xe3\x81\xbe\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x8a\xe3\x82\x8a\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82' gatwickText2= '\xe3\x82\xac\xe3\x83\x88\xe3\x82\xa6\xe3\x82\xa3\xe3\x83\x83\xe3\x82\xaf<font color=red>\xe7\xa9\xba\xe6\xb8\xaf\xe3\x81\xa8\xe9\x80\xa3\xe7\xb5\xa1\xe9\x80\x9a\xe8\xb7\xaf\xe3\x81\xa7\xe7\x9b\xb4\xe7\xb5\x90</font>\xe3\x81\x95\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x84\xe3\x82\x8b\xe5\x94\xaf\xe4\xb8\x80\xe3\x81\xae\xe3\x83\x9b\xe3\x83\x86\xe3\x83\xab\xe3\x81\xa7\xe3\x81\x82\xe3\x82\x8b\xe5\xbd\x93\xe3\x83\x9b\xe3\x83\x86\xe3\x83\xab\xe3\x81\xaf\xe3\x80\x81\xe8\xa1\x97\xe3\x81\xae\xe4\xb8\xad\xe5\xbf\x83\xe9\x83\xa8\xe3\x81\x8b\xe3\x82\x8930\xe5\x88\x86\xe3\x81\xae\xe5\xa0\xb4\xe6\x89\x80\xe3\x81\xab\xe3\x81\x94\xe3\x81\x96\xe3\x81\x84\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82\xe5\x85\xa8\xe5\xae\xa2\xe5\xae\xa4\xe3\x81\xab\xe9\xab\x98\xe9\x80\x9f\xe3\x82\xa4\xe3\x83\xb3\xe3\x82\xbf\xe3\x83\xbc\xe3\x83\x8d\xe3\x83\x83\xe3\x83\x88<link fg="blue" href="http://www.reportlab.com">\xe7\x92\xb0\xe5\xa2\x83\xe3\x82\x92\xe5\xae\x8c\xe5\x82\x99</link>\xe3\x81\x97\xe3\x81\xa6<u>\xe3\x81\x8a\xe3\x82\x8a\xe3\x81\xbe\xe3\x81\x99</u>\xe3\x80\x82\xe3\x83\x95\xe3\x82\xa1\xe3\x83\x9f\xe3\x83\xaa\xe3\x83\xbc\xe3\x83\xab\xe3\x83\xbc\xe3\x83\xa0\xe3\x81\xaf5\xe5\x90\x8d\xe6\xa7\x98\xe3\x81\xbe\xe3\x81\xa7\xe3\x81\x8a\xe6\xb3\x8a\xe3\x82\x8a\xe3\x81\x84\xe3\x81\x9f\xe3\x81\xa0\xe3\x81\x91\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82\xe3\x81\xbe\xe3\x81\x9f\xe3\x80\x81\xe3\x82\xa8\xe3\x82\xb0\xe3\x82\xbc\xe3\x82\xaf\xe3\x83\x86\xe3\x82\xa3\xe3\x83\x96\xe3\x83\xab\xe3\x83\xbc\xe3\x83\xa0\xe3\x81\xae\xe3\x81\x8a\xe5\xae\xa2\xe6\xa7\x98\xe3\x81\xaf\xe3\x80\x81\xe3\x82\xa8\xe3\x82\xb0\xe3\x82\xbc\xe3\x82\xaf\xe3\x83\x86\xe3\x82\xa3\xe3\x83\x96\xe3\x83\xa9\xe3\x82\xa6\xe3\x83\xb3\xe3\x82\xb8\xe3\x82\x92\xe3\x81\x94\xe5\x88\xa9\xe7\x94\xa8\xe3\x81\x84\xe3\x81\x9f\xe3\x81\xa0\xe3\x81\x91\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82\xe4\xba\x8b\xe5\x89\x8d\xe3\x81\xab\xe3\x81\x94\xe4\xba\x88\xe7\xb4\x84\xe3\x81\x84\xe3\x81\x9f\xe3\x81\xa0\xe3\x81\x91\xe3\x82\x8b\xe3\x82\xbf\xe3\x82\xa4\xe3\x83\xa0\xe3\x83\x88\xe3\x82\xa5\xe3\x83\x95\xe3\x83\xa9\xe3\x82\xa4\xe3\x83\xbb\xe3\x83\x91\xe3\x83\x83\xe3\x82\xb1\xe3\x83\xbc\xe3\x82\xb8\xe3\x81\xab\xe3\x81\xaf\xe3\x80\x81\xe7\xa9\xba\xe6\xb8\xaf\xe3\x81\xae\xe9\xa7\x90\xe8\xbb\x8a\xe6\x96\x99\xe9\x87\x91\xe3\x81\x8c\xe5\x90\xab\xe3\x81\xbe\xe3\x82\x8c\xe3\x81\xa6\xe3\x81\x8a\xe3\x82\x8a\xe3\x81\xbe\xe3\x81\x99\xe3\x80\x82' c.setFont('HeiseiMin-W3', 12) jPara = Paragraph(gatwickText, jStyle) jPara.wrap(300, 200) jPara.drawOn(c, 100, 220) jPara = Paragraph(gatwickText2, jStyle) jPara.wrap(300, 200) jPara.drawOn(c, 100, 320) c.setFillColor(colors.purple) tx = c.beginText(100, 200) tx.setFont('Helvetica', 12) tx.textLines("""This document shows sample output in Japanese from the Reportlab PDF library. This page shows the two fonts available and tests our ability to measure the width of glyphs in both horizontal and vertical writing, with proportional and fixed-width characters. The red boxes should be the same width (or height) as the character strings they surround. The next pages show more samples and information. """) c.drawText(tx) c.setFont('Helvetica',10) c.drawCentredString(297, 36, 'Page %d' % c.getPageNumber()) c.showPage() c.setFont('Helvetica', 30) c.drawString(100,700, 'Japanese TrueType Font Support') msg = u'\u6771\u4EAC : Unicode font'.encode('utf8') msg2 = u'utf8 input 0123456789 ABCDEF'.encode('utf8') from reportlab.pdfbase.ttfonts import TTFont try: msmincho = TTFont('MS Mincho','msmincho.ttc',subfontIndex=0,asciiReadable=0) fn = ' file=msmincho.ttc subfont 0' except: try: msmincho = TTFont('MS Mincho','msmincho.ttf',asciiReadable=0) fn = 'file=msmincho.ttf' except: #Ubuntu - works on Lucid Lynx if xpdf-japanese installed try: msmincho = TTFont('MS Mincho','ttf-japanese-mincho.ttf') fn = 'file=msmincho.ttf' except: msmincho = None if msmincho is None: c.setFont('Helvetica', 12) c.drawString(100,600, 'Cannot find msmincho.ttf or msmincho.ttc') else: pdfmetrics.registerFont(msmincho) c.setFont('MS Mincho', 30) c.drawString(100,600, msg) c.drawString(100,570, msg2) c.drawString(100,540, fn) if fn.endswith('0'): try: msmincho1 = TTFont('MS Mincho 1','msmincho.ttc',subfontIndex=1,asciiPreload=0) pdfmetrics.registerFont(msmincho1) fn = ' file=msmincho.ttc subfont 1' c.setFont('MS Mincho 1',30) c.drawString(100,500,msg+fn) except: c.setFont('Helvetica',30) c.drawString(100,500,msg) c.drawString(100,470, msg2) c.drawString(100,440, fn) #test a paragraph with CJK and <br/> tags u = u'''<font color=red>\u30ac\u30c8\u30a6\u30a3\u30c3</font><br/><font color=blue>\u30af\u7a7a\u6e2f\u3068\u9023\u7d61\u901a</font><br/>\u8def\u3067\u76f4\u7d50\u3055\u308c\u3066\u3044\u308b\u552f<br/>\u4e00\u306e\u30db\u30c6\u30eb\u3067\u3042\u308b\u5f53\u30db\u30c6\u30eb\u306f\u3001\u8857\u306e\u4e2d\u5fc3\u90e8\u304b\u308930\u5206\u306e\u5834\u6240\u306b\u3054\u3056\u3044\u307e\u3059\u3002\u5168\u5ba2\u5ba4\u306b\u9ad8\u901f\u30a4\u30f3\u30bf\u30fc\u30cd\u30c3\u30c8<br/>\u74b0\u5883\u3092\u5b8c\u5099\u3057\u3066\u304a\u308a\u307e\u3059\u3002\u30d5\u30a1\u30df\u30ea\u30fc\u30eb\u30fc\u30e0\u306f5\u540d\u69d8\u307e\u3067\u304a\u6cca\u308a\u3044\u305f\u3060\u3051\u307e\u3059\u3002\u307e\u305f\u3001\u30a8\u30b0\u30bc\u30af\u30c6\u30a3\u30d6\u30eb\u30fc\u30e0\u306e\u304a\u5ba2\u69d8\u306f\u3001\u30a8\u30b0\u30bc\u30af\u30c6\u30a3\u30d6\u30e9\u30a6\u30f3\u30b8\u3092\u3054\u5229\u7528\u3044\u305f\u3060\u3051\u307e\u3059\u3002\u4e8b\u524d\u306b\u3054\u4e88\u7d04\u3044\u305f\u3060\u3051\u308b\u30bf\u30a4\u30e0\u30c8\u30a5\u30d5\u30e9\u30a4\u30fb\u30d1\u30c3\u30b1\u30fc\u30b8\u306b\u306f\u3001\u7a7a\u6e2f\u306e\u99d0\u8eca\u6599\u91d1\u304c\u542b\u307e\u308c\u3066\u304a\u308a\u307e\u3059\u3002''' jPara = Paragraph(u, jStyle) jPara.wrap(300, 500) jPara.drawOn(c, 100, 300) c.showPage() # realistic text sample ## sample = """Adobe Acrobat ##\x83h\x83L\x83\x85\x83\x81\x83\x93\x83g\x82\xaa\x8aJ\x82\xa9\x82\xc8\x82\xad\x82\xc4\x8d\xa2\x82\xc1\x82\xbd\x82\xb1\x82\xc6\x82\xcd ##\x82\xa0\x82\xe8\x82\xdc\x82\xb9\x82\xf1\x82\xa9\x81B\x8e\x96\x8b\xc6\x8cv\x89\xe6\x8f\x91\x81A\x89c\x8b\xc6\x83\x8c\x83|\x81[\x83g ##\x81A\x83J\x83^\x83\x8d\x83O\x82\xe2\x83p\x83\x93\x83t\x83\x8c\x83b\x83g\x82\xc8\x82\xc7\x90\xa7\x8d\xec\x95\xa8\x82\xcc\x8e\xed ##\x97\xde\x82\xc9\x82\xa9\x82\xa9\x82\xed\x82\xe7\x82\xb8\x81A ##\x83h\x83L\x83\x85\x83\x81\x83\x93\x83g\x82\xcdAdobe® Acrobat® 5.0\x82\xf0\x8eg\x82\xc1\x82\xc4Adobe PDF\x81iPortable Document ##Format\x81j\x83t\x83@\x83C\x83\x8b\x82\xc9\x95\xcf\x8a\xb7\x82\xb5\x82\xdc\x82\xb5\x82\xe5\x82\xa4\x81B\x96\xb3\x8f\x9e\x94z\x95z\x82\xcc ##Adobe Acrobat Reader\x82\xf0\x8eg\x82\xa6\x82\xce\x81A\x83n\x81[\x83h\x83E\x83F\x83A\x81A\x83\\\x83t\x83g\x83E\x83F\x83A\x82\xc9\x82\xa9 ##\x82\xa9\x82\xed\x82\xe7\x82\xb8\x81A\x92N\x82\xc5\x82\xe0\x82\xa0\x82\xc8\x82\xbd\x82\xcc\x83h\x83L\x83\x85\x83\x81\x83\x93\x83g\x82\xf0 ##\x83I\x83\x8a\x83W\x83i\x83\x8b\x82\xcc\x91\xcc\x8d\xd9\x82\xc5\x8aJ\x82\xad\x82\xb1\x82\xc6\x82\xaa\x82\xc5\x82\xab\x82\xdc\x82\xb7\x81B ##\x82\xa0\x82\xc8\x82\xbd\x82\xcc\x88\xd3\x90}\x82\xb5\x82\xbd\x82\xc6\x82\xa8\x82\xe8\x82\xc9\x8f\xee\x95\xf1\x82\xf0\x93`\x82\xa6\x82\xe9 ##\x82\xb1\x82\xc6\x82\xaa\x82\xc5\x82\xab\x82\xdc\x82\xb7\x81B ##\x82\xb3\x82\xe7\x82\xc9\x81AAdobe Acrobat 5.0\x82\xc5\x82\xcd\x81AWeb\x83u\x83\x89\x83E\x83U\x82\xa9\x82\xe7\x83R\x83\x81\x83\x93\x83g\x82\xe2 ##\x83}\x81[\x83N\x83A\x83b\x83v\x82\xf0\x8f\x91\x82\xab\x8d\x9e\x82\xf1\x82\xbe\x82\xe8\x81A\x93d\x8eq\x8f\x90\x96\xbc\x82\xf0\x8f\x91\x82\xab ##\x8d\x9e\x82\xdd\x81A\x8c\xb4\x96{\x82\xc6\x82\xb5\x82\xc4\x83\x8d\x81[\x83J\x83\x8b\x82\xc9\x95\xdb\x91\xb6\x82\xb7\x82\xe9\x82\xb1\x82\xc6\x82\xe0\x89\xc2\x94\\\x82\xc5\x82\xb7\x81B ##\x8a\xe9\x8b\xc6\x93\xe0\x82\xa0\x82\xe9\x82\xa2\x82\xcd\x8a\xe9\x8b\xc6\x82\xcc\x98g\x82\xf0\x92\xb4\x82\xa6\x82\xc4\x83`\x81[\x83\x80\x82\xc5 ##\x82\xcc\x83h\x83L\x83\x85\x83\x81\x83\x93\x83g\x83\x8f\x81[\x83N\x82\xcc\x90\xb6\x8eY\x90\xab\x82\xf0\x8c\xfc\x8f\xe3\x82\xb3\x82\xb9\x82\xe9\x82\xb1\x82\xc6\x82\xaa\x82\xc5\x82\xab\x82\xdc\x82\xb7\x81B ## ##Adobe Acrobat 5.0\x82\xc5\x8d\xec\x90\xac\x82\xb5\x82\xbdAdobe PDF\x82\xcd\x81A(Acrobat 5.0\x82\xc5\x82\xcc\x82\xdd\x83T\x83|\x81[\x83g ##\x82\xb5\x82\xc4\x82\xa2\x82\xe9\x88\xc3\x8d\x86\x89\xbb\x90\xdd\x92\xe8\x82\xf0\x8f\x9c\x82\xa2\x82\xc4\x82\xcd)\x8f]\x97\x88\x82\xdc ##\x82\xc5\x82\xcc\x83o\x81[\x83W\x83\x87\x83\x93(3\x82\xa8\x82\xe6\x82\xd1\x82S)\x82\xccAcrobat Reader\x82\xc5\x82\xe0\x8aJ\x82\xad ##\x82\xb1\x82\xc6\x82\xaa\x82\xc5\x82\xab\x82\xdc\x82\xb7\x81B\x8f\xee\x95\xf1\x8b\xa4\x97L\x82\xcc\x83c\x81[\x83\x8b\x82\xc6\x82\xb5 ##\x82\xc4\x81A\x82\xb3\x82\xe7\x82\xc9\x90i\x95\xe0\x82\xb5\x82\xbdAdobe Acrobat 5.0\x82\xf0\x81A\x8f]\x97\x88\x82\xcc\x8a\xc2\x8b\xab ##\x82\xc5\x82\xe0\x88\xc0\x90S\x82\xb5\x82\xc4\x82\xb2\x97\x98\x97p\x82\xa2\x82\xbd\x82\xbe\x82\xaf\x82\xdc\x82\xb7\x81B ## ##\x96{\x90\xbb\x95i\x82\xf0\x83l\x83b\x83g\x83\x8f\x81[\x83N\x82\xc8\x82\xc7\x82\xf0\x89\xee\x82\xb5\x82\xc4\x92\xbc\x90\xda\x82\xa0\x82\xe9 ##\x82\xa2\x82\xcd\x8a\xd4\x90\xda\x82\xc9\x95\xa1\x90\x94\x82\xcc\x92[\x96\x96\x82\xa9\x82\xe7\x8eg\x97p\x82\xb7\x82\xe9\x8f\xea\x8d\x87\x81A ##\x82\xbb\x82\xcc\x92[\x96\x96\x82\xc6\x93\xaf\x90\x94\x82\xcc\x83\x89\x83C\x83Z\x83\x93\x83X\x82\xf0\x82\xb2\x8dw\x93\xfc\x82\xad\x82\xbe ##\x82\xb3\x82\xa2\x81B\x96{\x90\xbb\x95i\x82\xcd\x83N\x83\x89\x83C\x83A\x83\x93\x83g\x97p\x83\\\x83t\x83g\x83E\x83F\x83A\x82\xc5\x82\xa0\x82\xe8 ##\x81A\x83T\x81[\x83o\x97p\x83\\\x83t\x83g\x83E\x83F\x83A\x82\xc6\x82\xb5\x82\xc4\x82\xa8\x8eg\x82\xa2\x82\xa2\x82\xbd\x82\xbe\x82\xad\x82\xb1\x82\xc6 ##\x82\xcd\x81A\x8f\xe3\x8bL\x95\xfb\x96@\x82\xc9\x82\xe6\x82\xe9\x88\xc8\x8aO\x81A\x8b\x96\x91\xf8\x82\xb3\x82\xea\x82\xc4\x82\xa2\x82\xdc\x82\xb9 ##\x82\xf1\x81B\x95\xa1\x90\x94\x82\xcc\x83\x89\x83C\x83Z\x83\x93\x83X\x82\xf0\x82\xb2\x8dw\x93\xfc\x82\xb3\x82\xea\x82\xe9\x8f\xea\x8d\x87\x82\xc9 ##\x82\xcd\x83\x89\x83C\x83Z\x83\x93\x83X\x83v\x83\x8d\x83O\x83\x89\x83\x80\x82\xf0\x82\xb2\x97\x98\x97p\x82\xc9\x82\xc8\x82\xe9\x82\xc6\x82\xa8\x93\xbe\x82\xc5\x82\xb7\x81B ## ## ##\x81y\x82\xa8\x92m\x82\xe7\x82\xb9\x81zMicrosoft Office XP\x82\xa9\x82\xe7PDF\x82\xf0\x8d\xec\x90\xac\x82\xb7\x82\xe9\x82\xc9\x82\xcd ##""" ## c.setFont('Helvetica', 24) ## c.drawString(100,750, "Sample text from Adobe's web site") ## tx = c.beginText(100,700) ## tx.setFont('Helvetica', 10) ## tx.textLine('Note: line wrapping has not been preserved and some lines may be wrapped in mid-word.') ## tx.textLine('We are just testing that we see Japanese and not random characters!') ## tx.setFont('HeiseiMin-W3-90ms-RKSJ-H',6) ## tx.textLines(sample) ## tx.setFont('Helvetica', 8) ## tx.textLine() ## tx.textLine() ## tx.textLines(""" ## This test document shows Japanese output from the Reportlab PDF Library. ## You may use two fonts, HeiseiMin-W3 and HeiseiKakuGo-W5, and a number of ## different encodings. ## ## The available encoding names (with comments from the PDF specification) are: ## encodings_jpn = [ ## # official encoding names, comments taken verbatim from PDF Spec ## '83pv-RKSJ-H', #Macintosh, JIS X 0208 character set with KanjiTalk6 ## #extensions, Shift-JIS encoding, Script Manager code 1 ## '90ms-RKSJ-H', #Microsoft Code Page 932 (lfCharSet 0x80), JIS X 0208 ## #character set with NEC and IBM extensions ## '90ms-RKSJ-V', #Vertical version of 90ms-RKSJ-H ## '90msp-RKSJ-H', #Same as 90ms-RKSJ-H, but replaces half-width Latin ## #characters with proportional forms ## '90msp-RKSJ-V', #Vertical version of 90msp-RKSJ-H ## '90pv-RKSJ-H', #Macintosh, JIS X 0208 character set with KanjiTalk7 ## #extensions, Shift-JIS encoding, Script Manager code 1 ## 'Add-RKSJ-H', #JIS X 0208 character set with Fujitsu FMR extensions, ## #Shift-JIS encoding ## 'Add-RKSJ-V', #Vertical version of Add-RKSJ-H ## 'EUC-H', #JIS X 0208 character set, EUC-JP encoding ## 'EUC-V', #Vertical version of EUC-H ## 'Ext-RKSJ-H', #JIS C 6226 (JIS78) character set with NEC extensions, ## #Shift-JIS encoding ## 'Ext-RKSJ-V', #Vertical version of Ext-RKSJ-H ## 'H', #JIS X 0208 character set, ISO-2022-JP encoding, ## 'V', #Vertical version of H ## 'UniJIS-UCS2-H', #Unicode (UCS-2) encoding for the Adobe-Japan1 character ## #collection ## 'UniJIS-UCS2-V', #Vertical version of UniJIS-UCS2-H ## 'UniJIS-UCS2-HW-H', #Same as UniJIS-UCS2-H, but replaces proportional Latin ## #characters with half-width forms ## 'UniJIS-UCS2-HW-V' #Vertical version of UniJIS-UCS2-HW-H ## ] ## ## The next few pages show the complete character set available in the encoding ## "90ms-RKSJ-H" - Shift-JIS with the standard Microsoft extensions. ## """) ## c.drawText(tx) ## ## c.setFont('Helvetica',10) ## c.drawCentredString(297, 36, 'Page %d' % c.getPageNumber()) ## ## ## ## c.showPage() from reportlab.lib import textsplit c.setFont('HeiseiMin-W3', 14) y = 700 c.drawString(70, y, 'cannot end line') y -= 20 for group in textsplit.CANNOT_START_LINE: c.drawString(70, y, group) y -= 20 c.setFont('Helvetica',10) c.drawString(70, y, ' '.join([ascii(x)[4:-1] for x in group])) c.setFont('HeiseiMin-W3', 14) y -= 20 y -= 20 c.drawString(70, y, 'cannot end line') y -= 20 for group in textsplit.CANNOT_END_LINE: c.drawString(70, y, group) y -= 20 c.setFont('Helvetica',10) c.drawString(70, y, ' '.join([ascii(x)[2:] for x in group])) c.setFont('HeiseiMin-W3', 14) y -= 20 c.showPage() #utf8 encoded paragraph sample2_uni = u'''\u30ac\u30c8\u30a6\u30a3\u30c3\u30af\u7a7a\u6e2f\u3068\u9023\u7d61\u901a \u8def\u3067\u76f4\u7d50\u3055\u308c\u3066\u3044\u308b\u552f\u4e00\u306e\u30db\u30c6\u30eb \u3067\u3042\u308b\u5f53\u30db\u30c6\u30eb\u306f\u3001\u8857\u306e\u4e2d\u5fc3\u90e8\u304b \u308930\u5206\u306e\u5834\u6240\u306b\u3054\u3056\u3044\u307e\u3059\u3002\u5168\u5ba2\u5ba4 \u306b\u9ad8\u901f\u30a4\u30f3\u30bf\u30fc\u30cd\u30c3\u30c8\u74b0\u5883\u3092\u5b8c\u5099 \u3057\u3066\u304a\u308a\u307e\u3059\u3002\u30d5\u30a1\u30df\u30ea\u30fc\u30eb\u30fc\u30e0 \u306f5\u540d\u69d8\u307e\u3067\u304a\u6cca\u308a\u3044\u305f\u3060\u3051\u307e\u3059\u3002 \u307e\u305f\u3001\u30a8\u30b0\u30bc\u30af\u30c6\u30a3\u30d6\u30eb\u30fc\u30e0\u306e\u304a \u5ba2\u69d8\u306f\u3001\u30a8\u30b0\u30bc\u30af\u30c6\u30a3\u30d6\u30e9\u30a6\u30f3\u30b8 \u3092\u3054\u5229\u7528\u3044\u305f\u3060\u3051\u307e\u3059\u3002\u4e8b\u524d\u306b\u3054 \u4e88\u7d04\u3044\u305f\u3060\u3051\u308b\u30bf\u30a4\u30e0\u30c8\u30a5\u30d5\u30e9\u30a4 \u30fb\u30d1\u30c3\u30b1\u30fc\u30b8\u306b\u306f\u3001\u7a7a\u6e2f\u306e\u99d0\u8eca\u6599 \u91d1\u304c\u542b\u307e\u308c\u3066\u304a\u308a\u307e\u3059\u3002''' oneline_uni = u''.join(sample2_uni.split()) sample2_utf8 = oneline_uni.encode('utf8') from reportlab.platypus import Paragraph from reportlab.lib.styles import ParagraphStyle jsty = ParagraphStyle('japanese',fontName='HeiseiMin-W3', wordWrap='CJK') jpara = Paragraph(oneline_uni, style=jsty) c.drawString(100, 710, 'Try to wrap a paragraph using a style with wordWrap="CJK"') w, h = jpara.wrap(400,400) jpara.drawOn(c, 100, 700 - h) #now try to split it... c.drawString(100, 510, 'Now try to split a paragraph as if over a page break') topPara, bottomPara = jpara.split(400, 30) w1, h1 = topPara.wrap(400, 30) topPara.drawOn(c, 100, 450) w2, h2 = bottomPara.wrap(400, 30) bottomPara.drawOn(c, 100, 400) #print 'split into heights %0.2f, %0.2f' % (topPara.height, bottomPara.height) ## c.showPage() ## ## ## # full kuten chart in EUC ## c.setFont('Helvetica', 24) ## c.drawString(72,750, 'Characters available in JIS 0208-1997') ## y = 600 ## for row in range(1, 95): ## KutenRowCodeChart(row, 'HeiseiMin-W3','EUC-H').drawOn(c, 72, y) ## y = y - 125 ## if y < 50: ## c.setFont('Helvetica',10) ## c.drawCentredString(297, 36, 'Page %d' % c.getPageNumber()) ## c.showPage() ## y = 700 ## ## c.showPage() #try with Unicode truetype - Mincho for starters ## import time ## started = time.clock() ## c.showPage() ## c.setFont('Helvetica',16) ## c.drawString(100,750, 'About to say Tokyo in MS Gothic...') ## ## from reportlab.pdfbase.ttfonts import TTFont, TTFontFile ## f = TTFontFile("msgothic.ttf") ## print f.name ## ## pdfmetrics.registerFont(TTFont(f.name, f)) ## ## utfText = u'Andr\202'.encode('utf8') ## c.setFont(f.name,16) ## c.drawString(100,700, utfText) ## ## ## #tokyoUCS2 = '\x67\x71\x4E\xAC' ## finished = time.clock() c.save() if VERBOSE: print('saved test_multibyte_jpn.pdf')
class Report(object): render = {'table': render.TableRender, 'pie': render.PieRender, 'histo': render.HistoRender, 'line': render.LineRender, 'gantt': render.GanttRender, } margin = 30 big_title_height = 40 title_height = 50 frame_margin = 5 frag_title_height = 20 frag_margin = 9 edenwall_height = 60 def __init__(self, title, enterprise, interval, logo): self.title = title self.enterprise = enterprise self.interval = interval self.logo = logo self.width, self.height = A4 self.buf = StringIO() self.canvas = Canvas(self.buf, pagesize=A4) self.page_title = '' self.page_rows = [] self.page_frags = 0 self.page_num = 1 # Build story. self.canvas.saveState() self.canvas.setStrokeColor(colors.RED) self.canvas.setLineWidth(2) self.canvas.roundRect(self.margin, self.edenwall_height + self.margin, self.width, self.height, 20, stroke=1, fill=0) self.canvas.setFillColor(colors.GREEN2) self.canvas.setStrokeColor(colors.GREEN1) self.canvas.roundRect(- self.margin, - self.margin, self.width - self.margin, self.edenwall_height + self.margin, 20, stroke=1, fill=1) # TODO do not hardcode this values. img = Image('/var/lib/ufwi_rpcd/edenwall.png', 1209 / (300/(self.edenwall_height-self.margin/2)), self.edenwall_height-self.margin/2) img.drawOn(self.canvas, self.margin, self.margin/4) self.canvas.restoreState() if self.logo: img = Image(StringIO(self.logo)) img._setup_inner() img.drawOn(self.canvas, (self.width - self.margin)/2 - img.drawWidth/2, 2*self.height/3) offset = 40 self.canvas.setFillColor(black) self.canvas.setFont("Helvetica-Bold", self.big_title_height) self.canvas.drawCentredString((self.width-self.margin)/2, self.height/3, title) self.canvas.setFont("Helvetica-Bold", self.frag_title_height) self.canvas.drawString(offset, self.height - offset, enterprise) def __getstate__(self): d = self.__dict__.copy() del d['canvas'] return d def __setstate__(self, d): self.__dict__ = d self.canvas = Canvas(self.buf, pagesize=A4) def build(self): self.canvas.showPage() self.canvas.save() return self.buf def addGraph(self, title, columns, table, render): frags = self.page_frags for row, cols in enumerate(self.page_rows): frags -= cols if frags < 0: break if frags >= 0: self.addPage(self.page_title, self.page_rows) col = 0 row = 0 cols = self.page_rows[0] else: col = - frags - 1 # You can read that? Not me. x = self.margin + self.frame_margin + (col+1) * self.frag_margin + \ col * (self.width - 2*self.margin - 2*self.frame_margin - (col+1)*self.frag_margin) / cols y = self.margin + self.frame_margin + (row+1) * self.frag_margin + \ row * (self.height - 2*self.margin - 2*self.frame_margin - self.title_height - 2*self.frag_margin) / len(self.page_rows) width = (self.width - 2*self.margin - 2*self.frame_margin - 2*cols*self.frag_margin) / cols height = (self.height - 2*self.margin - 2*self.frame_margin - self.title_height - 2*len(self.page_rows)*self.frag_margin) / len(self.page_rows) self.canvas.setFillColor(colors.GREEN1) self.canvas.roundRect(x, y, width, height, 7, stroke=0, fill=1) self.canvas.setFillColor(white) x += 1 y += 1 width -= 2 height -= 2 self.canvas.roundRect(x, y, width, height - self.frag_title_height, 7, stroke=0, fill=1) self.canvas.setFillColor(white) self.canvas.setFont("Helvetica", 3*self.frag_title_height/4) self.canvas.drawCentredString(x + width/ 2, y + height - 3*self.frag_title_height/4, title) self.page_frags += 1 if len(table) > 0: klass = self.render[render] obj = klass(width, height - self.frag_title_height - 2*self.frame_margin, columns, table) r = obj.render() if isinstance(r, Drawing): renderPDF.draw(obj.render(), self.canvas, x, y + self.frame_margin) elif isinstance(r, Flowable): r.drawOn(self.canvas, x, y + height - self.frag_title_height - obj.height - self.frame_margin) else: pass #self.append(Paragraph(title, h2)) #self.append(Paragraph('No data', h2)) #self.append(KeepTogether([Paragraph(title, h2), # Paragraph('No data', h2)])) def addPage(self, title, rows=[1]): self.canvas.showPage() self.canvas.saveState() self.canvas.setLineWidth(2) self.canvas.setStrokeColor(colors.RED) self.canvas.roundRect(self.margin, self.margin, self.width - self.margin*2, self.height - self.margin*2, 20, stroke=1, fill=0) self.canvas.restoreState() self.canvas.setFillColor(colors.GREEN1) self.canvas.setFont("Helvetica-Bold", self.title_height/3) self.canvas.drawString(self.margin*2, self.height - self.margin - 4*self.title_height/5, title) self.canvas.setFont("Helvetica-Bold", self.title_height/3) self.canvas.drawRightString(self.width - self.margin*2, self.height - self.margin - 4*self.title_height/5, self.interval) self.page_num += 1 self.canvas.setFont("Helvetica-Bold", 12) self.canvas.drawCentredString(self.width/2, 0, "Page %d" % self.page_num) self.page_title = title self.page_rows = rows self.page_frags = 0
def draw_label(self, c: Canvas, col: int, row: int, redemption_code: str): x = self.left_margin + (col + 0.5) * self.label_width + col * self.inner_margin y = self.page_height - self.top_margin - (row + 0.5) * self.label_height # Drawing label bounds helps when adjusting layout. Not for production. # self.draw_label_bounds(c, x, y) c.setFont("Courier-Bold", 13) c.drawString(x - 80, y + 14, redemption_code) c.setFont("Helvetica", 10) # Space to enter redemption month and day. p = c.beginPath() p.moveTo(x + 20, y + 12) p.lineTo(x + 45, y + 12) p.moveTo(x + 55, y + 12) p.lineTo(x + 80, y + 12) p.close() c.drawPath(p) c.drawCentredString(x + 15, y + 16, 'm:') c.drawCentredString(x + 50, y + 16, 'd:') # Space to enter redeemer's email address. p = c.beginPath() p.moveTo(x - 80, y - 14) p.lineTo(x + 80, y - 14) p.close() c.drawPath(p) c.drawCentredString(x, y - 24, 'email address')