def draw_pdf_page(canvas, table=[], extraordinary=None, title=None, image=None, logo=None, fontsize=12): # Header - Title and Logo if title: canvas.setFont("Helvetica", 32) canvas.drawString(x=40, y=510, text=title) # Content canvas.setFont("Helvetica", fontsize) # Table y = 450 - fontsize # origin of coordinates is bottom left for (label, value) in table: canvas.drawString(40, y, label) # breaks lines if too long and then draw line by line for line in simpleSplit(text=value, fontName=canvas._fontname, fontSize=canvas._fontsize, maxWidth=130): canvas.drawString(175, y, line) y -= 15 y -= 6 # add spacing between two rows if extraordinary: canvas.drawString(40, y, "Extraordinary:") y -= 16 for line in simpleSplit(text=extraordinary, fontName=canvas._fontname, fontSize=canvas._fontsize, maxWidth=255): canvas.drawString(50, y, line) y -= 15 # plot image if image: try: w = 480 h = image.height / image.width * w # keep ratio canvas.drawImage(image.url, x=321.9, y=450 - h, width=w, height=h) except IOError: print("Image not found") pdf_page_frame(canvas, logo)
def computeSize(self): # the thing will draw in its own coordinate system self._lineWidths = [] topPadding = self.topPadding leftPadding = self.leftPadding rightPadding = self.rightPadding bottomPadding = self.bottomPadding self._lines = simpleSplit(self._text,self.fontName,self.fontSize,self.maxWidth) if not self.width: self._width = leftPadding+rightPadding if self._lines: self._lineWidths = [stringWidth(line,self.fontName,self.fontSize) for line in self._lines] self._width += max(self._lineWidths) else: self._width = self.width self._height = self.height or ((self.leading or 1.2*self.fontSize) * len(self._lines)+topPadding+bottomPadding) self._ewidth = (self._width-leftPadding-rightPadding) self._eheight = (self._height-topPadding-bottomPadding) boxAnchor = self._getBoxAnchor() if boxAnchor in ['n','ne','nw']: self._top = -topPadding elif boxAnchor in ['s','sw','se']: self._top = self._height-topPadding else: self._top = 0.5*self._eheight self._bottom = self._top - self._eheight if boxAnchor in ['ne','e','se']: self._left = leftPadding - self._width elif boxAnchor in ['nw','w','sw']: self._left = leftPadding else: self._left = -self._ewidth*0.5 self._right = self._left+self._ewidth
def drawMeal(c, x, y, width, height, mealTime, fillers, students): xCenter = x + width / 2 c.setFillColor(colors.black) c.setFontSize(16) c.drawCentredString(xCenter, y, mealTime.name.strip()) y -= 16 c.setFontSize(12) for f in fillers: if f.display: c.drawCentredString(xCenter, y, f.description.strip()) y -= 12 if fillers: y -= 10 for s in students: name = s.flaggedName lines = simpleSplit(name, FONT, 12, width) if len(lines) == 1: c.drawString(x, y, lines[0]) else: c.drawString(x, y, lines[0]) for line in lines[1:]: y -= 12 c.drawString(x + 12, y, line) c.setFontSize(12) y -= 14 return y
def drawMeal(c, x, y, width, height, mealTime, fillers, students): xCenter = x + width / 2 c.setFillColor(colors.black) c.setFontSize(16) c.drawCentredString(xCenter, y, mealTime.name.strip()) y -= 16 c.setFontSize(12) for f in fillers: if f.display: c.drawCentredString(xCenter, y, f.description.strip()) y -= 12 if fillers: y -= 10 for s in students: name = s.flaggedName lines = simpleSplit(name, FONT, 12, width) if len(lines) == 1: c.drawString(x, y, lines[0]) else: c.drawString(x, y, lines[0]) for line in lines[1:]: y -= 12 c.drawString(x+12, y, line) c.setFontSize(12) y -= 14 return y
def draw_text_bottom(canvas, text, fontsize=60): def get_center_x_coord(text, fontName, fontsize): strwidth = stringWidth(text, fontName, fontsize) x = (width - strwidth) / 2 return x fontName = "Helvetica-Bold" maxWidth = 0.8 * width canvas.setFillColor(black) canvas.setStrokeColor(black) canvas.setFont(fontName, fontsize) lines = simpleSplit(text, fontName, fontsize, maxWidth) if (len(lines) > 1): draw_text_bottom(canvas, text, fontsize * 0.9) else: y = 170 canvas.drawString(get_center_x_coord(text, fontName, fontsize), y, text) # Smaller text fontName = "Helvetica" fontsize = 20 canvas.setFont(fontName, fontsize) text = "Asp-lunch Tisdag Lv1" y = y - 30 canvas.drawString(get_center_x_coord(text, fontName, fontsize), y, text) text = "12:00 i FB" y = y - fontsize - 5 canvas.drawString(get_center_x_coord(text, fontName, fontsize), y, text) text = "Tas ned den 11/12" y = fontsize canvas.drawString(get_center_x_coord(text, fontName, fontsize), y, text)
def setHeader(self): """ sets all the header information per page, adds Title and tile bar, aligned on the top center of the page """ showLogoWidth = self.setShowLogo() showLogoWidth = showLogoWidth + 5 if showLogoWidth else 0 # add 5 for padding if show logo exists self.canvas.setLineWidth(width=1) self.canvas.setFillColor(lightslategray) self.canvas.setStrokeColor(black) self.canvas.rect( self.marginSize + showLogoWidth, (self.pageHeight - self.header), (self.pageWidth - (self.marginSize * 2)) - showLogoWidth, self.marginSize, fill=True, stroke=True, ) # header text self.canvas.setFillColor(black) titleSplit = simpleSplit( self.title, self.fontType, 16, (self.pageWidth - (self.marginSize * 2)) - showLogoWidth ) self.canvas.setFont(self.fontType, 16) self.canvas.drawString( (self.marginSize * 1.25) + showLogoWidth, self.pageHeight - (self.marginSize * 1.125), titleSplit[0] )
def create_paragraph(texttype, input_text, fontsize, fontstyle, maxwidth, align): # if texttype == 'lyric' or len(input_text) <= 1: # text = input_text # small_fontsize = fontsize # else: # text = input_text[0] # small_fontsize = str(fontsize*0.7) # for i in range(1,len(input_text)): # if input_text[i] in ['#', 'b']: # text += '<super>' + input_text[i] + '</super>' # else: # text += input_text[i] # # if '<super>' in text: # print text text = input_text text_width = stringWidth(text, fontstyle, fontsize) new_fontsize = fontsize line_count = len(simpleSplit(text, fontstyle, new_fontsize, maxwidth)) while (line_count > 1 or text_width > maxwidth) and new_fontsize > 0: new_fontsize = new_fontsize - scale_it(0.5) text_width = stringWidth(text, fontstyle, new_fontsize) line_count = len(simpleSplit(text, fontstyle, new_fontsize, maxwidth)) # if text == 'something from the': # print "text width: " + str(text_width) + " font size: " + str(fontsize) if fontsize <= 0: print "error: can't print this " + texttype + ": [" + text + "] too wide at any size. Exiting." exit() # make a new style based on this new size uniq = str(time.clock()) style_name = texttype + uniq styles.add(ParagraphStyle( style_name, fontName=fontstyle, fontSize=new_fontsize, alignment=align)) return Paragraph(text, styles[style_name])
def particionar_text(self, c): tet = "" for i in range(len(c)): tet += c[i] lines = simpleSplit(tet, 'Times-Roman', 8, 95) if len(lines) > 1: return tet[:-1] return tet
def particionar_text(self, c, f, d): tet = "" for i in range(len(c)): tet += c[i] lines = simpleSplit(tet, 'Arimo-Regular', f, d) if len(tet) > d: return tet[:-1] return tet
def particionar_text(self,c,tam): tet = "" for i in range(len(c)): tet += c[i] lines = simpleSplit(tet,'Calibri',8,tam) if len(lines)>1: return tet[:-1] return tet
def computeSize(self): # the thing will draw in its own coordinate system ddfKlass = getattr(self,'ddfKlass',None) if not ddfKlass: self._lineWidths = [] self._lines = simpleSplit(self._text,self.fontName,self.fontSize,self.maxWidth) if not self.width: self._width = self.leftPadding+self.rightPadding if self._lines: self._lineWidths = [stringWidth(line,self.fontName,self.fontSize) for line in self._lines] self._width += max(self._lineWidths) else: self._width = self.width self._getBaseLineRatio() if self.leading: self._leading = self.leading elif self.useAscentDescent: self._leading = self._ascent - self._descent else: self._leading = self.fontSize*1.2 objH = self._leading*len(self._lines) else: if self.ddf is None: raise RuntimeError('DirectDrawFlowable class is not available you need the rlextra package as well as reportlab') sty = dict( name='xlabel-generated', fontName=self.fontName, fontSize=self.fontSize, fillColor=self.fillColor, strokeColor=self.strokeColor, ) sty = self._style = (ddfStyle.clone if self.ddfStyle else ParagraphStyle)(**sty) self._getBaseLineRatio() if self.useAscentDescent: sty.autoLeading = True sty.leading = self._ascent - self._descent else: sty.leading = self.leading if self.leading else self.fontSize*1.2 self._leading = sty.leading ta = self._getTextAnchor() aW = self.maxWidth or 0x7fffffff if ta!='start': sty.alignment = TA_LEFT obj = ddfKlass(self._text,style=sty) _, objH = obj.wrap(aW,0x7fffffff) aW = self.maxWidth or obj._width_max sty.alignment = _ta2al[ta] self._ddfObj = obj = ddfKlass(self._text,style=sty) _, objH = obj.wrap(aW,0x7fffffff) if not self.width: self._width = self.leftPadding+self.rightPadding self._width += obj._width_max else: self._width = self.width self._computeSizeEnd(objH)
def reviseCPS(text, cps): # Split in Lines to check HEIGHT lines = simpleSplit(text, cps.fontName, cps.fontSize, maxWidth) while cps.leading * len(lines) > maxHeight: cps.fontSize -= 1 cps.leading -= 0.6 lines = simpleSplit(text, cps.fontName, cps.fontSize, maxWidth) # Get Lines WIDTH lineWidth = [stringWidth(k, cps.fontName, cps.fontSize) for k in lines] k = lines[lineWidth.index(max(lineWidth))] lineWidth = lineWidth[lineWidth.index(max(lineWidth))] while lineWidth > maxWidth: cps.fontSize -= 1 cps.leading -= 0.6 lineWidth = stringWidth(k, cps.fontName, cps.fontSize)
def __break_lines(self, textString: str, max_w: int) -> str: """__break_lines will break lines Arguments: textString (str): Text to break max_w (int): Max width Returns: str: New str """ return simpleSplit(textString, self.fontType, self.font_size, max_w)
def split_clue_lines(clues, width): lines = [] across_clues = [c for c in clues if c.direction == 'A'] lines.append('ACROSS') for c in across_clues: clue_text = str(c.start_num) + '. ' + c.clue_text first_line = simpleSplit(clue_text, 'Helvetica', 12, width)[0] next_lines = simpleSplit(clue_text[len(first_line):], 'Helvetica', 12, width - TAB_LENGTH) lines += [first_line] + ['_' + l for l in next_lines] down_clues = [c for c in clues if c.direction == 'D'] lines.append(' ') lines.append('DOWN') for c in down_clues: clue_text = str(c.start_num) + '. ' + c.clue_text first_line = simpleSplit(clue_text, 'Helvetica', 12, width)[0] next_lines = simpleSplit(clue_text[len(first_line):], 'Helvetica', 12, width - TAB_LENGTH) lines += [first_line] + next_lines return lines
def get_text_height(lines, width=DEFAULT_WIDTH): answer = 0 for line in lines: # simpleSplit calculates how reportlab will break up the lines for # display in a paragraph, by using width/fontsize. # Default Frame padding is 6px on left & right # TODO Drop font size if first line is just one short word split = simpleSplit(line.text, line.style.fontName, line.style.fontSize, width - 12) answer += len(split) * line.style.leading return answer
def pdfkeycreate(self): for i, intersection in enumerate(self.key): try: temph = simpleSplit((intersection['H']), 'David', 8, 3.9 * cm) #temph.reverse() temph[0] = ((temph[0][::-1] + "." + str(i + 1))) self.keyh.append(Paragraph(temph[0], self.styles['default'])) for item in temph[1:]: self.keyh.append( Paragraph((item[::-1]), self.styles['default'])) except KeyError: pass try: tempv = simpleSplit((intersection['V']), 'David', 8, 3.9 * cm) tempv[0] = ((tempv[0][::-1] + "." + str(i + 1))) self.keyv.append(Paragraph(tempv[0], self.styles['default'])) for item in tempv[1:]: self.keyv.append( Paragraph((item[::-1]), self.styles['default'])) except KeyError: pass
def writetext(self, pos_x, pos_y, text): """Print text centred at pos_x, pos_y on the given canvas. If text is wider than maxwidth, it is wrapped on multiple lines. Returns the number of lines written. """ textlines = simpleSplit(text, *self.canvas.currentfont, self.maxwidth) for line in textlines: self.canvas.drawCentredString(pos_x, pos_y, line) pos_y -= self.baselineskip return len(textlines)
def __init__(self, font, text, align, height, width, **kwargs): BaseRenderer.__init__(self, **kwargs) self.font = font self.align = align self.lineheight = height self.width = width if self.width is None: self.lines = text.split("\n") else: self.lines = simpleSplit(text, *self.font, maxWidth=self.width) self.height = height * len(self.lines)
def draw_text(fontSize, y): lineheight = fontSize + 5 lines = simpleSplit(txt, fontName, fontSize, maxWidth) if (len(lines) > 2): draw_text(fontSize * 0.9, y) else: lines.reverse() for line in lines: x = get_center_x_coord( stringWidth(line, fontName, fontSize)) c.setFont(fontName, fontSize) c.drawString(x, y, line) y = y + lineheight
def insert_line(text, margin=0, size=12, color=black): global ACTUAL_LINE s = ParagraphStyle('my_style') s.textColor = color s.fontSize = size s.fontName = "Helvetica" s.leftIndent = margin lines = simpleSplit(text, "Helvetica", size, aW - 25 * mm) for line in lines: p = Paragraph(line, s) p.wrapOn(pdf_file, aW, aH) p.drawOn(pdf_file, 10 * mm, ACTUAL_LINE * mm) ACTUAL_LINE -= 9
def draw_constrained_text(self, text, style, canvas, x, y, w, h, border=False): fontSize = style.fontSize from reportlab.pdfbase.pdfmetrics import stringWidth from reportlab.lib.utils import simpleSplit # while stringWidth(text, style.fontName, fontSize) > w: # fontSize -= 1 # while len(simpleSplit(text, style.fontName, fontSize, w)) > num_lines: # fontSize -= 1 if style.wordWrap == 'CJK': while stringWidth(text, style.fontName, fontSize) > w: fontSize -= 1 height = fontSize lines = [text] else: height = h + 1 while height > h: # print(stringWidth(text, style.fontName, fontSize), w) lines = simpleSplit(text, style.fontName, fontSize, w) height = fontSize * len(lines) # print(height, h) fontSize -= 1 fontSize += 1 # print('H: ', h, height) y_offset = (h - height) / 2 if border: canvas.rect(x, y, w, h, stroke=1, fill=0) # outer border canvas.rect(x, y + y_offset, w, height, stroke=1, fill=0) lines.reverse() for line in lines: textobject = canvas.beginText() textobject.setTextOrigin(x, y + y_offset) textobject.setFont(style.fontName, fontSize) # print(style.textColor, str(style.textColor)) textobject.setFillColorRGB(*normalizeRGB(style.textColor)) #textobject.setCharSpace(1.5) textobject.textLine(line) canvas.drawText(textobject) y_offset += fontSize
def normalize_string(to_draw, font, size, max_width): """문자열을 draw_strings 함수에서 사용할 수 있게 정규화한다.""" # 리스트나 튜플로 들어오면 그대로 반환하면 된다. if isinstance(to_draw, (list, tuple)): strings = to_draw # 문자열로 들어오면 최대 길이에 맞게 쪼갠다. elif isinstance(to_draw, str): strings = simpleSplit(to_draw, font, size, max_width) else: assert False return strings
def setHeader(self): """ sets all the header information per page, adds Title and tile bar, aligned on the top center of the page """ showLogoWidth = self.setShowLogo() showLogoWidth = showLogoWidth + 5 if showLogoWidth else 0 # add 5 for padding if show logo exists self.canvas.setLineWidth(width=1) self.canvas.setFillColor(lightslategray) self.canvas.setStrokeColor(black) self.canvas.rect(self.marginSize + showLogoWidth, (self.pageHeight-self.header), (self.pageWidth-(self.marginSize*2)) - showLogoWidth, self.marginSize, fill=True, stroke=True) # header text self.canvas.setFillColor(black) titleSplit = simpleSplit(self.title, self.fontType, 16, (self.pageWidth-(self.marginSize*2)) - showLogoWidth) self.canvas.setFont(self.fontType, 16) self.canvas.drawString((self.marginSize*1.25) + showLogoWidth, self.pageHeight - (self.marginSize*1.125), titleSplit[0])
def computeSize(self): # the thing will draw in its own coordinate system self._lineWidths = [] topPadding = self.topPadding leftPadding = self.leftPadding rightPadding = self.rightPadding bottomPadding = self.bottomPadding self._lines = simpleSplit(self._text, self.fontName, self.fontSize, self.maxWidth) if not self.width: self._width = leftPadding + rightPadding if self._lines: self._lineWidths = [stringWidth(line, self.fontName, self.fontSize) for line in self._lines] self._width += max(self._lineWidths) else: self._width = self.width if self.useAscentDescent: self._ascent, self._descent = getAscentDescent(self.fontName, self.fontSize) self._baselineRatio = self._ascent / (self._ascent - self._descent) else: self._baselineRatio = 1 / 1.2 if self.leading: self._leading = self.leading elif self.useAscentDescent: self._leading = self._ascent - self._descent else: self._leading = self.fontSize * 1.2 self._height = self.height or (self._leading * len(self._lines) + topPadding + bottomPadding) self._ewidth = self._width - leftPadding - rightPadding self._eheight = self._height - topPadding - bottomPadding boxAnchor = self._getBoxAnchor() if boxAnchor in ["n", "ne", "nw"]: self._top = -topPadding elif boxAnchor in ["s", "sw", "se"]: self._top = self._height - topPadding else: self._top = 0.5 * self._eheight self._bottom = self._top - self._eheight if boxAnchor in ["ne", "e", "se"]: self._left = leftPadding - self._width elif boxAnchor in ["nw", "w", "sw"]: self._left = leftPadding else: self._left = -self._ewidth * 0.5 self._right = self._left + self._ewidth
def text(self, text, width=None, height=None, left=0, bottom=0, top=None, right=None, style=None): ''' add a text/paragraph to canvas ''' self.saveState() style = getSampleStyleSheet()['Normal'] if style==None else style p = Paragraph(text,style) width = checkPercent(width, self.width) height = checkPercent(height, self.height) width = stringWidth(p.getPlainText(),style.fontName, style.fontSize)+1 if width==None else width height = style.leading*len(simpleSplit(p.getPlainText(), style.fontName, style.fontSize, width)) if height==None else height width = self.width if width > self.width else width width, height = p.wrap(width, height) x,y = self.placement(width, height, left, bottom, top, right) p.drawOn(self,x,y) self.restoreState()
def __set_header(self): """__set_header will set the header """ self.canvas.setFont(self.fontType, 8) self.canvas.setFillColorRGB(.68, .68, .68) self.canvas.rect( self.margin_size, (self.page_height - self.full_header), (self.page_width - (self.margin_size * 2)), self.header, fill=True, stroke=True) # header text self.canvas.setFillColor('black') title_split = simpleSplit( self.title, self.fontType, 8, (self.page_width - (self.margin_size * 2))) self.canvas.drawString( (self.margin_size * 1.25), self.page_height - self.margin_header - .75 * self.header, title_split[0])
def wrappedTextBox(canvas, text, boxSize, fontName, fontSize): c.saveState() lineHeight = getTextHeight(fontName, fontSize) lines = simpleSplit(args.text, fontName, fontSize, textWidth) totalHeight = len(lines) * lineHeight if totalHeight > boxSize[1]: raise RuntimeError("ERROR: Text is too big") # center text vertically c.translate(0, (boxSize[1] - totalHeight) / 2 + totalHeight - lineHeight) # print each line for i in range(len(lines)): c.drawString(0, -lineHeight * i, lines[i]) c.restoreState()
def generate_pdf(opts, notes): outfile = os.path.join(opts.outdir, 'out.pdf') tallest_note = -1 for n in notes: lines = simpleSplit(n, opts.font, opts.font_size, opts.note_width) tallest_note = max(tallest_note, len(lines)) note_height = ((tallest_note + 1) * opts.leading) + (opts.notepadding * 2) s = ParagraphStyle('note') s.fontName = opts.font s.textColor = 'black' s.alignment = TA_LEFT s.fontSize = opts.font_size s.leading = opts.leading img_w, img_h = opts.pagesize pagesize = (img_w, img_h + note_height) c = canvas.Canvas(outfile, pagesize=pagesize) c.setStrokeColorRGB(0, 0, 0) for slide, note in slides_and_notes(opts, notes): c.setFillColor(HexColor('#ffffff')) c.rect(0, 0, img_w, img_h + note_height, fill=1) c.drawImage(slide, 0, note_height, img_w, img_h, preserveAspectRatio=True) c.line(0, note_height, img_w, note_height) if note: p = Paragraph(note.replace('\n', '<br/>'), s) p.wrapOn(c, opts.note_width, note_height) p.breakLines(opts.note_width) p.drawOn(c, opts.notepadding, note_height - opts.notepadding) c.showPage() c.save()
def draw_constrained_text(self, text, style, canvas, x, y, w, h, border=False): fontSize = style.fontSize from reportlab.pdfbase.pdfmetrics import stringWidth from reportlab.lib.utils import simpleSplit # while stringWidth(text, style.fontName, fontSize) > w: # fontSize -= 1 # while len(simpleSplit(text, style.fontName, fontSize, w)) > num_lines: # fontSize -= 1 if style.wordWrap == 'CJK': while stringWidth(text, style.fontName, fontSize) > w: fontSize -= 1 height = fontSize lines = [text] else: height = h + 1 while height > h: # print(stringWidth(text, style.fontName, fontSize), w) lines = simpleSplit(text, style.fontName, fontSize, w) height = fontSize * len(lines) # print(height, h) fontSize -= 1 fontSize += 1 # print('H: ', h, height) y_offset = (h - height)/2 if border: canvas.rect(x, y, w, h, stroke=1, fill=0) # outer border canvas.rect(x, y+y_offset, w, height, stroke=1, fill=0) lines.reverse() for line in lines: textobject = canvas.beginText() textobject.setTextOrigin(x, y+y_offset) textobject.setFont(style.fontName, fontSize) # print(style.textColor, str(style.textColor)) textobject.setFillColorRGB(*normalizeRGB(style.textColor)) #textobject.setCharSpace(1.5) textobject.textLine(line) canvas.drawText(textobject) y_offset += fontSize
def addText(self, box): x, y, width, height = box.getBoundsPrintSize(self.page_data.resolution) text = self.canvas.beginText() # Make the text transparent if we are not # creating a PDF from scratch if not self._from_scratch: text.setTextRenderMode(3) text.setTextOrigin(x * units.inch, (self.page_data.height - y) * units.inch) text.setCharSpace(box.text_data.letter_space) text.setLeading(box.text_data.line_space + box.text_data.size) text.moveCursor(0, box.text_data.size) #todo: efficiently add the required font self.canvas.setFontSize(box.text_data.size) if not box.text: return lines = simpleSplit(box.text, self.canvas._fontname, box.text_data.size, box.width) text.textLines('\n'.join(lines)) self.canvas.drawText(text)
def addText(self, box): x, y, width, height = box.getBoundsPrintSize(self.page_data.resolution) text = self.canvas.beginText() # Make the text transparent if we are not # creating a PDF from scratch if not self._from_scratch: text.setTextRenderMode(3) text.setTextOrigin(x * units.inch, (self.page_data.height - y) * units.inch) text.setCharSpace(box.text_data.letter_space) text.setLeading(box.text_data.line_space + box.text_data.size) text.moveCursor(0, box.text_data.size) #todo: efficiently add the required font self.canvas.setFontSize(box.text_data.size) lines = simpleSplit(box.text, self.canvas._fontname, box.text_data.size, box.width) text.textLines('\n'.join(lines)) self.canvas.drawText(text)
def applyStyle(row, font, colspacing): tmpRow = [] for i, cell in enumerate(row): for fontsize in [8, 7, 6, 5]: lines = simpleSplit(str(cell), font, fontsize, colspacing[i]) if len(lines) < 3 and ((len(lines) * fontsize * 1.2)) < 19: style = ParagraphStyle( name='normal', alignment=1, leading=fontsize, # leftIndent=0, # borderPadding=0, # rightIndent=0, # spaceBefore=0, # spaceAfter=0, wordWrap=None, fontSize=fontsize) break tmpRow.append(Paragraph(str(cell), style)) return tmpRow
def draw_note_page(self, c): if self.style.notepage and self.note.strip() != '': fnt_size = self.style.notepage_font_size wrk_widt = self.width - self.style.notepage_margin_left - self.style.notepage_margin_right fnt_name = self.style.notepage_font_name lines = [a for b in [[''] if s == '' else simpleSplit(s, fnt_name, fnt_size, wrk_widt) for s in self.note.split(sep='\n')] for a in b] lin_heig = self.style.notepage_line_height mar_left = self.style.notepage_margin_left pos = self.height - self.style.notepage_margin_top c.setFont(self.style.titlepage_author_font_name, fnt_size) pags = 0 for line in lines: pos -= lin_heig if pos <= self.style.notepage_margin_bottom: c.showPage() c.setFont(self.style.titlepage_author_font_name, fnt_size) pags += 1 pos = self.height - self.style.notepage_margin_top - lin_heig c.drawString(mar_left, pos, line) c.showPage() pags += 1 if pags % 2 == 1: c.showPage()
def wrappedTextBox(canvas, text, boxSize, fontName, fontSize): c.saveState() texto = re.sub("(.{40})", "\\1\n", args.text, 0, re.DOTALL) now = datetime.datetime.now() formattedDate = now.strftime("%d/%m/%Y-%H:%M:%S") texto += '\n' texto += formattedDate lineHeight = getTextHeight(fontName, fontSize) lines = simpleSplit(texto, fontName, fontSize, textWidth) totalHeight = len(lines) * lineHeight if totalHeight > boxSize[1]: raise RuntimeError("ERROR: Text is too big") # center text vertically c.translate(0, (boxSize[1] - totalHeight) / 2 + totalHeight - lineHeight) # print each line for i in range(len(lines)): c.drawString(0, -lineHeight * i, lines[i]) c.restoreState()
def computeSize(self): # the thing will draw in its own coordinate system self._lineWidths = [] self._lines = simpleSplit(self._text, self.fontName, self.fontSize, self.maxWidth) if not self.width: self._width = self.leftPadding + self.rightPadding if self._lines: self._lineWidths = [ stringWidth(line, self.fontName, self.fontSize) for line in self._lines ] self._width += max(self._lineWidths) else: self._width = self.width self._getBaseLineRatio() if self.leading: self._leading = self.leading elif self.useAscentDescent: self._leading = self._ascent - self._descent else: self._leading = self.fontSize * 1.2 self._computeSizeEnd(self._leading * len(self._lines))
def text2paragraph(text): #TODO If you dont find an effect, still work on the description #TODO Icons can also be mentioned in the description --> No because Golden would change to emoji font_file = 'font/Symbola_hint.ttf' # font_file = 'font/NotoSans-Regular.ttf' # font_file = 'font/NotoEmoji-Regular.ttf' # font_file = 'font/OpenSansEmoji.ttf' # open_font = TTFont('OpenSansEmoji', font_file) # emoji_font = TTFont('Noto Emoji', font_file) symbola_font = TTFont('Symbola', font_file) # noto_font = TTFont('Noto Sans', font_file) pdfmetrics.registerFont(symbola_font) # pdfmetrics.registerFont(emoji_font) # pdfmetrics.registerFont(open_font) # t = text.replace("@truWorldControl", "").replace("#fakenewz", "").strip() t = text t = re.sub("(?i)@truworldcontrol", "", t) t = re.sub("(?i)#fakenewz", "", t) t = t.strip() t = '\n'.join([x for x in t.splitlines() if x.strip()]) # t = worldcontrol[2].text style_desc = getSampleStyleSheet() style_desc = style_desc["BodyText"] style_desc.alignment = TA_LEFT # style_desc.fontName = 'Noto Emoji' # style_desc.spaceAfter = 30 style_effect = getSampleStyleSheet() style_effect = style_effect["BodyText"] # style_effect.fontSize = 16 # style_effect.fontName = 'Noto Emoji' style_effect.borderPadding = 2 style_effect.alignment = TA_CENTER style_effect.borderWidth = 1 style_effect.borderColor = '#000000' # effect = re.search("\[(.*?)\]", t) r = [] p_desc = [] p_effect = [] # Needs to be refactored if t.find("[")!=-1: desc = t[0:t.find("[")].strip() effect = t[t.find("[")+1:t.find("]")].upper() effect_emoji = replace_arrows(effect) effect_emoji = replace_icon_names(effect_emoji) effect_emoji = replace_emoji(effect_emoji, style_effect) effect_emoji = effect_emoji.replace("\n", "<br />") p_effect = Paragraph(effect_emoji, style_effect) else: desc = t effect = '_' p_effect = Paragraph(effect, style_effect) desc_emoji = replace_emoji(desc, style_desc) if desc_emoji.find("\n")!=-1: d = desc_emoji.split("\n") d[0] = "<u>" + d[0] + "</u>" desc_emoji = "<br />".join(d) lines_desc = simpleSplit(desc, 'Helvetica', 12, 6.5*cm) lines_effect = simpleSplit(effect, 'Helvetica', 12, 6.5*cm) lineSpacing = 3.88*cm/(len(lines_desc) + len(lines_effect)) - 3 style_desc.leading = lineSpacing p_desc = Paragraph(desc_emoji, style_desc) r.append(p_desc) if p_effect: r.append(p_effect) return(r)
def break_lines(text, aW): # simpleSplit calculates how reportlab will break up the lines for # display in a paragraph, by using width/fontsize. return simpleSplit(text, style.fontName, style.fontSize, aW)
def split_text(canvas, text, width): return simpleSplit(text, canvas._fontname, canvas._fontsize, width)
def drawReciboCaixa(self, boletoDados, x, y): self.pdfCanvas.saveState() self.pdfCanvas.translate(x * mm, y * mm) # De baixo para cima posicao 0,0 esta no canto inferior esquerdo self.pdfCanvas.setFont('Helvetica', self.fontSizeTitle) y = 1.5 * self.heightLine self.pdfCanvas.drawRightString( self.width, (1.5 * self.heightLine) + self.deltaTitle - 1, 'Autenticação Mecânica / Ficha de Compensação') # Primeira linha depois do codigo de barra y += self.heightLine self.pdfCanvas.setLineWidth(2) self._horizontalLine(0, y, self.width) self.pdfCanvas.drawString(self.width - (45 * mm) + self.space, y + self.space, 'Código de baixa') self.pdfCanvas.drawString(0, y + self.space, 'Sacador / Avalista') y += self.heightLine self.pdfCanvas.drawString(0, y + self.deltaTitle, 'Sacado') sacado = boletoDados.sacado # Linha grossa dividindo o Sacado y += self.heightLine self.pdfCanvas.setLineWidth(2) self._horizontalLine(0, y, self.width) self.pdfCanvas.setFont('Helvetica', self.fontSizeValue) for i in range(len(sacado)): self.pdfCanvas.drawString(15 * mm, (y - 10) - (i * self.deltaFont), sacado[i]) self.pdfCanvas.setFont('Helvetica', self.fontSizeTitle) # Linha vertical limitando todos os campos da direita self.pdfCanvas.setLineWidth(1) self._verticalLine(self.width - (45 * mm), y, 9 * self.heightLine) self.pdfCanvas.drawString(self.width - (45 * mm) + self.space, y + self.deltaTitle, '(=) Valor cobrado') # Campos da direita y += self.heightLine self._horizontalLine(self.width - (45 * mm), y, 45 * mm) self.pdfCanvas.drawString(self.width - (45 * mm) + self.space, y + self.deltaTitle, '(+) Outros acréscimos') y += self.heightLine self._horizontalLine(self.width - (45 * mm), y, 45 * mm) self.pdfCanvas.drawString(self.width - (45 * mm) + self.space, y + self.deltaTitle, '(+) Mora/Multa') y += self.heightLine self._horizontalLine(self.width - (45 * mm), y, 45 * mm) self.pdfCanvas.drawString(self.width - (45 * mm) + self.space, y + self.deltaTitle, '(-) Outras deduções') y += self.heightLine self._horizontalLine(self.width - (45 * mm), y, 45 * mm) self.pdfCanvas.drawString(self.width - (45 * mm) + self.space, y + self.deltaTitle, '(-) Descontos/Abatimentos') self.pdfCanvas.drawString(0, y + self.deltaTitle, 'Instruções') self.pdfCanvas.setFont('Helvetica', self.fontSizeValue) instrucoes = boletoDados.instrucoes[:7] for i in range(len(instrucoes)): parts = utils.simpleSplit(instrucoes[i], 'Helvetica', 9, self.width - 45 * mm) if not parts: parts = [' '] self.pdfCanvas.drawString(2 * self.space, y - (i * self.deltaFont), parts[0]) self.pdfCanvas.setFont('Helvetica', self.fontSizeTitle) # Linha horizontal com primeiro campo Uso do Banco y += self.heightLine self._horizontalLine(0, y, self.width) self.pdfCanvas.drawString(0, y + self.deltaTitle, 'Uso do banco') self._verticalLine((30) * mm, y, 2 * self.heightLine) self.pdfCanvas.drawString((30 * mm) + self.space, y + self.deltaTitle, 'Carteira') self._verticalLine((30 + 20) * mm, y, self.heightLine) self.pdfCanvas.drawString(((30 + 20) * mm) + self.space, y + self.deltaTitle, 'Espécie') self._verticalLine((30 + 20 + 20) * mm, y, 2 * self.heightLine) self.pdfCanvas.drawString(((30 + 40) * mm) + self.space, y + self.deltaTitle, 'Quantidade') self._verticalLine((30 + 20 + 20 + 20 + 20) * mm, y, 2 * self.heightLine) self.pdfCanvas.drawString(((30 + 40 + 40) * mm) + self.space, y + self.deltaTitle, 'Valor') self.pdfCanvas.drawString(self.width - (45 * mm) + self.space, y + self.deltaTitle, '(=) Valor documento') self.pdfCanvas.setFont('Helvetica', self.fontSizeValue) self.pdfCanvas.drawString((30 * mm) + self.space, y + self.space, boletoDados.carteira) self.pdfCanvas.drawString(((30 + 20) * mm) + self.space, y + self.space, boletoDados.especie) self.pdfCanvas.drawString(((30 + 20 + 20) * mm) + self.space, y + self.space, boletoDados.quantidade) valor = self._formataValorParaExibir(boletoDados.valor) self.pdfCanvas.drawString(((30 + 20 + 20 + 20 + 20) * mm) + self.space, y + self.space, valor) valorDocumento = self._formataValorParaExibir( boletoDados.valor_documento) self.pdfCanvas.drawRightString(self.width - 2 * self.space, y + self.space, valorDocumento) self.pdfCanvas.setFont('Helvetica', self.fontSizeTitle) # Linha horizontal com primeiro campo Data documento y += self.heightLine self._horizontalLine(0, y, self.width) self.pdfCanvas.drawString(0, y + self.deltaTitle, 'Data do documento') self.pdfCanvas.drawString((30 * mm) + self.space, y + self.deltaTitle, 'N. do documento') self.pdfCanvas.drawString(((30 + 40) * mm) + self.space, y + self.deltaTitle, 'Espécie doc') self._verticalLine((30 + 20 + 20 + 20) * mm, y, self.heightLine) self.pdfCanvas.drawString(((30 + 40 + 20) * mm) + self.space, y + self.deltaTitle, 'Aceite') self.pdfCanvas.drawString(((30 + 40 + 40) * mm) + self.space, y + self.deltaTitle, 'Data processamento') self.pdfCanvas.drawString(self.width - (45 * mm) + self.space, y + self.deltaTitle, 'Nosso número') self.pdfCanvas.setFont('Helvetica', self.fontSizeValue) self.pdfCanvas.drawString( 0, y + self.space, boletoDados.data_documento.strftime('%d/%m/%Y')) self.pdfCanvas.drawString((30 * mm) + self.space, y + self.space, boletoDados.numero_documento) self.pdfCanvas.drawString(((30 + 40) * mm) + self.space, y + self.space, boletoDados.especie_documento) self.pdfCanvas.drawString(((30 + 40 + 20) * mm) + self.space, y + self.space, boletoDados.aceite) self.pdfCanvas.drawString( ((30 + 40 + 40) * mm) + self.space, y + self.space, boletoDados.data_processamento.strftime('%d/%m/%Y')) self.pdfCanvas.drawRightString(self.width - 2 * self.space, y + self.space, boletoDados.format_nosso_numero()) self.pdfCanvas.setFont('Helvetica', self.fontSizeTitle) # Linha horizontal com primeiro campo Cedente y += self.heightLine self._horizontalLine(0, y, self.width) self.pdfCanvas.drawString(0, y + self.deltaTitle, 'Cedente') self.pdfCanvas.drawString(self.width - (45 * mm) + self.space, y + self.deltaTitle, 'Agência/Código cedente') self.pdfCanvas.setFont('Helvetica', self.fontSizeValue) self.pdfCanvas.drawString(0, y + self.space, boletoDados.cedente[0]) self.pdfCanvas.drawRightString(self.width - 2 * self.space, y + self.space, boletoDados.agencia_conta) self.pdfCanvas.setFont('Helvetica', self.fontSizeTitle) # Linha horizontal com primeiro campo Local de Pagamento y += self.heightLine self._horizontalLine(0, y, self.width) self.pdfCanvas.drawString(0, y + self.deltaTitle, 'Local de pagamento') self.pdfCanvas.drawString(self.width - (45 * mm) + self.space, y + self.deltaTitle, 'Vencimento') self.pdfCanvas.setFont('Helvetica', self.fontSizeValue) self.pdfCanvas.drawString(0, y + self.space, boletoDados.local_pagamento) self.pdfCanvas.drawRightString( self.width - 2 * self.space, y + self.space, boletoDados.data_vencimento.strftime('%d/%m/%Y')) self.pdfCanvas.setFont('Helvetica', self.fontSizeTitle) # Linha grossa com primeiro campo logo tipo do banco self.pdfCanvas.setLineWidth(3) y += self.heightLine self._horizontalLine(0, y, self.width) self.pdfCanvas.setLineWidth(2) self._verticalLine(40 * mm, y, self.heightLine) # Logo Tipo self._verticalLine(60 * mm, y, self.heightLine) # Numero do Banco if boletoDados.logo_image_path: self.pdfCanvas.drawImage(boletoDados.logo_image_path, 0, y + self.space + 1, 40 * mm, self.heightLine, preserveAspectRatio=True, anchor='sw') self.pdfCanvas.setFont('Helvetica-Bold', 18) self.pdfCanvas.drawCentredString(50 * mm, y + 2 * self.space, boletoDados.codigo_dv_banco) self.pdfCanvas.setFont('Helvetica-Bold', 10) self.pdfCanvas.drawRightString(self.width, y + 2 * self.space, boletoDados.linha_digitavel) # Codigo de barras self._codigoBarraI25(boletoDados.barcode, 2 * self.space, 0) self.pdfCanvas.restoreState() return self.width, (y + self.heightLine) / mm
def myCV(s, fontName="Helvetica", fontSize=10, maxWidth=72): return "\n".join(simpleSplit(s, fontName, fontSize, maxWidth))
def betterSplit(string, font_name, font_size, width): r = [ a for b in [ [''] if s == '' else simpleSplit(s, font_name, font_size, width) for s in string.split(sep='\n') ] for a in b ] if r == ['']: return [] else: return r
def drawReciboSacadoCanhoto(self, boletoDados, x, y): self.pdfCanvas.saveState() self.pdfCanvas.translate(x * mm, y * mm) linhaInicial = 12 # Horizontal Lines self.pdfCanvas.setLineWidth(2) self._horizontalLine(0, 0, self.widthCanhoto) self.pdfCanvas.setLineWidth(1) self._horizontalLine(0, (linhaInicial + 0) * self.heightLine, self.widthCanhoto) self._horizontalLine(0, (linhaInicial + 1) * self.heightLine, self.widthCanhoto) self.pdfCanvas.setLineWidth(2) self._horizontalLine(0, (linhaInicial + 2) * self.heightLine, self.widthCanhoto) # Vertical Lines self.pdfCanvas.setLineWidth(1) self._verticalLine(self.widthCanhoto - (35 * mm), (linhaInicial + 0) * self.heightLine, self.heightLine) self._verticalLine(self.widthCanhoto - (35 * mm), (linhaInicial + 1) * self.heightLine, self.heightLine) self.pdfCanvas.setFont('Helvetica-Bold', 6) self.pdfCanvas.drawRightString(self.widthCanhoto, 0 * self.heightLine + 3, 'Recibo do Sacado') # Titles self.pdfCanvas.setFont('Helvetica', 6) self.deltaTitle = self.heightLine - (6 + 1) self.pdfCanvas.drawString( self.space, (((linhaInicial + 0) * self.heightLine)) + self.deltaTitle, 'Nosso Número') self.pdfCanvas.drawString( self.widthCanhoto - (35 * mm) + self.space, (((linhaInicial + 0) * self.heightLine)) + self.deltaTitle, 'Vencimento') self.pdfCanvas.drawString( self.space, (((linhaInicial + 1) * self.heightLine)) + self.deltaTitle, 'Agência/Código Cedente') self.pdfCanvas.drawString( self.widthCanhoto - (35 * mm) + self.space, (((linhaInicial + 1) * self.heightLine)) + self.deltaTitle, 'Valor Documento') # Values self.pdfCanvas.setFont('Helvetica', 9) heighFont = 9 + 1 valorDocumento = self._formataValorParaExibir( boletoDados.valor_documento) self.pdfCanvas.drawString( self.space, (((linhaInicial + 0) * self.heightLine)) + self.space, boletoDados.format_nosso_numero()) self.pdfCanvas.drawString( self.widthCanhoto - (35 * mm) + self.space, (((linhaInicial + 0) * self.heightLine)) + self.space, boletoDados.data_vencimento.strftime('%d/%m/%Y')) self.pdfCanvas.drawString( self.space, (((linhaInicial + 1) * self.heightLine)) + self.space, boletoDados.agencia_conta) self.pdfCanvas.drawString( self.widthCanhoto - (35 * mm) + self.space, (((linhaInicial + 1) * self.heightLine)) + self.space, valorDocumento) demonstrativo = boletoDados.demonstrativo[0:12] for i in range(len(demonstrativo)): parts = utils.simpleSplit(demonstrativo[i], 'Helvetica', 9, self.widthCanhoto) self.pdfCanvas.drawString( 2 * self.space, (((linhaInicial - 1) * self.heightLine)) - (i * heighFont), parts[0]) self.pdfCanvas.restoreState() return (self.widthCanhoto / mm, ((linhaInicial + 2) * self.heightLine) / mm)
def myCV(s, fontName='Helvetica', fontSize=10, maxWidth=72): return '\n'.join(simpleSplit(s, fontName, fontSize, maxWidth))
def drawReciboCaixa(self, boletoDados, x, y): self.pdfCanvas.saveState() self.pdfCanvas.translate(x * mm, y * mm) # De baixo para cima posicao 0,0 esta no canto inferior esquerdo self.pdfCanvas.setFont('Helvetica', self.fontSizeTitle) y = 1.5 * self.heightLine self.pdfCanvas.drawRightString( self.width, (1.5 * self.heightLine) + self.deltaTitle - 1, 'Autenticação Mecânica / Ficha de Compensação') # Primeira linha depois do codigo de barra y += self.heightLine self.pdfCanvas.setLineWidth(2) self._horizontalLine(0, y, self.width) self.pdfCanvas.drawString( self.width - (45 * mm) + self.space, y + self.space, 'Código de baixa') self.pdfCanvas.drawString(0, y + self.space, 'Sacador / Avalista') y += self.heightLine self.pdfCanvas.drawString(0, y + self.deltaTitle, 'Sacado') sacado = boletoDados.sacado # Linha grossa dividindo o Sacado y += self.heightLine self.pdfCanvas.setLineWidth(2) self._horizontalLine(0, y, self.width) self.pdfCanvas.setFont('Helvetica', self.fontSizeValue) for i in range(len(sacado)): self.pdfCanvas.drawString( 15 * mm, (y - 10) - (i * self.deltaFont), sacado[i]) self.pdfCanvas.setFont('Helvetica', self.fontSizeTitle) # Linha vertical limitando todos os campos da direita self.pdfCanvas.setLineWidth(1) self._verticalLine(self.width - (45 * mm), y, 9 * self.heightLine) self.pdfCanvas.drawString( self.width - (45 * mm) + self.space, y + self.deltaTitle, '(=) Valor cobrado') # Campos da direita y += self.heightLine self._horizontalLine(self.width - (45 * mm), y, 45 * mm) self.pdfCanvas.drawString( self.width - (45 * mm) + self.space, y + self.deltaTitle, '(+) Outros acréscimos') y += self.heightLine self._horizontalLine(self.width - (45 * mm), y, 45 * mm) self.pdfCanvas.drawString( self.width - (45 * mm) + self.space, y + self.deltaTitle, '(+) Mora/Multa') y += self.heightLine self._horizontalLine(self.width - (45 * mm), y, 45 * mm) self.pdfCanvas.drawString( self.width - (45 * mm) + self.space, y + self.deltaTitle, '(-) Outras deduções') y += self.heightLine self._horizontalLine(self.width - (45 * mm), y, 45 * mm) self.pdfCanvas.drawString( self.width - (45 * mm) + self.space, y + self.deltaTitle, '(-) Descontos/Abatimentos') self.pdfCanvas.drawString( 0, y + self.deltaTitle, 'Instruções') self.pdfCanvas.setFont('Helvetica', self.fontSizeValue) instrucoes = boletoDados.instrucoes[:7] for i in range(len(instrucoes)): parts = utils.simpleSplit(instrucoes[i], 'Helvetica', 9, self.width - 45 * mm) if not parts: parts = [' '] self.pdfCanvas.drawString( 2 * self.space, y - (i * self.deltaFont), parts[0]) self.pdfCanvas.setFont('Helvetica', self.fontSizeTitle) # Linha horizontal com primeiro campo Uso do Banco y += self.heightLine self._horizontalLine(0, y, self.width) self.pdfCanvas.drawString(0, y + self.deltaTitle, 'Uso do banco') self._verticalLine((30) * mm, y, 2 * self.heightLine) self.pdfCanvas.drawString( (30 * mm) + self.space, y + self.deltaTitle, 'Carteira') self._verticalLine((30 + 20) * mm, y, self.heightLine) self.pdfCanvas.drawString( ((30 + 20) * mm) + self.space, y + self.deltaTitle, 'Espécie') self._verticalLine( (30 + 20 + 20) * mm, y, 2 * self.heightLine) self.pdfCanvas.drawString( ((30 + 40) * mm) + self.space, y + self.deltaTitle, 'Quantidade') self._verticalLine( (30 + 20 + 20 + 20 + 20) * mm, y, 2 * self.heightLine) self.pdfCanvas.drawString( ((30 + 40 + 40) * mm) + self.space, y + self.deltaTitle, 'Valor') self.pdfCanvas.drawString( self.width - (45 * mm) + self.space, y + self.deltaTitle, '(=) Valor documento') self.pdfCanvas.setFont('Helvetica', self.fontSizeValue) self.pdfCanvas.drawString( (30 * mm) + self.space, y + self.space, boletoDados.carteira) self.pdfCanvas.drawString( ((30 + 20) * mm) + self.space, y + self.space, boletoDados.especie) self.pdfCanvas.drawString( ((30 + 20 + 20) * mm) + self.space, y + self.space, boletoDados.quantidade) valor = self._formataValorParaExibir(boletoDados.valor) self.pdfCanvas.drawString( ((30 + 20 + 20 + 20 + 20) * mm) + self.space, y + self.space, valor) valorDocumento = self._formataValorParaExibir( boletoDados.valor_documento) self.pdfCanvas.drawRightString( self.width - 2 * self.space, y + self.space, valorDocumento) self.pdfCanvas.setFont('Helvetica', self.fontSizeTitle) # Linha horizontal com primeiro campo Data documento y += self.heightLine self._horizontalLine(0, y, self.width) self.pdfCanvas.drawString( 0, y + self.deltaTitle, 'Data do documento') self.pdfCanvas.drawString( (30 * mm) + self.space, y + self.deltaTitle, 'N. do documento') self.pdfCanvas.drawString( ((30 + 40) * mm) + self.space, y + self.deltaTitle, 'Espécie doc') self._verticalLine( (30 + 20 + 20 + 20) * mm, y, self.heightLine) self.pdfCanvas.drawString( ((30 + 40 + 20) * mm) + self.space, y + self.deltaTitle, 'Aceite') self.pdfCanvas.drawString( ((30 + 40 + 40) * mm) + self.space, y + self.deltaTitle, 'Data processamento') self.pdfCanvas.drawString( self.width - (45 * mm) + self.space, y + self.deltaTitle, 'Nosso número') self.pdfCanvas.setFont('Helvetica', self.fontSizeValue) self.pdfCanvas.drawString( 0, y + self.space, boletoDados.data_documento.strftime('%d/%m/%Y')) self.pdfCanvas.drawString( (30 * mm) + self.space, y + self.space, boletoDados.numero_documento) self.pdfCanvas.drawString( ((30 + 40) * mm) + self.space, y + self.space, boletoDados.especie_documento) self.pdfCanvas.drawString( ((30 + 40 + 20) * mm) + self.space, y + self.space, boletoDados.aceite) self.pdfCanvas.drawString( ((30 + 40 + 40) * mm) + self.space, y + self.space, boletoDados.data_processamento.strftime('%d/%m/%Y')) self.pdfCanvas.drawRightString( self.width - 2 * self.space, y + self.space, boletoDados.format_nosso_numero()) self.pdfCanvas.setFont('Helvetica', self.fontSizeTitle) # Linha horizontal com primeiro campo Cedente y += self.heightLine self._horizontalLine(0, y, self.width) self.pdfCanvas.drawString(0, y + self.deltaTitle, 'Cedente') self.pdfCanvas.drawString( self.width - (45 * mm) + self.space, y + self.deltaTitle, 'Agência/Código cedente') self.pdfCanvas.setFont('Helvetica', self.fontSizeValue) self.pdfCanvas.drawString(0, y + self.space, boletoDados.cedente[0]) self.pdfCanvas.drawRightString( self.width - 2 * self.space, y + self.space, boletoDados.agencia_conta) self.pdfCanvas.setFont('Helvetica', self.fontSizeTitle) # Linha horizontal com primeiro campo Local de Pagamento y += self.heightLine self._horizontalLine(0, y, self.width) self.pdfCanvas.drawString( 0, y + self.deltaTitle, 'Local de pagamento') self.pdfCanvas.drawString( self.width - (45 * mm) + self.space, y + self.deltaTitle, 'Vencimento') self.pdfCanvas.setFont('Helvetica', self.fontSizeValue) self.pdfCanvas.drawString( 0, y + self.space, boletoDados.local_pagamento) self.pdfCanvas.drawRightString( self.width - 2 * self.space, y + self.space, boletoDados.data_vencimento.strftime('%d/%m/%Y')) self.pdfCanvas.setFont('Helvetica', self.fontSizeTitle) # Linha grossa com primeiro campo logo tipo do banco self.pdfCanvas.setLineWidth(3) y += self.heightLine self._horizontalLine(0, y, self.width) self.pdfCanvas.setLineWidth(2) self._verticalLine(40 * mm, y, self.heightLine) # Logo Tipo self._verticalLine(60 * mm, y, self.heightLine) # Numero do Banco if boletoDados.logo_image_path: self.pdfCanvas.drawImage( boletoDados.logo_image_path, 0, y + self.space + 1, 40 * mm, self.heightLine, preserveAspectRatio=True, anchor='sw') self.pdfCanvas.setFont('Helvetica-Bold', 18) self.pdfCanvas.drawCentredString( 50 * mm, y + 2 * self.space, boletoDados.codigo_dv_banco) self.pdfCanvas.setFont('Helvetica-Bold', 10) self.pdfCanvas.drawRightString( self.width, y + 2 * self.space, boletoDados.linha_digitavel) # Codigo de barras self._codigoBarraI25(boletoDados.barcode, 2 * self.space, 0) self.pdfCanvas.restoreState() return self.width, (y + self.heightLine) / mm
def myCV(s,fontName='Helvetica',fontSize=10,maxWidth=72): return '\n'.join(simpleSplit(s,fontName,fontSize,maxWidth))
def drawReciboSacadoCanhoto(self, boletoDados, x, y): self.pdfCanvas.saveState() self.pdfCanvas.translate(x * mm, y * mm) linhaInicial = 12 # Horizontal Lines self.pdfCanvas.setLineWidth(2) self._horizontalLine(0, 0, self.widthCanhoto) self.pdfCanvas.setLineWidth(1) self._horizontalLine(0, (linhaInicial + 0) * self.heightLine, self.widthCanhoto) self._horizontalLine(0, (linhaInicial + 1) * self.heightLine, self.widthCanhoto) self.pdfCanvas.setLineWidth(2) self._horizontalLine(0, (linhaInicial + 2) * self.heightLine, self.widthCanhoto) # Vertical Lines self.pdfCanvas.setLineWidth(1) self._verticalLine(self.widthCanhoto - (35 * mm), (linhaInicial + 0) * self.heightLine, self.heightLine) self._verticalLine(self.widthCanhoto - (35 * mm), (linhaInicial + 1) * self.heightLine, self.heightLine) self.pdfCanvas.setFont('Helvetica-Bold', 6) self.pdfCanvas.drawRightString(self.widthCanhoto, 0 * self.heightLine + 3, 'Recibo do Sacado') # Titles self.pdfCanvas.setFont('Helvetica', 6) self.deltaTitle = self.heightLine - (6 + 1) self.pdfCanvas.drawString(self.space, (((linhaInicial + 0) * self.heightLine)) + self.deltaTitle, 'Nosso Número') self.pdfCanvas.drawString(self.widthCanhoto - (35 * mm) + self.space, (((linhaInicial + 0) * self.heightLine)) + self.deltaTitle, 'Vencimento') self.pdfCanvas.drawString(self.space, (((linhaInicial + 1) * self.heightLine)) + self.deltaTitle, 'Agência/Código Cedente') self.pdfCanvas.drawString(self.widthCanhoto - (35 * mm) + self.space, (((linhaInicial + 1) * self.heightLine)) + self.deltaTitle, 'Valor Documento') # Values self.pdfCanvas.setFont('Helvetica', 9) heighFont = 9 + 1 valorDocumento = self._formataValorParaExibir( boletoDados.valor_documento) self.pdfCanvas.drawString( self.space, (((linhaInicial + 0) * self.heightLine)) + self.space, boletoDados.format_nosso_numero()) self.pdfCanvas.drawString( self.widthCanhoto - (35 * mm) + self.space, (((linhaInicial + 0) * self.heightLine)) + self.space, boletoDados.data_vencimento.strftime('%d/%m/%Y')) self.pdfCanvas.drawString( self.space, (((linhaInicial + 1) * self.heightLine)) + self.space, boletoDados.agencia_conta) self.pdfCanvas.drawString(self.widthCanhoto - (35 * mm) + self.space, (((linhaInicial + 1) * self.heightLine)) + self.space, valorDocumento) demonstrativo = boletoDados.demonstrativo[0:12] for i in range(len(demonstrativo)): parts = utils.simpleSplit(demonstrativo[i], 'Helvetica', 9, self.widthCanhoto) self.pdfCanvas.drawString( 2 * self.space, (((linhaInicial - 1) * self.heightLine)) - (i * heighFont), parts[0]) self.pdfCanvas.restoreState() return (self.widthCanhoto / mm, ((linhaInicial + 2) * self.heightLine) / mm)
def _drawReciboCaixa(self, boletoDados, x, y): """Imprime o Recibo do Caixa :param boletoDados: Objeto com os dados do boleto a ser preenchido. Deve ser subclasse de :class:`pyboleto.data.BoletoData` :type boletoDados: :class:`pyboleto.data.BoletoData` """ self.pdfCanvas.saveState() self.pdfCanvas.translate(x, y) # De baixo para cima posicao 0,0 esta no canto inferior esquerdo self.pdfCanvas.setFont('Helvetica', self.fontSizeTitle) y = 1.5 * self.heightLine self.pdfCanvas.drawRightString( self.width, (1.5 * self.heightLine) + self.deltaTitle - 1, 'Autenticação Mecânica / Ficha de Compensação' ) # Primeira linha depois do codigo de barra y += self.heightLine self.pdfCanvas.setLineWidth(2) self.__horizontalLine(0, y, self.width) y += self.heightLine yy = y self.pdfCanvas.drawString(0, y + self.deltaTitle, 'Pagador') sacado = boletoDados.sacado # Linha grossa dividindo o Sacado y += self.heightLine self.pdfCanvas.setLineWidth(2) self.__horizontalLine(0, y, self.width) self.pdfCanvas.setFont('Helvetica', self.fontSizeValue) for i in range(len(sacado)): L = simpleSplit(sacado[i],'Helvetica',self.fontSizeValue,350) yyy = y for t in L: self.pdfCanvas.drawString( 15 * mm, (yyy - 10) - (i * self.deltaFont), t ) yyy -= self.pdfCanvas._leading self.pdfCanvas.setFont('Helvetica', self.fontSizeTitle) # Sacado documento self.pdfCanvas.drawString(self.width - (44 * mm), yy + self.deltaTitle, 'CPF/CNPJ') sacado_documento = boletoDados.sacado_documento self.pdfCanvas.setFont('Helvetica', self.fontSizeValue) self.pdfCanvas.drawString(self.width - (44 * mm), yy + self.deltaTitle - 13, sacado_documento) self.pdfCanvas.setFont('Helvetica', self.fontSizeTitle) # Linha vertical limitando todos os campos da direita self.pdfCanvas.setLineWidth(1) self.__verticalLine(self.width - (45 * mm), y, 9 * self.heightLine) self.pdfCanvas.drawString( self.width - (45 * mm) + self.space, y + self.deltaTitle, '(=) Valor cobrado' ) # Campos da direita y += self.heightLine self.__horizontalLine(self.width - (45 * mm), y, 45 * mm) self.pdfCanvas.drawString( self.width - (45 * mm) + self.space, y + self.deltaTitle, '(+) Outros acréscimos' ) y += self.heightLine self.__horizontalLine(self.width - (45 * mm), y, 45 * mm) self.pdfCanvas.drawString( self.width - (45 * mm) + self.space, y + self.deltaTitle, '(+) Mora/Multa' ) y += self.heightLine self.__horizontalLine(self.width - (45 * mm), y, 45 * mm) self.pdfCanvas.drawString( self.width - (45 * mm) + self.space, y + self.deltaTitle, '(-) Outras deduções' ) y += self.heightLine self.__horizontalLine(self.width - (45 * mm), y, 45 * mm) self.pdfCanvas.drawString( self.width - (45 * mm) + self.space, y + self.deltaTitle, '(-) Descontos/Abatimentos' ) self.pdfCanvas.drawString( 0, y + self.deltaTitle, 'Instruções' ) self.pdfCanvas.setFont('Helvetica', self.fontSizeValue) instrucoes = boletoDados.instrucoes for i in range(len(instrucoes)): self.pdfCanvas.drawString( 2 * self.space, y - (i * self.deltaFont), instrucoes[i] ) self.pdfCanvas.setFont('Helvetica', self.fontSizeTitle) # Linha horizontal com primeiro campo Uso do Banco y += self.heightLine self.__horizontalLine(0, y, self.width) self.pdfCanvas.drawString(0, y + self.deltaTitle, 'Uso do banco') self.__verticalLine((30) * mm, y, 2 * self.heightLine) self.pdfCanvas.drawString( (30 * mm) + self.space, y + self.deltaTitle, 'Carteira' ) self.__verticalLine((30 + 20) * mm, y, self.heightLine) self.pdfCanvas.drawString( ((30 + 20) * mm) + self.space, y + self.deltaTitle, 'Espécie' ) self.__verticalLine( (30 + 20 + 20) * mm, y, 2 * self.heightLine ) self.pdfCanvas.drawString( ((30 + 40) * mm) + self.space, y + self.deltaTitle, 'Quantidade' ) self.__verticalLine( (30 + 20 + 20 + 20 + 20) * mm, y, 2 * self.heightLine) self.pdfCanvas.drawString( ((30 + 40 + 40) * mm) + self.space, y + self.deltaTitle, 'Valor') self.pdfCanvas.drawString( self.width - (45 * mm) + self.space, y + self.deltaTitle, '(=) Valor documento' ) self.pdfCanvas.setFont('Helvetica', self.fontSizeValue) self.pdfCanvas.drawString( (30 * mm) + self.space, y + self.space, boletoDados.carteira ) self.pdfCanvas.drawString( ((30 + 20) * mm) + self.space, y + self.space, boletoDados.especie ) self.pdfCanvas.drawString( ((30 + 20 + 20) * mm) + self.space, y + self.space, boletoDados.quantidade ) valor = self._formataValorParaExibir(boletoDados.valor) self.pdfCanvas.drawString( ((30 + 20 + 20 + 20 + 20) * mm) + self.space, y + self.space, valor ) valorDocumento = self._formataValorParaExibir( boletoDados.valor_documento ) self.pdfCanvas.drawRightString( self.width - 2 * self.space, y + self.space, valorDocumento ) self.pdfCanvas.setFont('Helvetica', self.fontSizeTitle) # Linha horizontal com primeiro campo Data documento y += self.heightLine self.__horizontalLine(0, y, self.width) self.pdfCanvas.drawString( 0, y + self.deltaTitle, 'Data do documento' ) self.pdfCanvas.drawString( (30 * mm) + self.space, y + self.deltaTitle, 'N. do documento' ) self.pdfCanvas.drawString( ((30 + 40) * mm) + self.space, y + self.deltaTitle, 'Espécie doc' ) self.__verticalLine( (30 + 20 + 20 + 20) * mm, y, self.heightLine ) self.pdfCanvas.drawString( ((30 + 40 + 20) * mm) + self.space, y + self.deltaTitle, 'Aceite' ) self.pdfCanvas.drawString( ((30 + 40 + 40) * mm) + self.space, y + self.deltaTitle, 'Data processamento' ) self.pdfCanvas.drawString( self.width - (45 * mm) + self.space, y + self.deltaTitle, 'Nosso número' ) self.pdfCanvas.setFont('Helvetica', self.fontSizeValue) self.pdfCanvas.drawString( 0, y + self.space, boletoDados.data_documento.strftime('%d/%m/%Y') ) self.pdfCanvas.drawString( (30 * mm) + self.space, y + self.space, boletoDados.numero_documento ) self.pdfCanvas.drawString( ((30 + 40) * mm) + self.space, y + self.space, boletoDados.especie_documento ) self.pdfCanvas.drawString( ((30 + 40 + 20) * mm) + self.space, y + self.space, boletoDados.aceite ) self.pdfCanvas.drawString( ((30 + 40 + 40) * mm) + self.space, y + self.space, boletoDados.data_processamento.strftime('%d/%m/%Y') ) self.pdfCanvas.drawRightString( self.width - 2 * self.space, y + self.space, boletoDados.format_nosso_numero() ) self.pdfCanvas.setFont('Helvetica', self.fontSizeTitle) # Linha horizontal com primeiro campo Cedente y += self.heightLine self.__horizontalLine(0, y, self.width) self.pdfCanvas.drawString(0, y + self.deltaTitle, 'Beneficiário') self.__verticalLine( (30 + 20 + 20 + 20 + 20) * mm, y, self.heightLine ) self.pdfCanvas.drawString( ((30 + 40 + 40) * mm) + self.space, y + self.deltaTitle, 'CPF/CNPJ Beneficiário' ) self.pdfCanvas.drawString( self.width - (45 * mm) + self.space, y + self.deltaTitle, 'Agência/Código do Beneficiário' ) self.pdfCanvas.setFont('Helvetica', self.fontSizeValue) self.pdfCanvas.drawString(0, y + self.space, boletoDados.cedente) self.pdfCanvas.drawString( ((30 + 40 + 40) * mm) + self.space, y + self.space, boletoDados.cedente_documento ) self.pdfCanvas.drawRightString( self.width - 2 * self.space, y + self.space, boletoDados.agencia_conta_cedente ) self.pdfCanvas.setFont('Helvetica', self.fontSizeTitle) # Linha horizontal com primeiro campo Local de Pagamento y += self.heightLine self.__horizontalLine(0, y, self.width) self.pdfCanvas.drawString( 0, y + self.deltaTitle, 'Local de pagamento' ) self.pdfCanvas.drawString( self.width - (45 * mm) + self.space, y + self.deltaTitle, 'Vencimento' ) self.pdfCanvas.setFont('Helvetica', self.fontSizeValue) self.pdfCanvas.drawString( 0, y + self.space, boletoDados.local_pagamento ) self.pdfCanvas.drawRightString( self.width - 2 * self.space, y + self.space, boletoDados.data_vencimento.strftime('%d/%m/%Y') ) self.pdfCanvas.setFont('Helvetica', self.fontSizeTitle) # Linha grossa com primeiro campo logo tipo do banco self.pdfCanvas.setLineWidth(3) y += self.heightLine self.__horizontalLine(0, y, self.width) self.pdfCanvas.setLineWidth(2) self.__verticalLine(40 * mm, y, self.heightLine) # Logo Tipo self.__verticalLine(60 * mm, y, self.heightLine) # Numero do Banco if boletoDados.logo_image: logo_image_path = self._load_image(boletoDados.logo_image) self.pdfCanvas.drawImage( logo_image_path, 0, y + self.space + 1, 40 * mm, self.heightLine, preserveAspectRatio=True, anchor='sw' ) self.pdfCanvas.setFont('Helvetica-Bold', 18) self.pdfCanvas.drawCentredString( 50 * mm, y + 2 * self.space, boletoDados.codigo_dv_banco ) self.pdfCanvas.setFont('Helvetica-Bold', 11.5) self.pdfCanvas.drawRightString( self.width, y + 2 * self.space, boletoDados.linha_digitavel ) # Codigo de barras self._codigoBarraI25(boletoDados.barcode, 2 * self.space, 0) self.pdfCanvas.restoreState() return self.width, (y + self.heightLine)