def create_first_page(): TOP = (29.7 - 5) * cm LEFT = 4 * cm RIGHT = (21 - 4) * cm FONT_SIZE = 10 FONT = "Plex" text = "PyJournal year 2020" image_path = "logo.png" # text right font = FONT font_size = FONT_SIZE canvas = Canvas("first_page.pdf", pagesize=A4) canvas.setFont(font, font_size) canvas.setFillColor(black) text_width = pdfmetrics.stringWidth(text, font, font_size) text_height = int(FONT_SIZE * 1.2) # TODO not correct canvas.drawString(RIGHT - text_width, TOP - text_height, text) # logo img = utils.ImageReader(image_path) img_width, img_height = img.getSize() aspect = img_height / float(img_width) display_width = 100 display_height = (display_width * aspect) canvas.drawImage(image_path, LEFT, TOP - display_height, width=display_width, height=display_height, mask="auto") canvas.save()
def ccPDFmake(frontFile, backFile, saveFile, text): canvas = Canvas(saveFile) front = utils.ImageReader(frontFile) back = utils.ImageReader(backFile) canvas.drawImage(front, FRONT_X, FRONT_Y, width=CC_WIDTH, height=CC_HEIGHT, mask='auto') canvas.drawImage(back, BACK_X, BACK_Y, width=CC_WIDTH, height=CC_HEIGHT, mask='auto') if text != "": canvas.saveState() canvas.rotate(55) canvas.setFillColorRGB(.6, .6, .6) canvas.setFont("Times-Roman", 30) canvas.drawString(10 * CM, 0.2 * CM, text) canvas.restoreState() canvas.save() return True
def export_pdf(playground, default_dpi, savefile=False): """Create a searchable PDF from a pile of HOCR + JPEG""" images = sorted(glob.glob(os.path.join(playground, '*.jpg'))) if len(images) == 0: print( "WARNING: No JPG images found in the folder", playground, "\nScript cannot proceed without them and will terminate now.\n") sys.exit(0) load_invisible_font() pdf = Canvas(savefile if savefile else StdoutWrapper(), pageCompression=1) pdf.setCreator('hocr-tools') pdf.setTitle(os.path.basename(playground)) dpi = default_dpi for image in images: im = Image.open(image) w, h = im.size try: dpi = im.info['dpi'][0] except KeyError: pass width = w * 72 / dpi height = h * 72 / dpi pdf.setPageSize((width, height)) pdf.drawImage(image, 0, 0, width=width, height=height) add_text_layer(pdf, image, height, dpi) pdf.showPage() pdf.save()
def export_pdf(playground, default_dpi): """Create a searchable PDF from a pile of HOCR + JPEG""" load_invisible_font() pdf = Canvas(StdoutWrapper(), pageCompression=1) pdf.setCreator('hocr-tools') pdf.setTitle(os.path.basename(playground)) images = glob.glob(os.path.join(playground, '*.png')) + glob.glob( os.path.join(playground, '*.jpg')) images = sorted(images, key=os.path.getmtime) dpi = default_dpi for image in images: im = Image.open(image) w, h = im.size try: dpi = im.info['dpi'][0] except KeyError: pass # width = w * 72 / dpi # height = h * 72 / dpi width, height = w, h # ignore DPIs pdf.setPageSize((width, height)) pdf.drawImage(image, 0, 0, width=width, height=height) add_text_layer(pdf, image, height, dpi) pdf.showPage() pdf.save()
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
def make_data_layer(profile, trip): canvas = Canvas(tempfile.TemporaryFile()) canvas.setFont("Helvetica", 11) canvas.drawString(144, 705, "%s %s" % (profile.firstname, profile.lastname)) canvas.drawString(144, 684, profile.birthday) canvas.drawString(310, 684, profile.placeofbirth) canvas.drawString( 144, 665, "%s %s %s" % (profile.address, profile.zipcode, profile.city)) canvas.drawString(72, 109, f'Fait à {profile.city}') canvas.drawString(72, 93, f'Le {trip.date.strftime("%d/%m/%Y")}') canvas.drawString(310, 93, f'à {trip.date.strftime("%H:%M")}') canvas.setFont("Helvetica", 12) for reason in trip.reasons: canvas.drawString(73, reason.value.get('y'), "x") qr_path = qr.generateQR(profile, trip) canvas.drawImage(qr_path, canvas._pagesize[0] - 107, 80, 82, 82) canvas.showPage() canvas.drawImage(qr_path, 50, canvas._pagesize[1] - 390, 300, 300) if os.path.exists(qr_path): os.remove(qr_path) stream = io.BytesIO() stream.write(canvas.getpdfdata()) stream.seek(0) return stream
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 title_pdf(string_data, nz, sr, vz, ct, filepatch): """сохранение в PDF формате титульной страницы""" canvas = Canvas("Title.pdf", pagesize=A4) if filepatch == None: canvas.setFont("DejaVuSerif-Italic", 14) canvas.drawString(5 * cm, 28 * cm, "Федерация настольного тенниса России") canvas.drawString(3 * cm, 27 * cm, "Федерация настольного тенниса Нижегородской области") canvas.setFont("DejaVuSerif-Italic", 20) canvas.drawString(2 * cm, 23 * cm, nz) canvas.setFont("DejaVuSerif-Italic", 16) canvas.drawString(2.5 * cm, 22 * cm, f"среди {sr} {vz}") canvas.setFont("DejaVuSerif-Italic", 14) canvas.drawString(5.5 * cm, 5 * cm, f"г. {ct} Нижегородская область") canvas.drawString(7.5 * cm, 4 * cm, string_data) else: canvas.drawImage(filepatch, 7 * cm, 12 * cm, 6.9 * cm, 4.9 * cm, mask=[0, 2, 0, 2, 0, 2]) # делает фон прозрачным canvas.setFont("DejaVuSerif-Italic", 14) canvas.drawString(5 * cm, 28 * cm, "Федерация настольного тенниса России") canvas.drawString(3 * cm, 27 * cm, "Федерация настольного тенниса Нижегородской области") canvas.setFont("DejaVuSerif-Italic", 20) canvas.drawString(2 * cm, 23 * cm, nz) canvas.setFont("DejaVuSerif-Italic", 16) canvas.drawString(2.5 * cm, 22 * cm, f"среди {sr} {vz}") canvas.setFont("DejaVuSerif-Italic", 14) canvas.drawString(5.5 * cm, 5 * cm, f"г. {ct} Нижегородская область") canvas.drawString(7.5 * cm, 4 * cm, string_data) canvas.save()
def export_pdf(playground, default_dpi, savefile=False): images = sorted(glob.glob(os.path.join(playground, '*.tiff'))) if len(images) == 0: print("WARNING: No images found in the folder") sys.exit(0) load_invisible_font() pdf = Canvas(savefile, pageCompression=1) pdf.setCreator('hocr-tools') pdf.setTitle(os.path.basename(playground)) dpi = default_dpi for image in images: im = Image.open(image) w, h = im.size try: dpi = im.info['dpi'][0] except KeyError: pass width = (w * 72 / dpi) height = (h * 72 / dpi) pdf.setPageSize((width, height)) pdf.drawImage(image, 0, 0, width=width, height=height) add_text_layer(pdf, image, height, dpi) pdf.showPage() pdf.save()
def edit_pdf(filePath): input_file = filePath output_file = filePath # Get pages reader = PdfReader(input_file) pages = [pagexobj(p) for p in reader.pages] # Compose new pdf canvas = Canvas(output_file) for page_num, page in enumerate(pages, start=1): # Add page canvas.setPageSize((page.BBox[2], page.BBox[3])) canvas.doForm(makerl(canvas, page)) # Draw header header_text = "Jhon institute" x = 180 canvas.saveState() canvas.setStrokeColorRGB(0, 0, 0) canvas.drawImage('input_logo.jpg', height=60, width=110,x=60, y=700) canvas.setFont('Times-Roman', 14) canvas.drawString(page.BBox[2] -x, 730, header_text) # Draw footer footer_text = "It’s easy to play any musical instrument: all you have to do is touch the right key at " \ "the right time and the instrument will play itself." x = 70 canvas.setStrokeColorRGB(0, 0, 0) canvas.setLineWidth(0.5) canvas.setFont('Times-Roman', 10) canvas.drawString(page.BBox[1] +x, 30, footer_text) canvas.restoreState() canvas.showPage() canvas.save()
def download_manka(dic, db): page = 0 match_obj = re.match(f'(.*)(\..*)', dic['img_url']) head = match_obj.group(1) tail = match_obj.group(2) c = None if dic['img_url'] != str.strip(dic['img_url']): print('NOT EQ') exit(0) c = Canvas(dic['name'] + '.pdf') try: while True: page += 1 print(f'Downloading Page{page}') image = ImageReader(f'{head}{page:d}{tail}') c.setPageSize(image.getSize()) c.drawImage(image, 0, 0, mask='auto') c.showPage() except OSError: if page == 1: return 0 pass page -= 1 if c: c.save() print('Done') return page
class pdf: def __init__(self, name, logo): self.text = None self.name = name self.canvas = Canvas(self.name + ".pdf") self.logo = logo from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont pdfmetrics.registerFont(TTFont('times', 'times.ttf')) pdfmetrics.registerFont(TTFont('timesb', 'timesbd.ttf')) if self.logo == "logo.png": self.canvas.drawImage(self.logo, 50, 700, mask="auto") def write_string(self, txt, x, y, font, size): self.canvas.setFont(font, size) self.canvas.drawString(x, y, txt) def write_text(self, txt, x, y, font, size): self.canvas.setFont(font, size) self.text = self.canvas.beginText(x, y) self.text.setFont(font, size) self.text.textLines(txt) self.canvas.drawText(self.text) def save(self): self.canvas.save()
def generate_pg1(self, report: canvas.Canvas) -> None: report.drawImage(plot_overall_return(self.returns, self.m_tick, False), 15, 400, 600, 300) main_text = portfolio_model.get_main_text(self.returns) reportlab_helpers.draw_paragraph(report, main_text, 30, 410, 550, 200) current_return = self.returns["return"][-1] beta = self.betas["total"][-1] market_return = self.returns[("Market", "Return")][-1] sharpe = f"{(current_return - self.rf)/ np.std(self.returns['return']):.2f}" treynor = f"{(current_return - self.rf)/ beta:.2f}" if beta > 0 else "N/A" alpha = f"{current_return - (self.rf + beta * (market_return - self.rf)):.2f}" information = ( f"{float(alpha)/ (np.std(self.returns['return'] - market_return)):.2f}" ) perf = [ ["Sharpe", sharpe], ["Treynor", treynor], ["Alpha", alpha], ["Information", information], ] reportlab_helpers.draw_table(report, "Performance", 540, 300, 30, perf) reportlab_helpers.draw_paragraph(report, portfolio_model.performance_text, 140, 290, 460, 200) report.showPage()
def test_single_page_image(): filename = os.path.join(TEST_OUTPUT, 'image-mono.pdf') pdf = Canvas(filename, pagesize=(72, 72)) with NamedTemporaryFile() as im_tmp: im = Image.new('1', (8, 8), 0) for n in range(8): im.putpixel((n, n), 1) im.save(im_tmp.name, format='PNG') # Draw image in a 72x72 pt or 1"x1" area pdf.drawImage(im_tmp.name, 0, 0, width=72, height=72) pdf.showPage() pdf.save() pdfinfo = pageinfo.pdf_get_all_pageinfo(filename) assert len(pdfinfo) == 1 page = pdfinfo[0] assert not page['has_text'] assert len(page['images']) == 1 pdfimage = page['images'][0] assert pdfimage['width'] == 8 # assert pdfimage['color'] == 'gray' # While unexpected, this is correct # PDF spec says /FlateDecode image must have /BitsPerComponent 8 # So mono images get upgraded to 8-bit assert pdfimage['bpc'] == 8 # DPI in a 1"x1" is the image width assert pdfimage['dpi_w'] == 8 assert pdfimage['dpi_h'] == 8
def export_pdf(images, hocrs, title="", default_dpi=300): """Create a searchable PDF from a pile of HOCR + JPEG""" load_invisible_font() pdf = Canvas(StdoutWrapper(), pageCompression=1) pdf.setCreator('ScanIt Cloud OCR') pdf.setTitle(title) dpi = default_dpi for i, image in enumerate(images): hocr = hocrs[i] w, h = image.size try: dpi = image.info['dpi'][0] except KeyError: pass width = w * 72 / dpi height = h * 72 / dpi pdf.setPageSize((width, height)) reportlab_pil_img = ImageReader(image) pdf.drawImage(reportlab_pil_img, 0, 0, width=width, height=height) add_text_layer(pdf, image, hocr, height, dpi) pdf.showPage() return pdf.getpdfdata()
def pdf(self): stream = BytesIO() pdf = Canvas(stream) pdf.drawImage(ImageReader(self.img), *self.dimensions) pdf.save() return PdfFileReader(stream).getPage(0)
def pdf_view(request, ticket_code): try: ticket = Ticket.objects.get(code=ticket_code) booking = ticket.booking except ObjectDoesNotExist: return render(request, 'booking/invalid_ticket_code.html') response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="ticket.pdf"' from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont pdfmetrics.registerFont(TTFont('ComicBd', 'booking/templates/booking/comicbd.ttf')) p = Canvas(response, pagesize=(260*mm, 150*mm), pageCompression=1) image_path = 'booking/templates/booking/ticket.png' image = ImageReader(image_path) p.drawImage(image, 0, 0, 260*mm, 150*mm, mask='auto') p.setFont('ComicBd', 20) p.drawString(70*mm, 90*mm, '{},'.format(booking.last_name)) p.drawString(70*mm, 80*mm, booking.first_name) p.drawString(165*mm, 90*mm, '{}'.format(booking.performance.title)) p.drawString(165*mm, 80*mm, booking.performance.start_date) p.drawString(165*mm, 70*mm, booking.performance.start_time) p.setFont('Times-Bold', 24) p.drawString(192*mm, 18*mm, ticket.code) if apps.get_app_config('booking').use_qr_codes: # Create QRcode qr_code = qr.QRCode( version=1, error_correction=qr.ERROR_CORRECT_L, box_size=3, border=4 ) verification_url = 'http://{}{}'.format( request.get_host(), reverse('booking:verify', args=(ticket_code,)) ) qr_code.add_data(verification_url) img = qr_code.make_image(fill_color="black", back_color="white") raw_img = BytesIO() img.save(raw_img, format='PNG') p.drawImage(ImageReader(raw_img), 210*mm, 35*mm, mask='auto') p.showPage() p.save() return response
def process_pdf(self, image_data, hocr_data, pdf_filename): """Utility function if you'd rather get the PDF data back instead of save it automatically.""" pdf = Canvas(pdf_filename, pageCompression=1) pdf.setCreator('hocr-tools') pdf.setPageSize((self.width, self.height)) pdf.drawImage(image_data, 0, 0, width=self.width, height=self.height) pdf = self.add_text_layer(pdf, hocr_data) pdf_data = pdf.getpdfdata() return pdf_data
def do(self, name: str, hocr_list: list, images: list) -> str: """ Cria um pdf searchable combinando imagens com hocr """ pdf_path = self.searchable_path + name + "_searchable.pdf" pdf = Canvas(pdf_path) pdf.setCreator('TotOcr') pdf.setTitle(name) dpi = 300 p1 = re.compile(r'bbox((\s+\d+){4})') p2 = re.compile(r'baseline((\s+[\d\.\-]+){2})') for img_path, hocr in zip(images, hocr_list): img = Image.open(img_path) w, h = img.size width = w * 72 / dpi height = h * 72 / dpi pdf.setPageSize((width, height)) pdf.drawImage(img_path, 0, 0, width=width, height=height) hocr_et = etree.fromstring(hocr) img.close() #Draw a text layer for OCR data for line in hocr_et.xpath('//*[@class="ocr_line"]'): linebox = p1.search(line.attrib['title']).group(1).split() try: baseline = p2.search(line.attrib['title']).group(1).split() except AttributeError: baseline = [0, 0] linebox = [float(i) for i in linebox] baseline = [float(i) for i in baseline] xpath_elements = './/*[@class="ocrx_word"]' if (not (line.xpath('boolean(' + xpath_elements + ')'))): # if there are no words elements present, # we switch to lines as elements xpath_elements = '.' for word in line.xpath(xpath_elements): rawtext = word.text.strip() if rawtext == '': continue font_width = pdf.stringWidth(rawtext, 'invisible', 8) if font_width <= 0: continue box = p1.search(word.attrib['title']).group(1).split() box = [float(i) for i in box] b = (((box[0] + box[2]) / 2 - linebox[0]) * baseline[0] + baseline[1]) + linebox[3] text = pdf.beginText() text.setTextRenderMode(3) # double invisible text.setFont('invisible', 8) text.setTextOrigin(box[0] * 72 / dpi, height - b * 72 / dpi) box_width = (box[2] - box[0]) * 72 / dpi text.setHorizScale(100.0 * box_width / font_width) text.textLine(rawtext) pdf.drawText(text) pdf.showPage() pdf.save() return pdf_path
def overlay_hocr(self, dpi, hocr_filename): hocr_dir, hocr_basename = os.path.split(hocr_filename) logging.debug("hocr_filename:%s, hocr_dir:%s, hocr_basename:%s" % (hocr_filename, hocr_dir, hocr_basename)) basename = hocr_basename.split('.')[0] pdf_filename = os.path.join("%s_ocr.pdf" % (basename)) # Switch to the hocr directory to make this easier cwd = os.getcwd() if hocr_dir != "": os.chdir(hocr_dir) with open(pdf_filename, "wb") as f: logging.info("Overlaying hocr and creating final %s" % pdf_filename) pdf = Canvas(f, pageCompression=1) pdf.setCreator('pyocr') pdf.setTitle(os.path.basename(hocr_filename)) logging.info("Analyzing OCR and applying text to PDF...") pdf.setPageCompression(1) logging.info("Searching for %s" % ("%s*.jpg" % basename)) for jpg_file in glob.glob("%s*.jpg" % basename): jpg = Image.open(jpg_file) w,h = jpg.size dpi_jpg = jpg.info['dpi'] width = w*72.0/dpi_jpg[0] height = h*72.0/dpi_jpg[1] del jpg pdf.setPageSize((width,height)) logging.info("Adding page image %s" % jpg_file) logging.info("Page width=%f, height=%f" % (width, height)) pdf.drawImage(jpg_file,0,0, width=width, height=height) # Get the page number pg_num = int(jpg_file.split(basename)[1].split('.')[0]) logging.info("Adding text to page %d" % pg_num) self.add_text_layer(pdf, hocr_basename,pg_num,height,dpi) pdf.showPage() os.remove(jpg_file) pdf.save() logging.info("Created OCR'ed pdf as %s" % (pdf_filename)) # Now we have to fix up stuff on windows because of reportlab # adding \r\r\n on each line (instead of \r\n) f = open(pdf_filename, "rb") s = str(f.read()) f.close() #s = s.replace('\r\r\n', '\r\n') #s = re.sub("\r\r\n", "\r\n", s) #f = open(pdf_filename, "wb") #f.write(s) #f.close() os.chdir(cwd) return os.path.join(hocr_dir,pdf_filename)
def _add_image(self, source, x, y): if 'redactor/' not in source: source = 'redactor/' + source document = BytesIO() canvas = Canvas(document, pagesize=self.page_size) canvas.setFillColorRGB(1, 1, 1) canvas.drawImage(source, x, y, mask='auto') canvas.save() self.pdf.getPage(0).mergePage( PdfFileReader(BytesIO(document.getvalue())).getPage(0))
def generate_pdf(chapter_name, images, out_file_path): canvas = Canvas(out_file_path) canvas.setTitle(chapter_name) for img_url in images: print 'downloading image: ', img_url image = ImageReader(img_url) canvas.setPageSize(image.getSize()) canvas.drawImage(image, x=0, y=0) canvas.showPage() canvas.save()
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 toutesReservations(self): # Lister les réservations effectuées par chaque client req ="SELECT titre, nom, e_mail, COUNT(place) FROM spectacles "\ "LEFT JOIN reservations USING(ref_spt) "\ "LEFT JOIN clients USING (ref_cli) "\ "GROUP BY nom, titre "\ "ORDER BY titre, nom" res =BD.executerReq(req) # Construction d'un tableau html pour lister les infos trouvées : tabl ='<table border="1" cellpadding="5">\n' tabs ="" for n in range(4): tabs +="<td>{{{0}}}</td>".format(n) ligneTableau ="<tr>" +tabs +"</tr>\n" # La première ligne du tableau contient les en-têtes de colonnes : tabl += ligneTableau.\ format("Titre", "Nom du client", "Courriel", "Places réservées") # Lignes suivantes : for tit, nom, mail, pla in res: tabl += ligneTableau.format(tit, nom, mail, pla) tabl +="</table>" # ======= Construction du document PDF correspondant : ======= # D'après le fichier de configuration tutoriel.conf, les documents # "statiques" doivent se trouver dans le sous-répertoire "annexes" # pour être accessibles depuis l'application web (mesure de sécurité) : fichier ="annexes/reservations.pdf" can = Canvas("%s" % (fichier), pagesize=A4) largeurP, hauteurP = A4 # largeur et hauteur de la page # Dessin du logo (aligné par son coin inférieur gauche) : can.drawImage("annexes/python.gif", 1*cm, hauteurP-6*cm, mask="auto") can.setFont("Times-BoldItalic", 28) can.drawString(6*cm, hauteurP-6*cm, "Grand théâtre de Python city") # Tableau des réservations : posY =hauteurP-9*cm # position verticale de départ tabs =(1*cm, 7*cm, 11*cm, 16.5*cm) # tabulations head =("Titre", "Nom du client", "Courriel", "Places réservées") # En-têtes du tableau : can.setFont("Times-Bold", 14) t =0 for txt in head: can.drawString(tabs[t], posY, head[t]) t +=1 # Lignes du tableau : posY -=.5*cm can.setFont("Times-Roman", 14) for tupl in res: posY, t = posY-15, 0 for champ in tupl: can.drawString(tabs[t], posY, str(champ)) # (Les valeurs numériques doivent être converties en chaînes !) t +=1 can.save() # Finalisation du PDF return mep(Glob.html["toutesReservations"].format(tabl, fichier))
def add(fbid, image): global c if c is None: c=Canvas('file.pdf') c.drawImage(image, 0,0, width=500,height=600) c.showPage() c.save() post_fb_url = "https://graph.facebook.com/v2.6/me/messages?access_token=%s"%PAGE_ACCESS_TOKEN response_msg = json.dumps({"recipient":{"id":fbid}, "message":{"text": 'Image Added Successfully' }}) status2 = requests.post(post_fb_url, headers={"Content-Type": "application/json"},data=response_msg) print status2.json()
def _save_pdf(self): """ Output the current document to a PDF file using ReportLab. """ save_model = self.application.get_save_model() save_view = self.application.get_save_view() document_model = self.application.get_document_model() # TODO: seperate saving code into its own thread? # Setup output pdf pdf = PdfCanvas(save_model.filename) pdf.setTitle(save_model.title) pdf.setAuthor(save_model.author) pdf.setKeywords(save_model.keywords) # Generate pages page_iter = document_model.get_iter_first() while page_iter: current_page = document_model.get_value(page_iter, 0) # Write transformed image temp_file_path = ''.join([tempfile.mktemp(), '.bmp']) current_page.pil_image.save(temp_file_path) assert os.path.exists(temp_file_path), \ 'Temporary bitmap file was not created by PIL.' size = constants.PAGESIZES_INCHES[current_page.page_size] pdf_width = size[0] * points_per_inch pdf_height = size[1] * points_per_inch # Swizzle width and height if the page has been rotated on its side if abs(current_page.rotation) % 180 == 90: pdf_width, pdf_height = pdf_height, pdf_width pdf.setPageSize((pdf_width, pdf_height)) pdf.drawImage( temp_file_path, 0, 0, width=pdf_width, height=pdf_height, preserveAspectRatio=True) pdf.showPage() os.remove(temp_file_path) page_iter = document_model.iter_next(page_iter) # Save complete PDF pdf.save() assert os.path.exists(save_model.filename), \ 'Final PDF file was not created by ReportLab.' document_model.clear()
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')
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 pdf(files, outfile, useportrait=True): print("Creating PDF...") pdf = Canvas(outfile) pagesize = portrait(A4) if useportrait else landscape(A4) for i in files: print("Creating PDF page for %s..." % i) pdf.setPageSize(pagesize) pdf.drawImage(i, 0, 0, *pagesize) pdf.showPage() print("Done!") print("Saving PDF...") pdf.save() print("Done!")
def paint_original_segments(fnames, transcriptions, page): pdf_fname = 'tmp/search_{0}.pdf'.format(page) pdf = Canvas(pdf_fname, pagesize=A4) top = A4[1] for fname, transcription in itertools.izip(fnames, transcriptions): segment = Image.open(fname) width, height = segment.size p = Paragraph(transcription, ParagraphStyle('Normal', alignment=TA_CENTER)) p.wrapOn(pdf, A4[0] - PARA_PADDING * 2, height) p.drawOn(pdf, PARA_PADDING, top - height / 2) pdf.drawImage(fname, 0, top - height) top -= height pdf.save() return pdf_fname
def export_pdf(imgname, default_dpi, outfile): """Trim the image and creates a PDF with the same size.""" if outfile == '': outfile = '%s.pdf' % (imgname) pdf = Canvas(outfile, pageCompression=1) dpi = default_dpi im = Image.open(imgname) w, h = im.size width = round(w * 72.0 / dpi, 3) height = round(h * 72.0 / dpi, 3) pdf.setPageSize((width, height)) pdf.drawImage(imgname, 0, 0, width, height, mask=None) pdf.showPage() pdf.save()
def testUseA85(self): '''test for bitbucket PR #59 by Vytis Banaitis''' from reportlab import rl_config from reportlab.pdfgen.canvas import Canvas old = rl_config.useA85 try: for v in 1, 0: rl_config.useA85 = v c = Canvas('test_useA85%s.pdf' % v) c.drawImage('test-rgba.png', 0,0) c.showPage() c.save() finally: rl_config.useA85 = old
def _draw_long_label(canvas: Canvas, sample_name, sample_creator, sample_creation_date, sample_id, ghs_classes, qrcode_uri, left_offset, bottom_offset, minimum_width=0, include_qrcode=False, qrcode_size=15 * mm): font_name = "Helvetica" font_size = 8 canvas.setFont(font_name, font_size) num_lines = 2 if include_qrcode: upper_line_text1 = sample_name upper_line_text2 = " • #{}".format(sample_id) middle_line_text = sample_creator lower_line_text = sample_creation_date num_lines = 3 else: upper_line_text1 = sample_name upper_line_text2 = " • #{}".format(sample_id) middle_line_text = sample_creator + " • " + sample_creation_date lower_line_text = '' min_height = 9 * mm if include_qrcode: min_height = max(min_height, qrcode_size - 2 * mm) padding = max(1 * mm, (min_height - num_lines * font_size) / 2) height = max(min_height, 2 * padding + num_lines * font_size) left_cursor = left_offset + 1 * mm canvas.setFont(font_name + '-Bold', font_size) canvas.drawString(left_cursor, bottom_offset + padding + (num_lines - 1) * font_size * 1.2, upper_line_text1) canvas.setFont(font_name, font_size) canvas.drawString(left_cursor + canvas.stringWidth(upper_line_text1, font_name + '-Bold', font_size), bottom_offset + padding + (num_lines - 1) * font_size * 1.2, upper_line_text2) canvas.drawString(left_cursor, bottom_offset + padding + (num_lines - 2) * font_size * 1.2, middle_line_text) if num_lines == 3: canvas.drawString(left_cursor, bottom_offset + padding, lower_line_text) text_width = max( canvas.stringWidth(upper_line_text1, font_name + '-Bold', font_size) + canvas.stringWidth(upper_line_text2, font_name, font_size), canvas.stringWidth(middle_line_text, font_name, font_size), canvas.stringWidth(lower_line_text, font_name, font_size) ) left_cursor += 1 * mm + text_width for ghs_class in ghs_classes: canvas.drawImage(GHS_IMAGE_URIS[ghs_class], left_cursor, bottom_offset + height / 2 - 4.5 * mm, 9 * mm, 9 * mm, (255, 255, 255, 255, 255, 255)) left_cursor += 9 * mm if height != 9 * mm: left_cursor += 1 * mm if include_qrcode: canvas.drawImage(qrcode_uri, left_cursor - 1 * mm, bottom_offset + height / 2 - qrcode_size / 2, qrcode_size, qrcode_size) left_cursor += qrcode_size - 2 * mm width = left_cursor - left_offset if width < minimum_width: width = minimum_width canvas.rect(left_offset, bottom_offset, width, height, 1) return bottom_offset
def _draw_poweredby(self, canvas: Canvas, op: OrderPosition, o: dict): content = o.get('content', 'dark') img = finders.find('pretixpresale/pdf/powered_by_pretix_{}.png'.format(content)) ir = ThumbnailingImageReader(img) try: width, height = ir.resize(None, float(o['size']) * mm, 300) except: logger.exception("Can not resize image") pass canvas.drawImage(ir, float(o['left']) * mm, float(o['bottom']) * mm, width=width, height=height, preserveAspectRatio=True, anchor='n', mask='auto')
def paint_original_segments(fnames, transcriptions, page): page_file = NamedTemporaryFile(suffix='.pdf', dir=path.abspath('./tmp/'), delete=False) pdf = Canvas(page_file.name, pagesize=A4) page_width, top = A4 for fname, transcription in itertools.izip(fnames, transcriptions): segment = Image.open(fname) width, height = segment.size p = Paragraph(transcription, ParagraphStyle('Normal', alignment=TA_CENTER)) p.wrapOn(pdf, page_width - PARA_PADDING * 2, height) p.drawOn(pdf, PARA_PADDING, top - height / 2) pdf.drawImage(fname, 0, top - height) top -= height pdf.save() page_file.close() return page_file.name
def make_pdf(deck_name): global successful_images global prog_bar global mutex c = Canvas(f'{deck_name}.pdf', pagesize=LEGAL) num_pages = ceil(len(successful_images) / 9) if num_pages <= 0: num_pages = 1 for current_page in range(num_pages): if current_page != num_pages: num_items = len(successful_images[(current_page * 9):((current_page + 1) * 9)]) else: num_items = len(successful_images[current_page * 9:]) for i in range(num_items): if i in [0, 3, 6]: x_align = 0.25 elif i in [1, 4, 7]: x_align = 3 else: x_align = 5.75 if i in [0, 1, 2]: y_align = 0.25 elif i in [3, 4, 5]: y_align = 4 else: y_align = 7.75 img_name = successful_images[i + (current_page * 9)] c.drawImage(img_name, x_align * inch, y_align * inch, width=2.5 * inch, height=3.48 * inch) # To explain: # Downloading the images is 50% of the work because our "max" is 2* number of images, # therefore we need to figure out how much of the overall "max" value our pages take up # we do this by taking half the max value i.e., 50% and then adding the ammount equivalent to # half of the percentage of the pages we are done with mutex.acquire() additional_percent = (current_page / num_pages) / 2 new_value = floor((prog_bar.maxval / 2) + (additional_percent * prog_bar.maxval)) prog_bar.update(new_value) mutex.release() c.showPage() c.save()
def get_image_page(image): inch = 72 bio = BytesIO() c = Canvas(bio, pagesize=(8.5*inch, 11*inch)) dim = c.drawImage(image, 0.5*inch, 6.3*inch, 495, 290) # print(dim) c.save() return PdfFileReader(bio).getPage(0)
def _draw_poweredby(self, canvas: Canvas, op: OrderPosition, o: dict): content = o.get('content', 'dark') if content not in ('dark', 'white'): content = 'dark' img = finders.find('pretixpresale/pdf/powered_by_pretix_{}.png'.format(content)) ir = ThumbnailingImageReader(img) try: width, height = ir.resize(None, float(o['size']) * mm, 300) except: logger.exception("Can not resize image") pass canvas.drawImage(ir, float(o['left']) * mm, float(o['bottom']) * mm, width=width, height=height, preserveAspectRatio=True, anchor='n', mask='auto')
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()
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 test(self): import os c = Canvas(filename, invariant=1, pageCompression=0) c.setFont('Helvetica-Bold', 36) c.drawString(100,700, 'Hello World') gif = os.path.join(os.path.dirname(unittest.__file__),'pythonpowered.gif') c.drawImage(gif,100,600) c.save() raw1 = open(filename, 'rb').read() c = Canvas(filename, invariant=1, pageCompression=0) c.setFont('Helvetica-Bold', 36) c.drawString(100,700, 'Hello World') c.drawImage(gif,100,600) c.save() raw2 = open(filename, 'rb').read() assert raw1 == raw2, 'repeated runs differ!'
def test(self): import os from reportlab.lib.testutils import testsFolder c = Canvas(filename, invariant=1, pageCompression=0) c.setFont('Helvetica-Bold', 36) c.drawString(100,700, 'Hello World') gif = os.path.join(testsFolder,'pythonpowered.gif') c.drawImage(gif,100,600) c.save() raw1 = open(filename, 'rb').read() c = Canvas(filename, invariant=1, pageCompression=0) c.setFont('Helvetica-Bold', 36) c.drawString(100,700, 'Hello World') c.drawImage(gif,100,600) c.save() raw2 = open(filename, 'rb').read() assert raw1 == raw2, 'repeated runs differ!'
def run(self): try: filename = self.filename + '.pdf' if os.path.exists(filename): raise Exception('File already exists') canvas = Canvas(filename, pageCompression=1) canvas.setCreator('Scanvark') canvas.setTitle('Scanned document') i = 0 count = len(self.pages) for i, page in enumerate(self.pages): self._progress_callback(self, i, count) w, h = [a * 72 / page.resolution for a in page.size] canvas.setPageSize((w, h)) reader = ImageReader(page.open_jpeg()) canvas.drawImage(reader, 0, 0, width=w, height=h) canvas.showPage() self._progress_callback(self, i, count) canvas.save() except Exception, e: self._error_callback(self, str(e))
def generate__a4_pdf_from_images_list(pdf_name="ss.pdf", images_filenames_list=[], card_size_mm = 80, card_boarder_mm = 5, pack_name = "SplendidSomething", creator="bmsleight", images_per_card = 3, word_list = [], image_zip_name = "", source_of_images = ""): pdf = Canvas(pdf_name) titlePage(pdf, pack_name, creator, images_per_card, word_list, image_zip_name, source_of_images) page_x = 210 page_y = 297 total_card_size_mm = card_size_mm + card_boarder_mm*2 cards_x = int(page_x / total_card_size_mm) page_margin_x = (page_x-(cards_x*total_card_size_mm))/2 cards_y = int(page_y / total_card_size_mm) page_margin_y = (page_y-(cards_y*total_card_size_mm))/2 index_images = 0 for pages in range(0, int(1+(len(images_filenames_list)/(cards_x*cards_y)) ) ): draw_grid_lines(pdf, total_card_size_mm, page_x, page_y, cards_x, page_margin_x, cards_y, page_margin_y) for x in range(0,cards_x): for y in range(0,cards_y): if index_images < len(images_filenames_list): x_pos = page_margin_x + (x * total_card_size_mm) + card_boarder_mm y_pos = page_margin_y + (y * total_card_size_mm) + card_boarder_mm pdf.drawImage(images_filenames_list[index_images], x_pos*mm, y_pos*mm, width=card_size_mm*mm, height=card_size_mm*mm, mask='auto') index_images = index_images + 1 simple_text_wrap(pdf, 5*mm, "<link href='http://SplendidSnap.com' color='blue'>Created at http://SplendidSnap.com</link>") pdf.showPage() # Backing tf = tempfile.NamedTemporaryFile(delete=False, suffix="ssc.png") with Image(width=300, height=300) as img: font = Font(path="/usr/share/fonts/truetype/freefont/LiberationMono-Bold.ttf", color=Color('NavyBlue')) img.caption('Splendid\nSnap\n.com', font=font, gravity='center') img.save(filename=tf.name) draw_grid_lines(pdf, total_card_size_mm, page_x, page_y, cards_x, page_margin_x, cards_y, page_margin_y) for x in range(0,cards_x): for y in range(0,cards_y): x_pos = page_margin_x + (x * total_card_size_mm) + card_boarder_mm y_pos = page_margin_y + (y * total_card_size_mm) + card_boarder_mm pdf.drawImage(tf.name, x_pos*mm, y_pos*mm, width=card_size_mm*mm, height=card_size_mm*mm, mask='auto') pdf.showPage() pdf.save()
def get_pages(self, start=1, end=100): raw_images = [] for i in range(start, end): request = self.get_page(i) if request.status_code == 404: break raw_images.append(request.content) if raw_images: # Create canvas in memory canvas_data = BytesIO() canvas = Canvas(canvas_data) # Iterate through URLs and add image data to PDF canvas for raw_img in raw_images: canvas.drawImage(ImageReader(BytesIO(raw_img)), 0, 0, 8.5 * inch, 11 * inch) canvas.showPage() canvas.save() return canvas_data
class Sla2Pdf_ng(object): """ sla to pdf format translation """ def __init__(self, document, pdfFolder, version, tablesProperties, pgObjList, numPages, iteratableGroups): """ Build a template object based on the specified file-like object and sequence of objects """ self.pdfFolder = pdfFolder self.pdfFileName = '_temp' self.version = version self.tablesProperties = tablesProperties self.document = document self.pageObjects = self.document.findall('PAGEOBJECT') self.pgObjList = pgObjList self.numPages = numPages self.iteratableGroups = iteratableGroups self.translate() def translate(self): self.pageProperties = Sla2pdfUtils.pageProFunc(self.document) self.canvas = Canvas(filename = self.pdfFolder + self.pdfFileName + '.pdf', pagesize=(self.pageProperties[0][8],self.pageProperties[0][7])) # Page's table reiter = False self.pdfPage = 0 for e in xrange(0, self.numPages): self.pdfPage = e for group in self.tablesProperties: self.group = group.keys()[0] self.tablesPropertie = group.values()[0] try: self.group= self.group.strip().split('%%%')[0] except: self.group= self.group.strip() if self.group in self.iteratableGroups: colu = int(self.tablesPropertie['columns']) self.tablesPropertie['iterproper'] = self.tablesPropertie['parasobj'][colu:(colu*2)] reiter = True cells = int(self.tablesPropertie['cells']) # Closing pages (elements of the same page must be near) if "noGroup" in self.group and self.tablesPropertie["pfile"] != "" : #print "IMMAGINEEEEEEEEEEEEEEE", self.group, self.tablesPropertie["isTableItem"] self.drawImage(group=self.group) # IMMAGINE elif "noGroup" in self.group and self.tablesPropertie["pfile"] == "": #print "MONOCELLAAAAAAA", self.group, self.tablesPropertie self.drawTable(group =self.group, monocell=True)# MONOCELLA else: # print "TABELLAAAAAAAA", self.group, self.tablesPropertie["isTableItem"] self.drawTable(group =self.group, reiter = reiter) # TABELLA self.canvas.saveState() self.canvas.showPage() self.canvas.save() def drawImage(self,group): """ Drawing an image """ pfile = self.tablesPropertie['pfile'] (imgPath, imgFile) = os.path.split(pfile) #innerIterator = self.iterator width = self.tablesPropertie['widths'][0] height = self.tablesPropertie['heights'][0] xPos = self.tablesPropertie['xpos'][0] yPos = self.tablesPropertie['ypos'][0] img = utils.ImageReader(Environment.imagesDir + imgFile) self.canvas.drawImage(img, xPos - self.pageProperties[self.pdfPage][9], self.pageProperties[0][7] - yPos - height + self.pageProperties[self.pdfPage][10], width=width, height=height) self.canvas.saveState() def drawTable(self, group=None, monocell=None, reiter = None): """ Drawing a table """ matrix = [] lst = [] matrix2 = [] vector = [] # Total of element's table cells = int(self.tablesPropertie['cells']) columns = int(self.tablesPropertie['columns']) rows = int(self.tablesPropertie['rows']) widths = self.tablesPropertie['widths'] heights = self.tablesPropertie['heights'] xpos = self.tablesPropertie['xpos'] ypos = self.tablesPropertie['ypos'] # print "DATI", cells, columns, rows, group, heights, widths contColumns = 0 ch = '' col = 0 cycle = False vector = [] alignment= None itexts = self.tablesPropertie['itextsobj'] paras = self.tablesPropertie['parasobj'] stile = TableStyle([]) stile.add('VALIGN',(0,0),(-1,-1),'TOP') tblprop = self.tablesPropertie['cellProperties'] if monocell==True: cells = 1 columns=1 rows = 1 for v in xrange(0,cells): if v == 0: contRows = 0 contColumns = 0 elif columns==1: contColumns = -1 contRows= int(v/columns) else: contRows= int(v/columns) contColumns = ((v)%columns) background = self.backgroundFunc(tblprop[v])# Finding background hexBorderColor = self.hexBorderColorFunc(tblprop[v]['borderColor']) stile.add('ROWBACKGROUNDS', (contColumns,contRows), (contColumns,contRows), (background, background)) cellpr = tblprop[v] cellpict = cellpr['cellPicture'] cellIMGHeight = cellpr['cellHeight'] cellIMGWidth = cellpr['cellWidth'] if (cellpr['bottomLine'] == 1 and cellpr['topLine'] == 1 and\ cellpr['leftLine'] == 1 and cellpr['rightLine'] == 1): stile.add('BOX', (contColumns,contRows), (contColumns,contRows), cellpr['lineWidth'], hexBorderColor) else: if cellpr['bottomLine'] == 1: stile.add('LINEBELOW', (contColumns,contRows), (contColumns,contRows), cellpr['lineWidth'], hexBorderColor) elif cellpr['topLine'] == 1: stile.add('LINEABOVE', (contColumns,contRows), (contColumns,contRows), cellpr['lineWidth'], hexBorderColor) if cellpr['leftLine'] == 1: stile.add('LINEBEFORE', (contColumns,contRows), (contColumns,contRows), cellpr['lineWidth'], hexBorderColor) if cellpr['rightLine'] == 1: stile.add('LINEAFTER', (contColumns,contRows), (contColumns,contRows), cellpr['lineWidth'], hexBorderColor) if not monocell: ch = self.chFunc(itexts[v])[0] itext = self.chFunc(itexts[v])[1] else: try: itext = itexts[0] ch = itexts[0].get('CH') except: itext = None ch = "" # self.chFunc(itexts[0])[1] actualPageObject = self.tablesPropertie# Borders uff = self.tablesPropertie['iterproper'] if uff != [] and v > columns: pdfAlignment = self.alignmentFunc(self.tablesPropertie['iterproper'][contColumns],v, reiter=True) else: pdfAlignment = self.alignmentFunc(paras, v, monocell) #alignment stile.add('ALIGN', (contColumns,contRows), (contColumns,contRows), pdfAlignment) if itext != None: fontName = self.fontNameFunc(itext) # Font name stile.add('FONT', (contColumns,contRows), (contColumns,contRows), fontName) fontSize = self.fontSizeFunc(itext)# Font size stile.add('FONTSIZE', (contColumns,contRows), (contColumns,contRows), fontSize) foreground = self.foregroundFunc(itext) #foreground stile.add('TEXTCOLOR', (contColumns,contRows), (contColumns,contRows), foreground) if "bcview" in ch: alignment="LEFT" vector.append(Sla2pdfUtils.createbarcode(ch)) else: vector.append(Sla2pdfUtils.makeParagraphs(ch, background, foreground, alignment, fontName, fontSize)) elif cellpict: (imgPath, imgFile) = os.path.split(cellpict) path = Environment.imagesDir + imgFile widthIMG = (float(cellIMGHeight)-2)*100/(float(cellIMGWidth)-2) img = Image(path,width=widthIMG,height=float(cellIMGHeight)-2) vector.append(img) else: vector.append('') if monocell==True: cycle= True elif ((v+1)%columns) == 0: contRows = 0 cycle= True if cycle == True: matrix.append(vector) vector = [] cycle = False # if columns > 1 and not reiter: # #wid = [] # hei = [] # for h in range(0,len(heights),rows): # hei.append(heights[h]) # heights = hei table=Table(matrix,style=stile, colWidths=widths[:columns], rowHeights=heights[:rows]) lst.append(table) # Effective table size sumRows = Sla2pdfUtils.sumRowsFunc(heights,rows) sumColumns = Sla2pdfUtils.sumColumnsFunc(widths,columns) f = Frame(x1=(xpos[0] - self.pageProperties[self.pdfPage][9]), y1=(self.pageProperties[self.pdfPage][7] - ypos[0] - sumRows + self.pageProperties[self.pdfPage][10] - 12), width=sumColumns, height=(sumRows+12), showBoundary=0) sumRows = sumColumns = 0 f.addFromList(lst, self.canvas) reiter = False #self.canvas.saveState() # ATTENZIONE !!! this part above is for generic function. def fontSizeFunc(self, itext): fontSize = "0" # Font size if self.version: try: fontSize = float(itext.get('FONTSIZE')) except: pass else: fontSize = float(itext.get('CSIZE')) if fontSize =="0": CHARSTYLE = self.document.findall('CHARSTYLE')[0] fontSize = float(CHARSTYLE.get('FONTSIZE')) #fontSize = "8" return fontSize def fontNameFunc(self, itext, monocell=False): if self.version: fontName = Sla2pdfUtils.getPdfFontName(str(itext.get('FONT'))) else: fontName = Sla2pdfUtils.getPdfFontName(str(itext.get('CFONT'))) return fontName def alignmentFunc(self,paras, v, monocell=False, reiter=False): if monocell==True: slaAlignment = paras[0].get('ALIGN') elif reiter ==True: slaAlignment = paras[0].get('ALIGN') else: slaAlignment = paras[v][0].get('ALIGN') if slaAlignment == None: slaAlignment = self.slaStyleDefault() pdfAlignment= Sla2pdfUtils.alignment(slaAlignment) return pdfAlignment def hexBorderColorFunc(self, borderColor): hexBorderColor = ColorDicTFull.colorDict[str(borderColor)][1] return hexBorderColor def foregroundFunc(self, itext): if self.version: textColor = itext.get('FCOLOR') else: textColor = itext.get('CCOLOR') foreground = colors.HexColor(ColorDicTFull.colorDict[str(textColor)][1]) return foreground def backgroundFunc(self, pageObject): cellProperties = pageObject if cellProperties['cellBackground'] == str("None"): sfondo = "White" else: sfondo = cellProperties['cellBackground'] background = colors.HexColor(ColorDicTFull.colorDict[str(sfondo)][1]) return background def chFunc(self, text): itexts = text ch = '' if len(itexts)>=1: if len(itexts)>1: for itext in itexts: chtmp = itext.get('CH') ch = ch +" "+ chtmp itext = itexts[0] else: itext = itexts[0] ch = itext.get('CH') else: itext = None return [ch, itext] def slaStyleDefault(self): styleTag = self.document.findall('STYLE')[0] styleDefault = styleTag.get('ALIGN') return styleDefault
smaller = min(lines) gap = larger - smaller frame = plt.gca() for xlabel_i in frame.axes.get_xticklabels(): xlabel_i.set_visible(False) plt.ylabel('Current Installs') plt.xlabel(format_date(dates[0]) + " to " + format_date(dates[-1])) plt.plot(range(days), lines, 'g-') plt.axis([0, days - 1, smaller - gap, larger]) image_name = proj_name + ".png" plt.savefig(image_name) image = ImageReader(image_name) pdf_file.drawImage(image, 90 * mm, 170 * mm, 110 * mm, 80 * mm) #----------------------------------------------------------------------- csv_file_name = set_csv_filename(sys.argv[1], "os_version") convert_to_utf8(csv_file_name) with open(csv_file_name, 'rb') as weeklyreport: filereader = csv.reader(weeklyreport, delimiter=',', quotechar='"') first_line = filereader.next() lines = get_latest_rows(filereader) insert_line("Installs by Android Version", 0, 16) for line in lines: insert_line(line[2], 20) for i in range (3,10):
if verbose: print "%s: bl (%d,%d), tr (%d,%d), size (%d,%d), dpi (%g,%g)" % ( image["filename"], image["x"], image["y"], image["x"]+image["w"], image["y"]+image["h"], image["w"], image["h"], image["pw"] * 72.0 / image["w"], image["ph"] * 72.0 / image["h"], ) # Rotate. rotates = [ lambda x,y,w,h: (x,y,w,h), # no rotation lambda x,y,w,h: (y, -x-w, h, w), # anticlockwise lambda x,y,w,h: (-x-w, -y-h, w, h), # 180 lambda x,y,w,h: (-y-h, x, h, w), # clockwise ] image["x"], image["y"], image["w"], image["h"] = ( rotates[angle](image["x"], image["y"], image["w"], image["h"]) ) # And draw the image. pdf.saveState() pdf.rotate(angle * 90) pdf.drawImage(img, image["x"], image["y"], image["w"], image["h"]) pdf.restoreState() pdf.showPage() pdf.save()
def formboleto(response,sacado,endereco,endereco1,valor,vencimento_date,nossonumero,observacao2): #temporarios #nossonumero = '99999998' #valor = '1,00' vencimento = vencimento_date.strftime('%d/%m/%Y') v = valor.replace(',','') fator = diff_date(vencimento_date) linhadigitavel = mount_line(banco,'9',carteira,agencia,nossonumero,fator,v) nossonumero += '-'+str(calc_our_number(ag+conta+carteira+nossonumero)) boleto=Canvas(response) # Logomarca da empresa boleto.drawImage(image=MEDIA_URL+'/alagoasdigital/logos/empresa.jpg', x=7*mm, y=280*mm, width=30*mm, height=11*mm) boleto.setStrokeColor(colors.black) boleto.setLineWidth(0.1) boleto.setFont('Helvetica-Bold',14) global localpagamento, usobanco if banco=='237': # bradesco boleto.drawImage(image=MEDIA_URL+'/alagoasdigital/logos/bancobradesco.jpg',x=160*mm, y=280*mm, width=25*mm, height=8*mm) # imagem do recido do sacado boleto.drawImage(image=MEDIA_URL+'/alagoasdigital/logos/bancobradesco.jpg',x=7*mm, y=229*mm, width=25*mm, height=8*mm) # imagem do banco na ficha de compensação boleto.drawImage(image=MEDIA_URL+'/alagoasdigital/logos/bancobradesco.jpg',x=7*mm, y=112*mm, width=25*mm, height=8*mm) # codigo do banco boleto.drawString(43*mm, 229*mm, '237-9') boleto.drawString(43*mm, 112*mm, '237-9') localpagamento+='Banco BRADESCO S/A' usobanco='269' #LINHADIGITAVEL='2379.264712 90600.000336 23007.514005 5 33070000011402' #CODIGOBARRA='23795330700000114022647190600000332300751400' elif banco=='422': # safra boleto.drawImage(image=MEDIA_URL+'/alagoasdigital/logos/bancosafra.jpg',x=160*mm, y=275*mm, width=32*mm, height=7*mm) # imagem do recido do sacado boleto.drawImage(image=MEDIA_URL+'/alagoasdigital/logos/bancosafra.jpg',x=7*mm, y=229*mm, width=30*mm, height=6*mm) # imagem do banco na ficha de compensação boleto.drawImage(image=MEDIA_URL+'/alagoasdigital/logos/bancosafra.jpg',x=7*mm, y=112*mm, width=30*mm, height=6*mm) # codigo do banco boleto.drawString(43*mm, 229*mm, '422-7') boleto.drawString(43*mm, 112*mm, '422-7') localpagamento+='Banco SAFRA' elif banco=='341': # itau boleto.drawImage(image=MEDIA_URL+'/alagoasdigital/logos/bancoitau.jpg',x=160*mm, y=275*mm, width=32*mm, height=7*mm) # imagem do recido do sacado boleto.drawImage(image=MEDIA_URL+'/alagoasdigital/logos/bancoitau.jpg',x=7*mm, y=229*mm, width=30*mm, height=6*mm) # imagem do banco na ficha de compensação boleto.drawImage(image=MEDIA_URL+'/alagoasdigital/logos/bancoitau.jpg',x=7*mm, y=112*mm, width=30*mm, height=6*mm) # codigo do banco boleto.drawString(43*mm, 229*mm, '341-7') boleto.drawString(43*mm, 112*mm, '341-7') #localpagamento+='Banco ITAU' else: # banco do brasil para default # imagem do canhoto boleto.drawImage(image=MEDIA_URL+'/alagoasdigital/logos/bancodobrasil.jpg',x=160*mm, y=280*mm, width=30*mm, height=5*mm) # imagem do recido do sacado boleto.drawImage(image=MEDIA_URL+'/alagoasdigital/logos/bancodobrasil.jpg',x=7*mm, y=229*mm, width=30*mm, height=5*mm) # imagem do banco na ficha de compensação boleto.drawImage(image=MEDIA_URL+'/alagoasdigital/logos/bancodobrasil.jpg',x=7*mm, y=112*mm, width=30*mm, height=5*mm) # codigo do banco boleto.drawString(43*mm, 229*mm, '001-9') boleto.drawString(43*mm, 112*mm, '001-9') localpagamento+='Banco do BRASIL S/A' # telefone da empresa boleto.setFont('Helvetica-Bold', 12) boleto.drawString(7*mm, 275*mm, telefone_empresa) ############### #RETICULAS DO VENCIMENTO E DO VALOR # (NÃO RETIRAR DAQUI SENÃO SOBREPORÁ O VALOR E O VENCIMENTO) # Recibo do sacado # retícula com cinza (Vencimento) boleto.setFillColor(colors.lightgrey) boleto.setStrokeColor(colors.white) boleto.rect(158*mm, 220*mm, 42*mm, 8*mm, stroke=1, fill=1) # retícula com cinza (Valor do documento) boleto.rect(158*mm, 196*mm, 42*mm, 8*mm, stroke=1, fill=1) # Ficha de compensação # retícula com cinza (Vencimento) boleto.setFillColor(colors.lightgrey) boleto.setStrokeColor(colors.lightgrey) boleto.rect(158*mm, 103*mm, 42*mm, 8*mm, stroke=1, fill=1) # retícula com cinza (Valor do documento) boleto.rect(158*mm, 79*mm, 42*mm, 8*mm, stroke=1, fill=1) # Término das retículas cinza ################ boleto.setStrokeColor(colors.black) boleto.setFillColor(colors.black) # Recibo de entrega boleto.setFont(FONTE_FORM, FONTE_FORM_TAM) boleto.drawString(7*mm, 270*mm, 'Sacado:') boleto.drawString(7*mm, 266*mm, 'Endereço:') boleto.drawString(7*mm, 258*mm, 'Documento:') boleto.drawString(7*mm, 254*mm, 'Emissão:') boleto.drawString(7*mm, 250*mm, 'Data:') boleto.drawString(80*mm, 258*mm, 'Valor:') boleto.drawString(80*mm, 254*mm, 'Vencimento:') boleto.drawString(80*mm, 250*mm, 'Assinatura: _______________________________') boleto.drawString(7*mm, 217*mm, 'Data do documento') boleto.drawString(41*mm, 217*mm, 'No. do documento') boleto.drawString(71*mm, 217*mm, 'Espécie doc') boleto.drawString(91*mm, 217*mm, 'Aceite') boleto.drawString(114*mm, 217*mm, 'Data do processamento') boleto.drawString(160*mm, 217*mm, 'Agência/Código do cedente') boleto.drawString(7*mm, 209*mm, 'Uso do banco') boleto.drawString(7*mm, 201*mm, 'Instruções (Todas informações deste BOLETO são de exclusiva responsabilidade do cedente)') boleto.drawString(7*mm, 225*mm, 'Cedente') boleto.drawString(160*mm, 225*mm, 'Vencimento') boleto.drawString(41*mm, 209*mm, 'Carteira') boleto.drawString(56*mm, 209*mm, 'Espécie') boleto.drawString(71*mm, 209*mm, 'Quantidade') boleto.drawString(71*mm, 205*mm, '') boleto.drawString(123*mm, 206*mm, 'x') boleto.drawString(124*mm, 209*mm, 'Valor') boleto.drawString(124*mm, 205*mm, '') boleto.drawString(160*mm, 209*mm, 'Nosso número') boleto.drawString(160*mm, 201*mm, '(=) Valor do documento') boleto.drawString(160*mm, 193*mm, '(-) Desconto/Abatimento') boleto.drawString(160*mm, 185*mm, '(-) Outras deduções') boleto.drawString(160*mm, 177*mm, '(+) Mora/Multa') boleto.drawString(160*mm, 169*mm, '(+) Outros acréscimos') boleto.drawString(160*mm, 161*mm, '(=) Valor cobrado') boleto.drawString(7*mm, 154*mm, 'Sacado') boleto.drawString(7*mm, 140*mm, 'Sacador/avalista') boleto.drawString(135*mm, 140*mm, 'Código de baixa') boleto.drawString(161*mm, 134*mm, 'Autenticação mecânica') boleto.setFont(FONTE_DADOS, FONTE_DADOS_TAM) boleto.drawString(20*mm, 270*mm, sacado) boleto.drawString(20*mm, 266*mm, endereco) boleto.drawString(20*mm, 262*mm, endereco1) boleto.drawString(20*mm, 258*mm, documento) boleto.drawString(20*mm, 254*mm, emissao) boleto.drawString(96*mm, 258*mm, valor) boleto.drawString(96*mm, 254*mm, vencimento) boleto.drawString(7*mm, 221*mm, cedente) boleto.drawString(180*mm, 221*mm, vencimento) boleto.drawString(7*mm, 213*mm, emissao) boleto.drawString(41*mm, 213*mm, documento) boleto.drawString(71*mm, 213*mm, especiedoc) boleto.drawString(91*mm, 213*mm, aceite) boleto.drawString(114*mm, 213*mm, emissao) boleto.drawString(160*mm, 213*mm, agencia) boleto.drawString(7*mm, 205*mm, usobanco) boleto.drawString(41*mm, 205*mm, carteira) boleto.drawString(56*mm, 205*mm, especiemon) boleto.drawString(160*mm, 189*mm, '') boleto.drawString(160*mm, 205*mm, nossonumero) boleto.drawString(7*mm, 197*mm, valorexpresso) boleto.drawString(177*mm, 197*mm, valor) boleto.drawString(20*mm, 185*mm, juros) boleto.drawString(160*mm, 181*mm, '') boleto.drawString(7*mm, 177*mm, observacao1) boleto.drawString(7*mm, 171*mm, observacao2) boleto.drawString(7*mm, 164*mm, observacao3) boleto.drawString(160*mm, 173*mm, '') boleto.drawString(160*mm, 165*mm, '') boleto.drawString(160*mm, 157*mm, '') boleto.drawString(7*mm, 151*mm, sacado) boleto.drawString(7*mm, 147*mm, endereco) boleto.drawString(7*mm, 144*mm, endereco1) # linha dividindo o canhoto boleto.setStrokeColor(colors.gray) boleto.line(0, 240*mm, 210*mm, 240*mm) # linha dividindo o recibo do sacado e ficha de compensação boleto.line(0, 122*mm, 210*mm, 122*mm) boleto.setStrokeColor(colors.black) boleto.setFillColor(colors.black) # abaixo da logo do banco boleto.line(7*mm, 228*mm, 200*mm, 228*mm) # separadores cedente, data do documento e uso do banco boleto.line(7*mm, 220*mm, 200*mm, 220*mm) boleto.line(7*mm, 212*mm, 200*mm, 212*mm) boleto.line(7*mm, 204*mm, 200*mm, 204*mm) # separador do número do banco boleto.line(42*mm, 228*mm, 42*mm, 234*mm) boleto.line(56*mm, 228*mm, 56*mm, 234*mm) # separador coluna cedente e vencimento boleto.line(158*mm, 228*mm, 158*mm, 156*mm) # separadores do bloco acima boleto.line(40*mm, 204*mm, 40*mm, 220*mm) boleto.line(55*mm, 204*mm, 55*mm, 212*mm) boleto.line(70*mm, 204*mm, 70*mm, 220*mm) boleto.line(90*mm, 212*mm, 90*mm, 220*mm) boleto.line(113*mm, 212*mm, 113*mm, 220*mm) boleto.line(123*mm, 204*mm, 123*mm, 212*mm) # separador em branco da quantidade e valor boleto.setStrokeColor(colors.white) boleto.line(123*mm, 205*mm, 123*mm, 208*mm) boleto.setStrokeColor(colors.black) boleto.line(158*mm, 196*mm, 200*mm, 196*mm) boleto.line(158*mm, 188*mm, 200*mm, 188*mm) boleto.line(158*mm, 180*mm, 200*mm, 180*mm) boleto.line(158*mm, 172*mm, 200*mm, 172*mm) boleto.line(158*mm, 164*mm, 200*mm, 164*mm) boleto.line(7*mm, 156*mm, 200*mm, 156*mm) # Divisor Recibo sacado e autenticação mecânica boleto.line(7*mm, 139*mm, 200*mm, 139*mm) boleto.line(144*mm, 126*mm, 144*mm, 133*mm) boleto.line(144*mm, 133*mm, 200*mm, 133*mm) boleto.line(200*mm, 126*mm, 200*mm, 133*mm) # Ficha de compensação boleto.setFont(FONTE_FORM, FONTE_FORM_TAM) boleto.drawString(7*mm, 108*mm, 'Local de pagamento') boleto.drawString(160*mm, 108*mm, 'Vencimento') boleto.drawString(7*mm, 100*mm, 'Cedente') boleto.drawString(7*mm, 92*mm, 'Data do documento') boleto.drawString(41*mm, 92*mm, 'No. do documento') boleto.drawString(71*mm, 92*mm, 'Espécie doc') boleto.drawString(91*mm, 92*mm, 'Aceite') boleto.drawString(114*mm, 92*mm, 'Data do processamento') boleto.drawString(160*mm, 100*mm, 'Agência/Código do cedente') boleto.drawString(7*mm, 84*mm, 'Uso do banco') boleto.drawString(41*mm, 84*mm, 'Carteira') boleto.drawString(56*mm, 84*mm, 'Espécie') boleto.drawString(71*mm, 84*mm, 'Quantidade') boleto.drawString(123*mm, 81*mm, 'x') boleto.drawString(124*mm, 84*mm, 'Valor') boleto.drawString(160*mm, 92*mm, 'Nosso número') boleto.drawString(160*mm, 84*mm, '(=) Valor do documento') boleto.drawString(160*mm, 76*mm, '(-) Desconto/Abatimento') boleto.drawString(160*mm, 68*mm, '(-) Outras deduções') boleto.drawString(160*mm, 60*mm, '(+) Mora/Multa') boleto.drawString(160*mm, 52*mm, '(+) Outros acréscimos') boleto.drawString(160*mm, 44*mm, '(=) Valor cobrado') boleto.drawString(7*mm, 36*mm, 'Sacado') boleto.drawString(7*mm, 23*mm, 'Sacador/avalista') boleto.drawString(135*mm, 23*mm, 'Código de baixa') boleto.drawString(161*mm, 20*mm, 'Autenticação mecânica') boleto.drawString(7*mm, 76*mm, 'Instruções (Todas informações deste BOLETO são de exclusiva responsabilidade do cedente)') boleto.setFont('Helvetica-Bold',14) boleto.drawString(58*mm, 112*mm, linhadigitavel) boleto.setFont(FONTE_DADOS, FONTE_DADOS_TAM) boleto.drawString(7*mm, 104*mm, localpagamento) boleto.drawString(180*mm, 104*mm, vencimento) boleto.drawString(7*mm, 96*mm, cedente) boleto.drawString(7*mm, 88*mm, emissao) boleto.drawString(41*mm, 88*mm, documento) boleto.drawString(71*mm, 88*mm, especiedoc) boleto.drawString(91*mm, 88*mm, aceite) boleto.drawString(114*mm, 88*mm, emissao) boleto.drawString(160*mm, 96*mm, agencia) boleto.drawString(7*mm, 80*mm, usobanco) boleto.drawString(41*mm, 80*mm, carteira) boleto.drawString(56*mm, 80*mm, especiemon) boleto.drawString(71*mm, 80*mm, '') boleto.drawString(124*mm, 80*mm, '') boleto.drawString(160*mm, 88*mm, nossonumero) boleto.drawString(7*mm, 72*mm, valorexpresso) boleto.drawString(177*mm, 80*mm, valor) boleto.drawString(160*mm, 72*mm, '') boleto.drawString(20*mm, 60*mm, juros) boleto.drawString(7*mm, 54*mm, observacao1) boleto.drawString(7*mm, 48*mm, observacao2) boleto.drawString(7*mm, 41*mm, observacao3) boleto.drawString(160*mm, 56*mm, '') boleto.drawString(160*mm, 48*mm, '') boleto.drawString(160*mm, 40*mm, '') boleto.drawString(160*mm, 32*mm, '') boleto.drawString(7*mm, 33*mm, sacado) boleto.drawString(7*mm, 29*mm, endereco) boleto.drawString(7*mm, 26*mm, endereco1) # Identificação das partes boleto.setFont(FONTE_FORM, FONTE_FORM_TAM_ID) boleto.drawString(165*mm, 140*mm, 'Recibo do sacado') boleto.drawString(163*mm, 23*mm, 'Ficha de compensação') boleto.setFont(FONTE_FORM, FONTE_FORM_TAM) # abaixo da logo do banco boleto.line(7*mm, 111*mm, 200*mm, 111*mm) # separador do número do banco boleto.line(42*mm, 111*mm, 42*mm, 116*mm) boleto.line(56*mm, 111*mm, 56*mm, 116*mm) # separador coluna local de pagamento e vencimento boleto.line(158*mm, 39*mm, 158*mm, 111*mm) # separadores local de pagamento, cedente, data do documento e uso do banco boleto.line(7*mm, 103*mm, 200*mm, 103*mm) boleto.line(7*mm, 95*mm, 200*mm, 95*mm) boleto.line(7*mm, 87*mm, 200*mm, 87*mm) boleto.line(7*mm, 79*mm, 200*mm, 79*mm) # separadores do bloco acima boleto.line(40*mm, 79*mm, 40*mm, 95*mm) boleto.line(55*mm, 79*mm, 55*mm, 87*mm) boleto.line(70*mm, 79*mm, 70*mm, 95*mm) boleto.line(90*mm, 87*mm, 90*mm, 95*mm) boleto.line(113*mm, 87*mm, 113*mm, 95*mm) boleto.line(123*mm, 79*mm, 123*mm, 87*mm) # separador em branco da quantidade e valor boleto.setStrokeColor(colors.white) boleto.line(123*mm, 80*mm, 123*mm, 83*mm) boleto.setStrokeColor(colors.black) # separadora valor documento, desconto abatimento boleto.line(158*mm, 71*mm, 200*mm, 71*mm) boleto.line(158*mm, 63*mm, 200*mm, 63*mm) boleto.line(158*mm, 55*mm, 200*mm, 55*mm) boleto.setLineWidth(0.2) boleto.line(158*mm, 47*mm, 200*mm, 47*mm) boleto.line(7*mm, 39*mm, 200*mm, 39*mm) # Divisor Ficha de compensação e autenticação mecânica boleto.setLineWidth(0.1) boleto.line(7*mm, 22*mm, 200*mm, 22*mm) boleto.line(144*mm, 12*mm, 144*mm, 19*mm) boleto.line(144*mm, 19*mm, 200*mm, 19*mm) boleto.line(200*mm, 12*mm, 200*mm, 19*mm) f = Frame(2*mm, mm, 5*mm, 20*mm, showBoundary=0) f.addFromList([I2of5(codigobarra,barWidth=0.89,ratio=2.2, xdim = 0.3*mm, checksum=0, bearers=0)], boleto) boleto.showPage() boleto.save() return response
story.append(Paragraph(ligne, styleN)) else: story.append(Paragraph(ligne, styleM)) n +=1 ofi.close() # === Construction du document PDF : can = Canvas("%s" % (fichier), pagesize=A4) largeurP, hauteurP = A4 # largeur et hauteur de la page can.setFont("Times-Bold", 18) can.drawString(5*cm, 28*cm, "Gestion des paragraphes avec ReportLab") # Mise en place de l'image, alignée à droite et centrée verticalement : posX =largeurP -1*cm -dimX # position du coin inférieur gauche posY =(hauteurP -dimY)/2 # (on laisse une marge de 1 cm à droite) can.drawImage(bitmap, posX, posY, width =dimX, height =dimY, mask="auto") # Mise en place des trois cadres entourant l'image : cS =Frame(1*cm, (hauteurP +dimY)/2, largeurP-2*cm, (hauteurP-dimY)/2-3*cm) cM =Frame(1*cm, (hauteurP -dimY)/2, largeurP-2*cm-dimX, dimY) cI =Frame(1*cm, 2*cm, largeurP-2*cm, (hauteurP-dimY)/2-2*cm) # Mise en place des paragraphes (fluables) dans ces trois cadres : cS.addFromList(story, can) # remplir le cadre supérieur cM.addFromList(story, can) # remplir le cadre médian cI.addFromList(story, can) # remplir le cadre inférieur can.save() # finaliser le document print("Éléments restants dans <story> : {0}.".format(len(story))) #import Image # Python Imaging Library #im =Image.open(fichierImage) # instanciation d'un objet-image PIL
class YearlyPdf: client = Address() provider = Address() items = [] title = "Faktura" vs = "00000000" creator = "" sign_image = None payment_days = 14 paytype = "Převodem" pdffile = None def __init__(self): self.p = inflect.engine() #self.TIN = "123121414" #self.CAN = "13123123123" self.TIN = "23102404783" self.CAN = "20/13/31/2009 21/14/31/2009" self.TOP = 260 self.LEFT = 20 pdfmetrics.registerFont(TTFont('DejaVu', '/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf')) self.pdffile = NamedTemporaryFile(delete=False) self.pdf = Canvas(self.pdffile.name, pagesize = A4) self.pdf.setFont("DejaVu", 15) self.pdf.setStrokeColorRGB(0, 0, 0) def __del__(self): if os.path.isfile(self.pdffile.name): os.unlink(self.pdffile.name) ############################################################# ## Setters ############################################################# def setClient(self, address): self.client = address def setProvider(self, address): self.provider = address def setTitle(self, value): self.title = value def setVS(self, value): self.vs = value def setCreator(self, value): self.creator = value def setPaytype(self, value): self.paytype = value def setPaymentDays(self, value): self.payment_days = int(value) def addItem(self, item): self.items.append(item) ############################################################# ## Getters ############################################################# def getContent(self): # Texty self.drawMain() self.drawProvider(self.TOP-8,self.LEFT+3) # self.drawClient(self.TOP-30,self.LEFT+91) #self.drawPayment(self.TOP-26,self.LEFT+3) self.pdf.setFont("DejaVu", 18) self.drawDates(self.TOP-10,self.LEFT+91) p = self.drawsItems(self.TOP-35,self.LEFT) #self.pdf.setFillColorRGB(0, 0, 0) self.pdf.showPage() self.pdf.save() f = open(self.pdffile.name) data = f.read() f.close() os.unlink(self.pdffile.name) return data ############################################################# ## Draw methods ############################################################# def drawMain(self): # Horní lajna self.pdf.drawString(self.LEFT*mm, self.TOP*mm, self.title) self.pdf.drawString((self.LEFT+65)*mm, self.TOP*mm, "Balance Sheet") self.pdf.setFont("DejaVu", 8) self.pdf.drawString((self.LEFT+120)*mm, (self.TOP)*mm, "Dated to: %s" % self.todate) self.pdf.drawString((self.LEFT+120)*mm, (self.TOP+3)*mm, "Dated from: %s" % self.fromdate) # Rámečky #self.pdf.rect((self.LEFT)*mm, (self.TOP-38)*mm, (self.LEFT+156)*mm, 35*mm, stroke=True, fill=False) path = self.pdf.beginPath() path.moveTo((self.LEFT+88)*mm, (self.TOP-3)*mm) path.lineTo((self.LEFT+88)*mm, (self.TOP-20)*mm) self.pdf.drawPath(path, True, True) path = self.pdf.beginPath() path.moveTo((self.LEFT)*mm, (self.TOP-20)*mm) path.lineTo((self.LEFT+88)*mm, (self.TOP-20)*mm) self.pdf.drawPath(path, True, True) path = self.pdf.beginPath() path.moveTo((self.LEFT+88)*mm, (self.TOP-26)*mm) path.lineTo((self.LEFT+176)*mm, (self.TOP-26)*mm) self.pdf.drawPath(path, True, True) path = self.pdf.beginPath() path.moveTo((self.LEFT+88)*mm, (self.TOP-26)*mm) path.lineTo((self.LEFT+88)*mm, (self.TOP-20)*mm) self.pdf.drawPath(path, True, True) def drawClient(self,TOP,LEFT): self.pdf.setFont("DejaVu", 12) self.pdf.drawString((LEFT)*mm, (TOP)*mm, "Odběratel") self.pdf.setFont("DejaVu", 8) text = self.pdf.beginText((LEFT+2)*mm, (TOP-6)*mm) text.textLines("\n".join(self.client.getAddressLines())) self.pdf.drawText(text) text = self.pdf.beginText((LEFT+2)*mm, (TOP-28)*mm) text.textLines("\n".join(self.client.getContactLines())) self.pdf.drawText(text) def drawProvider(self,TOP,LEFT): LEFT += 90 self.pdf.setFont("DejaVu", 12) self.pdf.drawString((LEFT)*mm, (TOP)*mm, "Address") self.pdf.setFont("DejaVu", 9) text = self.pdf.beginText((LEFT+2)*mm, (TOP-6)*mm) text.textLines("\n".join(self.provider.getAddressLines())) self.pdf.drawText(text) text = self.pdf.beginText((LEFT+40)*mm, (TOP-6)*mm) text.textLines("\n".join(self.provider.getContactLines())) self.pdf.drawText(text) if self.provider.note: self.pdf.drawString((LEFT+2)*mm, (TOP-26)*mm, self.provider.note) def drawPayment(self,TOP,LEFT): self.pdf.setFont("DejaVu", 11) self.pdf.drawString((LEFT)*mm, (TOP)*mm, "Patient Name") self.pdf.drawString((LEFT+50)*mm, (TOP)*mm, "Date") self.pdf.setFont("DejaVu", 9) text = self.pdf.beginText((LEFT+50)*mm, (TOP-6)*mm) text.textLines(self.date) self.pdf.drawText(text) text = self.pdf.beginText((LEFT+2)*mm, (TOP-6)*mm) text.textLines("\n".join(self.client.getAddressLines())) self.pdf.drawText(text) text = self.pdf.beginText((LEFT+2)*mm, (TOP-28)*mm) text.textLines("\n".join(self.client.getContactLines())) self.pdf.drawText(text) self.pdf.drawText(text) def drawsItems(self,TOP,LEFT): LEFT += 10 # Items #path = self.pdf.beginPath() #path.moveTo((LEFT)*mm, (TOP-4)*mm) #path.lineTo((LEFT+176)*mm, (TOP-4)*mm) #self.pdf.drawPath(path, True, True) self.pdf.setFont("DejaVu", 11) i=1 self.pdf.drawString((LEFT+1)*mm, (TOP-i)*mm, "Date") self.pdf.drawString((LEFT+40)*mm, (TOP-i)*mm, "Sale") self.pdf.drawString((LEFT+75)*mm, (TOP-i)*mm, "Purchase") self.pdf.drawString((LEFT+120)*mm, (TOP-i)*mm, "Credit") i+= 2 path = self.pdf.beginPath() path.moveTo((LEFT)*mm, (TOP-i)*mm) path.lineTo((LEFT+160)*mm, (TOP-i)*mm) self.pdf.drawPath(path, True, True) i+=7 self.pdf.setFont("DejaVu", 9) # List purchase = 0.0 sale = 0.0 credit = 0.0 for x in self.sitems: if TOP - i < 30: self.pdf.showPage() self.pdf.setFont("DejaVu", 9) i = TOP - 270 self.pdf.drawString((LEFT+1)*mm, (TOP-i)*mm, x.date) i+=0 self.pdf.drawString((LEFT+41)*mm, (TOP-i)*mm,"Rs. " + str(x.sale)) self.pdf.drawString((LEFT+76)*mm, (TOP-i)*mm,"Rs. " + str(x.purchase)) self.pdf.drawString((LEFT+121)*mm, (TOP-i)*mm,"Rs. " +str(x.credit)) i+=5 purchase += x.purchase sale += x.sale credit += x.credit path = self.pdf.beginPath() path.moveTo((LEFT)*mm, (TOP-i)*mm) path.lineTo((LEFT+160)*mm, (TOP-i)*mm) self.pdf.drawPath(path, True, True) i+= 10 path = self.pdf.beginPath() path.moveTo((LEFT)*mm, (TOP-i)*mm) path.lineTo((LEFT+160)*mm, (TOP-i)*mm) self.pdf.drawPath(path, True, True) sale = round(sale,2) purchase = round(purchase,2) credit = round(credit,2) self.pdf.setFont("DejaVu", 10) self.pdf.setFont("DejaVu", 11) self.pdf.drawString((LEFT+2)*mm, (TOP-i+3)*mm, "Total Sale: ") self.pdf.drawString((LEFT+25)*mm, (TOP-i+3)*mm, "Rs. " + str(sale)) self.pdf.drawString((LEFT+52)*mm, (TOP-i+3)*mm, "Purchase: ") self.pdf.drawString((LEFT+73)*mm, (TOP-i+3)*mm, "Rs. " + str(purchase)) self.pdf.drawString((LEFT+97)*mm, (TOP-i+3)*mm, "Credit: ") self.pdf.drawString((LEFT+112)*mm, (TOP-i+3)*mm, "Rs. " + str(credit)) # self.pdf.rect((LEFT)*mm, (TOP-i-12)*mm, (LEFT+156)*mm, (i+19)*mm, stroke=True, fill=False) #140,142 if self.sign_image: self.pdf.drawImage(self.sign_image, (LEFT+98)*mm, (TOP-i-72)*mm) return TOP - i # if self.creator: # path = self.pdf.beginPath() # path.moveTo((LEFT+110)*mm, (TOP-i-70)*mm) # path.lineTo((LEFT+164)*mm, (TOP-i-70)*mm) # self.pdf.drawPath(path, True, True) # self.pdf.drawString((LEFT+112)*mm, (TOP-i-75)*mm, "Authorized Signatory") # self.pdf.rect((LEFT)*mm, (TOP-i-12)*mm, (LEFT+156)*mm, (i+19)*mm, stroke=True, fill=False) #140,142 def drawDates(self,TOP,LEFT): LEFT -= 90 today = datetime.datetime.today() payback = today+datetime.timedelta(self.payment_days) self.pdf.setFont("DejaVu", 10) self.pdf.drawString((LEFT)*mm, (TOP+1)*mm, "TIN: %s" % self.TIN) self.pdf.drawString((LEFT)*mm, (TOP-4)*mm, "DL: %s" % self.CAN)
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 __init__(self, dictDonnees={}): self.dictDonnees = dictDonnees # Importation des données DB = GestionDB.DB() # Catégories de menus if 0 not in dictDonnees["categories_menus"]: if len(dictDonnees["categories_menus"]) == 0 : conditions = "WHERE IDcategorie IN ()" elif len(dictDonnees["categories_menus"]) == 1 : conditions = "WHERE IDcategorie=%d" % dictDonnees["categories_menus"][0] else : conditions = "WHERE IDcategorie IN %s" % (str(tuple(dictDonnees["categories_menus"]))) else : conditions = "" req = """SELECT IDcategorie, nom FROM menus_categories %s ORDER BY ordre;""" % conditions DB.ExecuterReq(req) listeDonnees = DB.ResultatReq() self.dictDonnees["categories"] = [] for IDcategorie, nom in listeDonnees: self.dictDonnees["categories"].append({"IDcategorie": IDcategorie, "nom": nom}) # Légendes req = """SELECT IDlegende, nom, couleur FROM menus_legendes ;""" DB.ExecuterReq(req) listeDonnees = DB.ResultatReq() self.dictDonnees["legendes"] = {} for IDlegende, nom, couleur in listeDonnees: couleur = UTILS_Images.CouleurStrToTuple(couleur) self.dictDonnees["legendes"][IDlegende] = {"IDlegende" : IDlegende, "nom": nom, "couleur" : couleur} # Menus req = """SELECT IDmenu, IDcategorie, date, texte FROM menus WHERE date>='%s' AND date<='%s' AND IDrestaurateur=%d ;""" % (dictDonnees["date_debut"], dictDonnees["date_fin"], dictDonnees["IDrestaurateur"]) DB.ExecuterReq(req) listeDonnees = DB.ResultatReq() self.dictDonnees["menus"] = {} for IDmenu, IDcategorie, date, texte in listeDonnees: date = UTILS_Dates.DateEngEnDateDD(date) if self.dictDonnees["menus"].has_key(date) == False: self.dictDonnees["menus"][date] = {} if texte != None and len(texte) == 0: texte = None self.dictDonnees["menus"][date][IDcategorie] = {"IDmenu": IDmenu, "texte": texte} DB.Close() # Paramètres if dictDonnees["page_format"] == "paysage" : hauteur_page, largeur_page = A4 else : largeur_page, hauteur_page = A4 # Initialisation du PDF nomDoc = FonctionsPerso.GenerationNomDoc("MENU", "pdf") canvas = Canvas(nomDoc, pagesize=(largeur_page, hauteur_page)) # Calcule les pages if dictDonnees["type"] == "mensuel" : liste_pages = [{"annee" : date.year, "mois" : date.month} for date in list(rrule.rrule(rrule.MONTHLY, dtstart=dictDonnees["date_debut"], until=dictDonnees["date_fin"]))] if dictDonnees["type"] == "hebdomadaire" : liste_pages = [{"date" : date} for date in list(rrule.rrule(rrule.WEEKLY, dtstart=dictDonnees["date_debut"], until=dictDonnees["date_fin"]))] if dictDonnees["type"] == "quotidien" : liste_pages = [{"date" : date} for date in list(rrule.rrule(rrule.DAILY, dtstart=dictDonnees["date_debut"], until=dictDonnees["date_fin"]))] num_page = 0 for dict_page in liste_pages : # Calcule le nombre de lignes et de colonnes if dictDonnees["type"] == "mensuel": calendrier = self.GetCalendrierMois(annee=dict_page["annee"], mois=dict_page["mois"], jours_semaine=dictDonnees["jours_semaine"]) nbre_lignes = len(calendrier) nbre_colonnes = len(dictDonnees["jours_semaine"]) texte_titre = UTILS_Dates.PeriodeComplete(mois=dict_page["mois"], annee=dict_page["annee"]) if dictDonnees["type"] == "hebdomadaire": calendrier = self.GetCalendrierSemaine(date=dict_page["date"], jours_semaine=dictDonnees["jours_semaine"]) nbre_lignes = 1 nbre_colonnes = len(dictDonnees["jours_semaine"]) texte_titre = self.GetLabelSemaine(calendrier[0], calendrier[-1]) if dictDonnees["type"] == "quotidien": calendrier = None nbre_lignes = 1 nbre_colonnes = 1 texte_titre = UTILS_Dates.DateComplete(dict_page["date"]) # Préparation marge_haut = copy.copy(dictDonnees["page_marge_haut"]) marge_bas = copy.copy(dictDonnees["page_marge_bas"]) # Calcule la largeur des cases largeur_case = ((largeur_page - dictDonnees["page_marge_gauche"] - dictDonnees["page_marge_droite"]) - dictDonnees["page_espace_horizontal"] * (nbre_colonnes - 1)) / nbre_colonnes # Dessine l'image de fond if dictDonnees["page_fond_image"] != "aucune" : canvas.drawImage(Chemins.GetStaticPath("Images/%s" % dictDonnees["page_fond_image"]), 0, 0, largeur_page, hauteur_page, preserveAspectRatio=False) # Dessine le titre if dictDonnees["titre_afficher"] == True: if dictDonnees["titre_texte"] != "" : texte_titre = u"%s %s" % (dictDonnees["titre_texte"], texte_titre) titre = Titre(parent=self, texte=texte_titre, canvas=canvas, largeur=largeur_page) marge_haut += dictDonnees["titre_hauteur"] # Dessine les entêtes if dictDonnees["entete_afficher"] == True: for num_colonne in range(0, nbre_colonnes): # Calcule la position de la case x_entete = dictDonnees["page_marge_gauche"] + ((largeur_case + dictDonnees["page_espace_horizontal"]) * num_colonne) y_entete = hauteur_page - marge_haut - dictDonnees["entete_hauteur"] # Dessine l'entête texte = UTILS_Dates.LISTE_JOURS[dictDonnees["jours_semaine"][num_colonne]] entete = Entete(parent=self, texte=texte, canvas=canvas, x=x_entete, y=y_entete, largeur_case=largeur_case) marge_haut += dictDonnees["entete_hauteur"] + dictDonnees["page_espace_vertical"] # Dessine le pied if dictDonnees["pied_afficher"] == True and len(dictDonnees["pied_texte"]) > 0 : pied = Pied(parent=self, texte=dictDonnees["pied_texte"], canvas=canvas, x=dictDonnees["page_marge_gauche"], y=marge_bas, largeur=largeur_page - dictDonnees["page_marge_gauche"] - dictDonnees["page_marge_droite"]) marge_bas += dictDonnees["pied_hauteur"] + dictDonnees["page_espace_vertical"] # Dessine la légende self.dictNumerosLegendes = {} if dictDonnees["legende_afficher"] == True : # Recherche les légendes présentes dans la page liste_legendes = [] for num_colonne in range(0, nbre_colonnes): for num_ligne in range(0, nbre_lignes): date, dictTextes = self.GetDateAndTextes(num_ligne=num_ligne, num_colonne=num_colonne, dict_page=dict_page, calendrier=calendrier) for IDcategorie, dictTexte in dictTextes.iteritems(): for chaine in REGEX_LEGENDES.findall(dictTexte["texte"]): try : IDlegende = int(chaine[1:-1]) dictLegende = self.dictDonnees["legendes"][IDlegende] if dictLegende not in liste_legendes and self.dictDonnees["legendes"].has_key(IDlegende) : liste_legendes.append(dictLegende) except : pass if len(liste_legendes) > 0 : legende = Legende(parent=self, liste_legendes=liste_legendes, canvas=canvas, x=dictDonnees["page_marge_gauche"], y=marge_bas, largeur=largeur_page - dictDonnees["page_marge_gauche"] - dictDonnees["page_marge_droite"]) self.dictNumerosLegendes = legende.dictNumerosLegendes marge_bas += dictDonnees["legende_hauteur"] + dictDonnees["page_espace_vertical"] # Calcul la hauteur des cases hauteur_case = ((hauteur_page - marge_haut - marge_bas) - dictDonnees["page_espace_vertical"] * (nbre_lignes - 1)) / nbre_lignes # Dessine les cases for num_colonne in range(0, nbre_colonnes): for num_ligne in range(0, nbre_lignes): # Calcule la position de la case x_case = dictDonnees["page_marge_gauche"] + ((largeur_case + dictDonnees["page_espace_horizontal"]) * num_colonne) y_case = hauteur_page - marge_haut - hauteur_case - ((hauteur_case + dictDonnees["page_espace_vertical"]) * num_ligne) # Recherche la date et les textes date, dictTextes = self.GetDateAndTextes(num_ligne=num_ligne, num_colonne=num_colonne, dict_page=dict_page, calendrier=calendrier) # Dessin de la case case = Case(parent=self, date=date, dictTextes=dictTextes, canvas=canvas, x=x_case, y=y_case, largeur_case=largeur_case, hauteur_case=hauteur_case) # Dessine la grille if dictDonnees["page_grille"] == True : canvas.setStrokeColor(ColorWxToPdf(wx.LIGHT_GREY, alpha=0.5)) canvas.setFillColor(ColorWxToPdf(wx.LIGHT_GREY, alpha=0.5)) canvas.setLineWidth(0.25) canvas.grid(range(0, int(largeur_page)+50, 50), range(0, int(hauteur_page)+50, 50)) canvas.setFont("Helvetica", 8) canvas.drawString(10, 10, _(u"Largeur carreau=50")) # Saut de page if num_page < len(liste_pages) - 1: canvas.showPage() # Finalisation du PDF canvas.save() try: FonctionsPerso.LanceFichierExterne(nomDoc) except: print "Probleme dans l'edition du menu"
class Invoice: client = Address() provider = Address() items = [] title = "Faktura" vs = "00000000" creator = "" sign_image = None payment_days = 14 paytype = "Převodem" pdffile = None def __init__(self): self.TOP = 260 self.LEFT = 20 pdfmetrics.registerFont(TTFont('DejaVu', '/usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf')) self.pdffile = NamedTemporaryFile(delete=False) self.pdf = Canvas(self.pdffile.name, pagesize = letter) self.pdf.setFont("DejaVu", 15) self.pdf.setStrokeColorRGB(0, 0, 0) def __del__(self): if os.path.isfile(self.pdffile.name): os.unlink(self.pdffile.name) ############################################################# ## Setters ############################################################# def setClient(self, address): self.client = address def setProvider(self, address): self.provider = address def setTitle(self, value): self.title = value def setVS(self, value): self.vs = value def setCreator(self, value): self.creator = value def setPaytype(self, value): self.paytype = value def setPaymentDays(self, value): self.payment_days = int(value) def addItem(self, item): self.items.append(item) ############################################################# ## Getters ############################################################# def getContent(self): # Texty self.drawMain() self.drawProvider(self.TOP-10,self.LEFT+3) self.drawClient(self.TOP-30,self.LEFT+91) self.drawPayment(self.TOP-47,self.LEFT+3) self.drawItems(self.TOP-80,self.LEFT) self.drawDates(self.TOP-10,self.LEFT+91) #self.pdf.setFillColorRGB(0, 0, 0) self.pdf.showPage() self.pdf.save() f = open(self.pdffile.name) data = f.read() f.close() os.unlink(self.pdffile.name) return data ############################################################# ## Draw methods ############################################################# def drawMain(self): # Horní lajna self.pdf.drawString(self.LEFT*mm, self.TOP*mm, self.title) self.pdf.drawString((self.LEFT+100)*mm, self.TOP*mm, "Variabilní symbol: %s" % self.vs) # Rámečky self.pdf.rect((self.LEFT)*mm, (self.TOP-68)*mm, (self.LEFT+156)*mm, 65*mm, stroke=True, fill=False) path = self.pdf.beginPath() path.moveTo((self.LEFT+88)*mm, (self.TOP-3)*mm) path.lineTo((self.LEFT+88)*mm, (self.TOP-68)*mm) self.pdf.drawPath(path, True, True) path = self.pdf.beginPath() path.moveTo((self.LEFT)*mm, (self.TOP-39)*mm) path.lineTo((self.LEFT+88)*mm, (self.TOP-39)*mm) self.pdf.drawPath(path, True, True) path = self.pdf.beginPath() path.moveTo((self.LEFT+88)*mm, (self.TOP-23)*mm) path.lineTo((self.LEFT+176)*mm, (self.TOP-23)*mm) self.pdf.drawPath(path, True, True) def drawClient(self,TOP,LEFT): self.pdf.setFont("DejaVu", 12) self.pdf.drawString((LEFT)*mm, (TOP)*mm, "Odběratel") self.pdf.setFont("DejaVu", 8) text = self.pdf.beginText((LEFT+2)*mm, (TOP-6)*mm) text.textLines("\n".join(self.client.getAddressLines())) self.pdf.drawText(text) text = self.pdf.beginText((LEFT+2)*mm, (TOP-28)*mm) text.textLines("\n".join(self.client.getContactLines())) self.pdf.drawText(text) def drawProvider(self,TOP,LEFT): self.pdf.setFont("DejaVu", 12) self.pdf.drawString((LEFT)*mm, (TOP)*mm, "Dodavatel") self.pdf.setFont("DejaVu", 8) text = self.pdf.beginText((LEFT+2)*mm, (TOP-6)*mm) text.textLines("\n".join(self.provider.getAddressLines())) self.pdf.drawText(text) text = self.pdf.beginText((LEFT+40)*mm, (TOP-6)*mm) text.textLines("\n".join(self.provider.getContactLines())) self.pdf.drawText(text) if self.provider.note: self.pdf.drawString((LEFT+2)*mm, (TOP-26)*mm, self.provider.note) def drawPayment(self,TOP,LEFT): self.pdf.setFont("DejaVu", 11) self.pdf.drawString((LEFT)*mm, (TOP)*mm, "Údaje pro platbu") #self.pdf.setFillColorRGB(255, 0, 0) text = self.pdf.beginText((LEFT+2)*mm, (TOP-6)*mm) text.textLines("""%s Číslo účtu: %s Variabilní symbol: %s"""%(self.provider.bank_name ,self.provider.bank_account, self.vs)) self.pdf.drawText(text) def drawItems(self,TOP,LEFT): # Items path = self.pdf.beginPath() path.moveTo((LEFT)*mm, (TOP-4)*mm) path.lineTo((LEFT+176)*mm, (TOP-4)*mm) self.pdf.drawPath(path, True, True) self.pdf.setFont("DejaVu", 9) self.pdf.drawString((LEFT+1)*mm, (TOP-2)*mm, "Fakturuji vám:") i=9 self.pdf.drawString((LEFT+100)*mm, (TOP-i)*mm, "Množství") self.pdf.drawString((LEFT+122)*mm, (TOP-i)*mm, "Cena za jedn.") self.pdf.drawString((LEFT+150)*mm, (TOP-i)*mm, "Cena celkem") i+=5 # List total=0.0 for x in self.items: self.pdf.drawString((LEFT+1)*mm, (TOP-i)*mm, x.name) i+=5 self.pdf.drawString((LEFT+100)*mm, (TOP-i)*mm, "%d ks" % x.count) self.pdf.drawString((LEFT+122)*mm, (TOP-i)*mm, "%.2f,- kč" % x.price) self.pdf.drawString((LEFT+150)*mm, (TOP-i)*mm, "%.2f,- kč" % (x.total())) i+=5 total += x.total() path = self.pdf.beginPath() path.moveTo((LEFT)*mm, (TOP-i)*mm) path.lineTo((LEFT+176)*mm, (TOP-i)*mm) self.pdf.drawPath(path, True, True) self.pdf.setFont("DejaVu", 12) self.pdf.drawString((LEFT+130)*mm, (TOP-i-10)*mm, "Celkem: %d ,- kč" % total) self.pdf.rect((LEFT)*mm, (TOP-i-17)*mm, (LEFT+156)*mm, (i+19)*mm, stroke=True, fill=False) #140,142 if self.sign_image: self.pdf.drawImage(self.sign_image, (LEFT+98)*mm, (TOP-i-72)*mm) path = self.pdf.beginPath() path.moveTo((LEFT+110)*mm, (TOP-i-70)*mm) path.lineTo((LEFT+164)*mm, (TOP-i-70)*mm) self.pdf.drawPath(path, True, True) self.pdf.drawString((LEFT+112)*mm, (TOP-i-75)*mm, "Vystavil: %s" % self.creator) def drawDates(self,TOP,LEFT): today = datetime.datetime.today() payback = today+datetime.timedelta(self.payment_days) self.pdf.setFont("DejaVu", 10) self.pdf.drawString((LEFT)*mm, (TOP+1)*mm, "Datum vystavení: %s" % today.strftime("%d.%m.%Y")) self.pdf.drawString((LEFT)*mm, (TOP-4)*mm, "Datum splatnosti: %s" % payback.strftime("%d.%m.%Y")) self.pdf.drawString((LEFT)*mm, (TOP-9)*mm, "Forma úhrady: " + self.paytype)
def to_pdf(self, outFileName, imageFileName=None, showBoundingboxes=False, fontname="Helvetica", invisibleText=False): """ Creates a PDF file with an image superimposed on top of the text. Text is positioned according to the bounding box of the lines in the hOCR file. The image need not be identical to the image used to create the hOCR file. It can have a lower resolution, different color mode, etc. """ # create the PDF file # page size in points (1/72 in.) pdf = Canvas( outFileName, pagesize=(self.width, self.height), pageCompression=1) # draw bounding box for each paragraph # light blue for bounding box of paragraph pdf.setStrokeColorRGB(0, 1, 1) # light blue for bounding box of paragraph pdf.setFillColorRGB(0, 1, 1) pdf.setLineWidth(0) # no line for bounding box for elem in self.hocr.findall( ".//%sp[@class='%s']" % (self.xmlns, "ocr_par")): elemtxt = self._get_element_text(elem).rstrip() if len(elemtxt) == 0: continue pxl_coords = self.element_coordinates(elem) pt = self.pt_from_pixel(pxl_coords) # draw the bbox border if showBoundingboxes: pdf.rect( pt.x1, self.height - pt.y2, pt.x2 - pt.x1, pt.y2 - pt.y1, fill=1) # check if element with class 'ocrx_word' are available # otherwise use 'ocr_line' as fallback elemclass = "ocr_line" if self.hocr.find( ".//%sspan[@class='ocrx_word']" % (self.xmlns)) is not None: elemclass = "ocrx_word" # itterate all text elements # light green for bounding box of word/line pdf.setStrokeColorRGB(1, 0, 0) pdf.setLineWidth(0.5) # bounding box line width pdf.setDash(6, 3) # bounding box is dashed pdf.setFillColorRGB(0, 0, 0) # text in black for elem in self.hocr.findall( ".//%sspan[@class='%s']" % (self.xmlns, elemclass)): elemtxt = self._get_element_text(elem).rstrip() elemtxt = self.replace_unsupported_chars(elemtxt) if len(elemtxt) == 0: continue pxl_coords = self.element_coordinates(elem) pt = self.pt_from_pixel(pxl_coords) # draw the bbox border if showBoundingboxes: pdf.rect( pt.x1, self.height - pt.y2, pt.x2 - pt.x1, pt.y2 - pt.y1, fill=0) text = pdf.beginText() fontsize = pt.y2 - pt.y1 text.setFont(fontname, fontsize) if invisibleText: text.setTextRenderMode(3) # Invisible (indicates OCR text) # set cursor to bottom left corner of bbox (adjust for dpi) text.setTextOrigin(pt.x1, self.height - pt.y2) # scale the width of the text to fill the width of the bbox text.setHorizScale( 100 * (pt.x2 - pt.x1) / pdf.stringWidth( elemtxt, fontname, fontsize)) # write the text to the page text.textLine(elemtxt) pdf.drawText(text) # put the image on the page, scaled to fill the page if imageFileName is not None: pdf.drawImage(imageFileName, 0, 0, width=self.width, height=self.height) # finish up the page and save it pdf.showPage() pdf.save()
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()