def elem2frags(self, elem, style): #print "elem2frags(%s)" % elem frag = ParaFrag() frag.text = '' frag.fontName = style.fontName frag.fontSize = style.fontSize frag.textColor = style.textColor frag.rise = style.rise frag.underline = style.underline frag.strike = 0 # added for reportlab 2.0 frag.link = None # added for reportlab 2.0 if elem.__class__ == html.CDATA: frag.text = " ".join(elem.text.split()) if elem.text.startswith(" "): frag.text = " " + frag.text if elem.text.endswith(" "): frag.text += " " #frag.text=elem.text yield frag return if elem.__class__ == html.BR: #frag.text='\n' frag.lineBreak = True yield frag return assert hasattr(elem, 'content') if elem.__class__ in (html.EM, html.I): family, bold, italic = ps2tt(frag.fontName) frag.fontName = tt2ps(family, bold, 1) #frag.fontName=frag.fontName+"-Italic" elif elem.__class__ == html.TT: family, bold, italic = ps2tt(frag.fontName) frag.fontName = tt2ps("Courier", bold, italic) elif elem.__class__ == html.B: family, bold, italic = ps2tt(frag.fontName) frag.fontName = tt2ps(family, 1, italic) elif elem.__class__ == html.U: frag.underline = True elif elem.__class__ == html.SUP: frag.rise = True else: raise "Cannot handle <%s> inside a paragraph" \ % elem.tag() ## for e in elem.content: ## if e.__class__ == html.CDATA: ## frag.text += e.text ## else: ## for ee in elem.content: ## for f in self.elem2frags(ee,frag): ## yield f for e in elem.content: for f in self.elem2frags(e, frag): yield f yield frag
def elem2frags(self, elem, style): # print "elem2frags(%s)" % elem frag = ParaFrag() frag.text = "" frag.fontName = style.fontName frag.fontSize = style.fontSize frag.textColor = style.textColor frag.rise = style.rise frag.underline = style.underline frag.strike = 0 # added for reportlab 2.0 frag.link = None # added for reportlab 2.0 if elem.__class__ == html.CDATA: frag.text = " ".join(elem.text.split()) if elem.text.startswith(" "): frag.text = " " + frag.text if elem.text.endswith(" "): frag.text += " " # frag.text=elem.text yield frag return if elem.__class__ == html.BR: # frag.text='\n' frag.lineBreak = True yield frag return assert hasattr(elem, "content") if elem.__class__ in (html.EM, html.I): family, bold, italic = ps2tt(frag.fontName) frag.fontName = tt2ps(family, bold, 1) # frag.fontName=frag.fontName+"-Italic" elif elem.__class__ == html.TT: family, bold, italic = ps2tt(frag.fontName) frag.fontName = tt2ps("Courier", bold, italic) elif elem.__class__ == html.B: family, bold, italic = ps2tt(frag.fontName) frag.fontName = tt2ps(family, 1, italic) elif elem.__class__ == html.U: frag.underline = True elif elem.__class__ == html.SUP: frag.rise = True else: raise "Cannot handle <%s> inside a paragraph" % elem.tag() ## for e in elem.content: ## if e.__class__ == html.CDATA: ## frag.text += e.text ## else: ## for ee in elem.content: ## for f in self.elem2frags(ee,frag): ## yield f for e in elem.content: for f in self.elem2frags(e, frag): yield f yield frag
def testParsing(self): fontName = getAFont() fontNameBI = tt2ps(fontName,1,1) stySTD = ParagraphStyle('STD',fontName=fontName) styBI = ParagraphStyle('BI',fontName=fontNameBI) self.assertRaises(ValueError,Paragraph,'aaaa <b><i>bibibi</b></i> ccccc',stySTD) self.assertRaises(ValueError,Paragraph,'AAAA <b><i>BIBIBI</b></i> CCCCC',styBI)
def handle_data(self,data): "Creates an intermediate representation of string segments." frag = copy.copy(self._stack[-1]) if hasattr(frag,'cbDefn'): if data!='': syntax_error('Only <onDraw> tag allowed') else: # if sub and super are both on they will cancel each other out if frag.sub == 1 and frag.super == 1: frag.sub = 0 frag.super = 0 if frag.sub: frag.rise = -frag.fontSize*subFraction frag.fontSize = max(frag.fontSize-sizeDelta,3) elif frag.super: frag.rise = frag.fontSize*superFraction frag.fontSize = max(frag.fontSize-sizeDelta,3) if frag.greek: frag.fontName = 'symbol' # bold, italic, and underline x = frag.fontName = tt2ps(frag.fontName,frag.bold,frag.italic) #save our data frag.text = data if hasattr(frag,'isBullet'): delattr(frag,'isBullet') self.bFragList.append(frag) else: self.fragList.append(frag)
def handle_data(self, data): "Creates an intermediate representation of string segments." #The old parser would only 'see' a string after all entities had #been processed. Thus, 'Hello ™ World' would emerge as one #fragment. HTMLParser processes these separately. We want to ensure #that successive calls like this are concatenated, to prevent too many #fragments being created. frag = copy.copy(self._stack[-1]) if hasattr(frag, 'cbDefn'): kind = frag.cbDefn.kind if data: self._syntax_error('Only empty <%s> tag allowed' % kind) elif hasattr(frag, '_selfClosingTag'): if data != '': self._syntax_error('No content allowed in %s tag' % frag._selfClosingTag) return else: # if sub and sup are both on they will cancel each other out if frag.sub == 1 and frag.sup == 1: frag.sub = 0 frag.sup = 0 if frag.sub: frag.rise = -fontSizeNormalize(frag, 'supr', frag.fontSize * subFraction) frag.fontSize = fontSizeNormalize( frag, 'sups', frag.fontSize - min(sizeDelta, 0.2 * frag.fontSize)) elif frag.sup: frag.rise = fontSizeNormalize(frag, 'supr', frag.fontSize * supFraction) frag.fontSize = fontSizeNormalize( frag, 'sups', frag.fontSize - min(sizeDelta, 0.2 * frag.fontSize)) if frag.greek: frag.fontName = 'symbol' data = _greekConvert(data) # bold, italic, and underline frag.fontName = tt2ps(frag.fontName, frag.bold, frag.italic) #save our data frag.text = data if hasattr(frag, 'isBullet'): delattr(frag, 'isBullet') self.bFragList.append(frag) else: self.fragList.append(frag)
def handle_data(self, data): "Creates an intermediate representation of string segments." # The old parser would only 'see' a string after all entities had # been processed. Thus, 'Hello ™ World' would emerge as one # fragment. HTMLParser processes these separately. We want to ensure # that successive calls like this are concatenated, to prevent too many # fragments being created. frag = copy.copy(self._stack[-1]) if hasattr(frag, "cbDefn"): kind = frag.cbDefn.kind if data: self._syntax_error("Only empty <%s> tag allowed" % kind) elif hasattr(frag, "_selfClosingTag"): if data != "": self._syntax_error("No content allowed in %s tag" % frag._selfClosingTag) return else: # if sub and sup are both on they will cancel each other out if frag.sub == 1 and frag.sup == 1: frag.sub = 0 frag.sup = 0 if frag.sub: frag.rise = -getattr(frag, "supr", frag.fontSize * subFraction) frag.fontSize = getattr(frag, "sups", frag.fontSize - min(sizeDelta, 0.2 * frag.fontSize)) elif frag.sup: frag.rise = getattr(frag, "supr", frag.fontSize * supFraction) frag.fontSize = getattr(frag, "sups", frag.fontSize - min(sizeDelta, 0.2 * frag.fontSize)) if frag.greek: frag.fontName = "symbol" data = _greekConvert(data) # bold, italic, and underline frag.fontName = tt2ps(frag.fontName, frag.bold, frag.italic) # save our data frag.text = data if hasattr(frag, "isBullet"): delattr(frag, "isBullet") self.bFragList.append(frag) else: self.fragList.append(frag)
def handle_data(self, data): "Creates an intermediate representation of string segments." frag = copy.copy(self._stack[-1]) if hasattr(frag, 'cbDefn'): kind = frag.cbDefn.kind if data: self._syntax_error('Only empty <%s> tag allowed' % kind) elif hasattr(frag, '_selfClosingTag'): if data != '': self._syntax_error('No content allowed in %s tag' % frag._selfClosingTag) return else: # if sub and super are both on they will cancel each other out if frag.sub == 1 and frag.super == 1: frag.sub = 0 frag.super = 0 if frag.sub: frag.rise = -frag.fontSize * subFraction frag.fontSize = max(frag.fontSize - sizeDelta, 3) elif frag.super: frag.rise = frag.fontSize * superFraction frag.fontSize = max(frag.fontSize - sizeDelta, 3) if frag.greek: frag.fontName = 'symbol' data = _greekConvert(data) # bold, italic, and underline frag.fontName = tt2ps(frag.fontName, frag.bold, frag.italic) #save our data frag.text = data if hasattr(frag, 'isBullet'): delattr(frag, 'isBullet') self.bFragList.append(frag) else: self.fragList.append(frag)
def handle_data(self,data): "Creates an intermediate representation of string segments." frag = copy.copy(self._stack[-1]) if hasattr(frag,'cbDefn'): kind = frag.cbDefn.kind if data: self._syntax_error('Only empty <%s> tag allowed' % kind) elif hasattr(frag,'_selfClosingTag'): if data!='': self._syntax_error('No content allowed in %s tag' % frag._selfClosingTag) return else: # if sub and super are both on they will cancel each other out if frag.sub == 1 and frag.super == 1: frag.sub = 0 frag.super = 0 if frag.sub: frag.rise = -frag.fontSize*subFraction frag.fontSize = max(frag.fontSize-sizeDelta,3) elif frag.super: frag.rise = frag.fontSize*superFraction frag.fontSize = max(frag.fontSize-sizeDelta,3) if frag.greek: frag.fontName = 'symbol' data = _greekConvert(data) # bold, italic, and underline frag.fontName = tt2ps(frag.fontName,frag.bold,frag.italic) #save our data if not isStrType(data): data = data.decode('utf-8') frag.text = data if hasattr(frag,'isBullet'): delattr(frag,'isBullet') self.bFragList.append(frag) else: self.fragList.append(frag)
def i(runtime, el, caller=None): fontname = runtime.state.font italic = tt2ps(fontname, 0, 1) runtime.state.font = italic output(runtime, prepare_arg(PythonCall(caller), runtime, el)) runtime.state.font = fontname
getSampleStyleSheet() returns a stylesheet you can use for initial development, with a few basic heading and text styles. ''' __all__=( 'PropertySet', 'ParagraphStyle', 'LineStyle', 'ListStyle', 'StyleSheet1', 'getSampleStyleSheet', ) from reportlab.lib.colors import white, black from reportlab.lib.enums import TA_LEFT, TA_CENTER from reportlab.lib.fonts import tt2ps from reportlab.rl_config import canvas_basefontname as _baseFontName _baseFontNameB = tt2ps(_baseFontName,1,0) _baseFontNameI = tt2ps(_baseFontName,0,1) _baseFontNameBI = tt2ps(_baseFontName,1,1) ########################################################### # This class provides an 'instance inheritance' # mechanism for its descendants, simpler than acquisition # but not as far-reaching ########################################################### class PropertySet: defaults = {} def __init__(self, name, parent=None, **kw): """When initialized, it copies the class defaults; then takes a copy of the attributes of the parent if any. All the work is done in init - styles
def incidencia_justificar_estudiante_fecha(request, id_estudiante): # incidencia = get_object_or_404(Incidencia, fecha__range=(now-dias, now), id=id_incidencia, estado=False) estudiante = get_object_or_404(Estudiante, id=id_estudiante) inspector = Inspector.objects.get(user=request.user) # asignatura = incidencia.asignaturaestudiante.asignatura.asignatura # horario = Horario.objects.get(cursoasignatura=incidencia.asignaturaestudiante.asignatura, dia=incidencia.fecha.weekday()) if request.method == 'POST': form = JustificarFechaForm(request.POST) if form.is_valid(): inicioString = request.POST.get('fecha_inicio') finString = request.POST.get('fecha_fin') justificacion = request.POST.get('justificacion') fechaInicio = datetime.datetime.strptime(inicioString, '%Y-%m-%d').date() fechaFin = datetime.datetime.strptime(finString, '%Y-%m-%d').date() incidencias = Incidencia.objects.filter(fecha__in=(fechaInicio, fechaFin), estado=False) if not incidencias.exists(): return render(request, 'incidencia/justificar/justificar_fecha.html', { 'form': form, 'estudiante': estudiante, 'estado': False }, context_instance=RequestContext(request)) for incidencia in incidencias: incidencia.justificacion = justificacion incidencia.estado = True incidencia.revisado_por = inspector incidencia.save() estiloHoja = getSampleStyleSheet() cabecera = estiloHoja['Title'] cabecera.pageBreakBefore = 0 cabecera.keepWithNext = 0 cabecera.textColor = colors.red estilo = estiloHoja['BodyText'] salto = Spacer(0, 10) pagina = [] pagina.append(salto) pagina.append( Paragraph("Unidad Educativa Particular Emanuel", cabecera)) cabecera.textColor = colors.black pagina.append(Paragraph("" + "Justificación", cabecera)) pagina.append(salto) pagina.append(salto) pagina.append( Paragraph( "Estudiante: " + estudiante.nombre + " " + estudiante.apellido, estilo)) fecha1 = fechaInicio.strftime("%A %d de %B del %Y %Z") fecha2 = fechaFin.strftime("%A %d de %B del %Y %Z") pagina.append(Paragraph("Fecha de Inicio: " + fecha1, estilo)) pagina.append(Paragraph("Fecha de Final: " + fecha2, estilo)) estilo.fontName = tt2ps('Times-Roman', 1, 0) pagina.append(Paragraph("" + "Justificación: ", estilo)) estilo.fontName = tt2ps('Times-Roman', 0, 0) pagina.append(Paragraph("" + justificacion, estilo)) pagina.append(salto) pagina.append(salto) pagina.append(salto) pagina.append(salto) pagina.append( Paragraph("" + estudiante.representante.nombres_completos(), estilo)) estilo.fontName = tt2ps('Times-Roman', 1, 0) pagina.append(Paragraph("REPRESENTANTE", estilo)) pagina.append(salto) pagina.append(salto) pagina.append(salto) estilo.fontName = tt2ps('Times-Roman', 0, 0) pagina.append(Paragraph(request.user.get_full_name(), estilo)) estilo.fontName = tt2ps('Times-Roman', 1, 0) pagina.append(Paragraph("INSPECTOR", estilo)) nombreArchivo = "justificante.pdf" documento = SimpleDocTemplate(nombreArchivo, pagesize=A6, showBoundary=1, displayDocTitle=1, leftMargin=2, rightMargin=2, topMargin=2, bottomMargin=2, title="Justificante") documento.build(pagina) salida = open(nombreArchivo) response = HttpResponse(salida, content_type='application/pdf') response[ 'Content-Disposition'] = 'inline; filename=' + nombreArchivo return response # return HttpResponseRedirect(reverse('incidencia_justificar_estudiante', args=(estudiante.id,))+"?mensaje=correcto") else: form = JustificarFechaForm() return render(request, 'incidencia/justificar/justificar_fecha.html', { 'form': form, 'estudiante': estudiante, }, context_instance=RequestContext(request))
getSampleStyleSheet() returns a stylesheet you can use for initial development, with a few basic heading and text styles. ''' __all__ = ( 'PropertySet', 'ParagraphStyle', 'LineStyle', 'ListStyle', 'StyleSheet1', 'getSampleStyleSheet', ) from reportlab.lib.colors import white, black from reportlab.lib.enums import TA_LEFT, TA_CENTER from reportlab.lib.fonts import tt2ps from reportlab.rl_config import canvas_basefontname as _baseFontName _baseFontNameB = tt2ps(_baseFontName, 1, 0) _baseFontNameI = tt2ps(_baseFontName, 0, 1) _baseFontNameBI = tt2ps(_baseFontName, 1, 1) ########################################################### # This class provides an 'instance inheritance' # mechanism for its descendants, simpler than acquisition # but not as far-reaching ########################################################### class PropertySet: defaults = {} def __init__(self, name, parent=None, **kw): """When initialized, it copies the class defaults; then takes a copy of the attributes of the parent
def get_font_name(cls, font_name): return fonts.tt2ps(font_name.value, 0, 0)
def __init__(self, config, league_id, playoff_slots, num_regular_season_weeks, week, data_dir, break_ties_bool, report_title_text, report_footer_text, report_info_dict): self.config = config self.league_id = league_id self.playoff_slots = int(playoff_slots) self.num_regular_season_weeks = int(num_regular_season_weeks) self.week = week self.data_dir = data_dir self.break_ties_bool = break_ties_bool self.current_standings_data = report_info_dict.get( "current_standings_data") self.playoff_probs_data = report_info_dict.get("playoff_probs_data") self.score_results_data = report_info_dict.get("score_results_data") self.coaching_efficiency_results_data = report_info_dict.get( "coaching_efficiency_results_data") self.luck_results_data = report_info_dict.get("luck_results_data") self.power_ranking_results_data = report_info_dict.get( "power_ranking_results_data") self.zscore_results_data = report_info_dict.get("zscore_results_data") self.bad_boy_results_data = report_info_dict.get( "bad_boy_results_data") self.beef_results_data = report_info_dict.get("beef_results_data") self.num_tied_scores = report_info_dict.get("num_tied_scores") self.num_tied_coaching_efficiencies = report_info_dict.get( "num_tied_coaching_efficiencies") self.num_tied_lucks = report_info_dict.get("num_tied_lucks") self.num_tied_power_rankings = report_info_dict.get( "num_tied_power_rankings") self.num_tied_bad_boys = report_info_dict.get("num_tied_bad_boys") self.num_tied_beef = report_info_dict.get("num_tied_beef") self.efficiency_dq_count = report_info_dict.get("efficiency_dq_count") self.tied_scores_bool = report_info_dict.get("tied_scores_bool") self.tied_coaching_efficiencies_bool = report_info_dict.get( "tied_coaching_efficiencies_bool") self.tied_lucks_bool = report_info_dict.get("tied_lucks_bool") self.tied_power_rankings_bool = report_info_dict.get( "tied_power_rankings_bool") self.tied_bad_boy_bool = report_info_dict.get("tied_bad_boy_bool") self.tied_beef_bool = report_info_dict.get("tied_beef_bool") self.tie_for_first_score = report_info_dict.get("tie_for_first_score") self.tie_for_first_coaching_efficiency = report_info_dict.get( "tie_for_first_coaching_efficiency") self.tie_for_first_luck = report_info_dict.get("tie_for_first_luck") self.tie_for_first_power_ranking = report_info_dict.get( "tie_for_first_power_ranking") self.tie_for_first_bad_boy = report_info_dict.get( "tie_for_first_bad_boy") self.tie_for_first_beef = report_info_dict.get("tie_for_first_beef") self.num_tied_for_first_scores = report_info_dict.get( "num_tied_for_first_scores") self.num_tied_for_first_coaching_efficiency = report_info_dict.get( "num_tied_for_first_coaching_efficiency") self.num_tied_for_first_luck = report_info_dict.get( "num_tied_for_first_luck") self.num_tied_for_first_power_ranking = report_info_dict.get( "num_tied_for_first_power_ranking") self.num_tied_for_first_bad_boy = report_info_dict.get( "num_tied_for_first_bad_boy") self.num_tied_for_first_beef = report_info_dict.get( "num_tied_for_first_beef") self.weekly_points_by_position_data = report_info_dict.get( "weekly_points_by_position_data") self.season_average_team_points_by_position = report_info_dict.get( "season_average_points_by_position") self.weekly_top_scorers = report_info_dict.get("weekly_top_scorers") self.weekly_highest_ce = report_info_dict.get("weekly_highest_ce") # table of contents self.toc = TableOfContents(self.break_ties_bool) # team data for use on team specific stats pages self.team_data = report_info_dict.get("team_results") # generic document elements self.metrics_4_col_widths = [ 1.00 * inch, 2.25 * inch, 2.25 * inch, 2.25 * inch ] self.metrics_4_col_widths_wide_right = [ 1.00 * inch, 2.50 * inch, 2.00 * inch, 2.25 * inch ] self.metrics_5_col_widths = [ 0.75 * inch, 1.75 * inch, 1.75 * inch, 1.75 * inch, 1.75 * inch ] self.power_ranking_col_widths = [ 1.00 * inch, 2.50 * inch, 2.50 * inch, 1.75 * inch ] self.line_separator = Drawing(100, 1) self.line_separator.add( Line(0, -65, 550, -65, strokeColor=colors.black, strokeWidth=1)) self.spacer_twentieth_inch = Spacer(1, 0.05 * inch) self.spacer_tenth_inch = Spacer(1, 0.10 * inch) self.spacer_quarter_inch = Spacer(1, 0.25 * inch) self.spacer_half_inch = Spacer(1, 0.50 * inch) self.spacer_five_inch = Spacer(1, 5.00 * inch) # Configure style and word wrap self.stylesheet = getSampleStyleSheet() self.stylesheet.add(ParagraphStyle(name='HC', parent=self.stylesheet['Normal'], fontSize=14, alignment=TA_CENTER, spaceAfter=6), alias='header-centered') self.text_style = self.stylesheet["BodyText"] self.text_styleN = self.stylesheet["Normal"] self.text_styleD = self.stylesheet["Heading1"] self.text_styleT = self.stylesheet["Heading2"] self.text_styleH = self.stylesheet["Heading3"] self.text_styleH5 = ParagraphStyle(name='Heading4', parent=self.text_styleN, fontName=tt2ps(bfn, 1, 1), fontSize=8, leading=10, spaceBefore=0, spaceAfter=0) self.text_style_title = self.stylesheet["HC"] self.text_style.wordWrap = "CJK" title_table_style_list = [ ("TEXTCOLOR", (0, 0), (-1, -1), colors.black), ("ALIGN", (0, 0), (-1, -1), "CENTER"), ("VALIGN", (0, 0), (-1, 0), "MIDDLE"), ] self.title_style = TableStyle(title_table_style_list) # Reportlab fonts: https://github.com/mattjmorrison/ReportLab/blob/master/src/reportlab/lib/fonts.py table_style_list = [("TEXTCOLOR", (0, 1), (-1, 1), colors.green), ("FONT", (0, 1), (-1, 1), "Helvetica-Oblique"), ("FONT", (0, 0), (-1, 0), "Helvetica-Bold"), ("FONTSIZE", (0, 0), (-1, -1), 10), ("TOPPADDING", (0, 0), (-1, -1), 1), ("ALIGN", (0, 0), (-1, -1), "CENTER"), ("GRID", (0, 0), (-1, -1), 0.5, colors.gray), ("GRID", (0, 0), (-1, 0), 1.5, colors.black), ("BOX", (0, 0), (-1, -1), 0.5, colors.black), ("INNERGRID", (0, 0), (-1, -1), 0.25, colors.black), ("VALIGN", (0, 0), (-1, 0), "MIDDLE"), ("BACKGROUND", (0, 0), (-1, 0), colors.lightgrey)] self.style = TableStyle(table_style_list) style_left_alight_right_col_list = copy.deepcopy(table_style_list) style_left_alight_right_col_list.append( ("ALIGN", (-1, 1), (-1, -1), "LEFT")) self.style_left_alighn_right_col = TableStyle( style_left_alight_right_col_list) self.style_no_highlight = TableStyle(table_style_list[2:]) red_highlight = table_style_list.copy() red_highlight[0] = ("TEXTCOLOR", (0, 1), (-1, 1), colors.darkred) self.style_red_highlight = TableStyle(red_highlight) boom_bust_table_style_list = [ ("TEXTCOLOR", (0, 0), (0, -1), colors.green), ("TEXTCOLOR", (1, 0), (1, -1), colors.darkred), ("FONT", (0, 0), (-1, -1), "Helvetica-Bold"), ("FONT", (0, 1), (-1, 1), "Helvetica-Oblique"), ("FONTSIZE", (0, 0), (-1, 0), 16), ("FONTSIZE", (0, 1), (-1, -2), 14), ("FONTSIZE", (0, -1), (-1, -1), 20), ("ALIGN", (0, 0), (-1, -1), "CENTER"), ("VALIGN", (0, 0), (-1, 0), "MIDDLE"), ] self.boom_bust_table_style = TableStyle(boom_bust_table_style_list) # report specific document elements self.standings_headers = [[ "Place", "Team", "Manager", "Record", "Points For", "Points Against", "Streak", "Waiver", "Moves", "Trades" ]] self.standings_col_widths = [ 0.50 * inch, 1.75 * inch, 1.00 * inch, 1.00 * inch, 0.80 * inch, 1.10 * inch, 0.50 * inch, 0.50 * inch, 0.50 * inch, 0.50 * inch ] ordinal_dict = { 1: "1st", 2: "2nd", 3: "3rd", 4: "4th", 5: "5th", 6: "6th", 7: "7th", 8: "8th", 9: "9th", 10: "10th", 11: "11th", 12: "12th" } ordinal_list = [] playoff_places = 1 while playoff_places <= self.playoff_slots: ordinal_list.append(ordinal_dict[playoff_places]) playoff_places += 1 self.playoff_probs_headers = [ ["Team", "Manager", "Record", "Playoffs", "Needed"] + ordinal_list ] self.playoff_probs_col_widths = [1.75 * inch, 0.90 * inch, 0.90 * inch, 0.65 * inch, 0.65 * inch] +\ [round(3.3 / self.playoff_slots, 2) * inch] * self.playoff_slots self.bad_boy_col_widths = [ 0.75 * inch, 1.75 * inch, 1.25 * inch, 1.25 * inch, 1.75 * inch, 1.00 * inch ] self.power_ranking_headers = [[ "Power Rank", "Team", "Manager", "Season Avg. (Place)" ]] self.scores_headers = [[ "Place", "Team", "Manager", "Points", "Season Avg. (Place)" ]] self.weekly_top_scorer_headers = [["Week", "Team", "Manager", "Score"]] self.weekly_highest_ce_headers = [[ "Week", "Team", "Manager", "Coaching Efficiency (%)" ]] self.efficiency_headers = [[ "Place", "Team", "Manager", "Coaching Efficiency (%)", "Season Avg. (Place)" ]] self.luck_headers = [[ "Place", "Team", "Manager", "Luck (%)", "Season Avg. (Place)" ]] self.bad_boy_headers = [[ "Place", "Team", "Manager", "Bad Boy Pts", "Worst Offense", "# Offenders" ]] self.beef_headers = [["Place", "Team", "Manager", "TABBU(s)"]] self.zscores_headers = [["Place", "Team", "Manager", "Z-Score"]] self.tie_for_first_footer = "<i> *Tie(s).</i>" # self.break_efficiency_ties_footer = "<i> *The league commissioner will " \ # "resolve coaching efficiency ties manually. The tiebreaker goes " \ # "to the manager whose team contains the most players who have " \ # "met or exceeded their average weekly fantasy points. If there is " \ # "still a tie after that, the manager whose players exceeded their " \ # "season average score by the highest cumulative percent wins.</i>" self.break_efficiency_ties_footer = "<i> *The league commissioner will " \ "resolve coaching efficiency ties manually.</i>" self.style_efficiency_dqs = None self.style_tied_scores = self.set_tied_values_style( self.num_tied_scores, table_style_list, "scores") self.style_tied_efficiencies = self.set_tied_values_style( self.num_tied_coaching_efficiencies, table_style_list, "coaching_efficiency") self.style_tied_luck = self.set_tied_values_style( self.num_tied_lucks, table_style_list, "luck") self.style_tied_power_rankings = self.set_tied_values_style( self.num_tied_power_rankings, table_style_list, "power_ranking") self.style_tied_bad_boy = self.set_tied_values_style( self.num_tied_bad_boys, table_style_list, "bad_boy") self.style_tied_beef = self.set_tied_values_style( self.num_tied_beef, style_left_alight_right_col_list, "beef") # options: "document", "section", or None self.report_title = self.create_title(report_title_text, element_type="document") footer_data = [[self.spacer_five_inch], [ Paragraph(report_footer_text, getSampleStyleSheet()["Normal"]) ]] self.report_footer = Table(footer_data, colWidths=7.75 * inch)
def get_font_name_bold(cls, font_name): return fonts.tt2ps(font_name.value, 1, 0)
def incidencia_justificar_estudiante_incidencia(request, id_estudiante, id_incidencia): now = datetime.datetime.now() if (now.weekday() == 0 or now.weekday() == 1): dias = datetime.timedelta(days=4) elif (now.weekday() == 6): dias = datetime.timedelta(days=3) else: dias = datetime.timedelta(days=2) incidencia = get_object_or_404(Incidencia, fecha__range=(now - dias, now), id=id_incidencia, estado=False) estudiante = incidencia.asignaturaestudiante.estudiante asignatura = incidencia.asignaturaestudiante.asignatura.asignatura # horario = Horario.objects.get(cursoasignatura=incidencia.asignaturaestudiante.asignatura, dia=incidencia.fecha.weekday()) if request.method == 'POST': form = JustificarForm(request.POST, instance=incidencia) if form.is_valid(): incidencia = form.save(commit=False) incidencia.estado = True incidencia.save() estiloHoja = getSampleStyleSheet() cabecera = estiloHoja['Title'] cabecera.pageBreakBefore = 0 cabecera.keepWithNext = 0 cabecera.textColor = colors.red estilo = estiloHoja['BodyText'] salto = Spacer(0, 10) pagina = [] pagina.append(salto) pagina.append( Paragraph("Unidad Educativa Particular Emanuel", cabecera)) cabecera.textColor = colors.black pagina.append(Paragraph("" + "Justificación", cabecera)) pagina.append(salto) pagina.append(salto) pagina.append( Paragraph( "Estudiante: " + estudiante.nombre + " " + estudiante.apellido, estilo)) pagina.append( Paragraph("Fecha: " + incidencia.fecha.strftime('%m/%d/%Y'), estilo)) pagina.append( Paragraph("Hora: " + incidencia.hora.get_hora_display(), estilo)) pagina.append(Paragraph("Asignatura: " + asignatura.nombre, estilo)) estilo.fontName = tt2ps('Times-Roman', 1, 0) pagina.append(Paragraph("" + "Justificación: ", estilo)) estilo.fontName = tt2ps('Times-Roman', 0, 0) pagina.append(Paragraph("" + incidencia.justificacion, estilo)) pagina.append(salto) pagina.append(salto) pagina.append(salto) pagina.append(salto) pagina.append( Paragraph("" + estudiante.representante.nombres_completos(), estilo)) estilo.fontName = tt2ps('Times-Roman', 1, 0) pagina.append(Paragraph("REPRESENTANTE", estilo)) pagina.append(salto) pagina.append(salto) pagina.append(salto) estilo.fontName = tt2ps('Times-Roman', 0, 0) pagina.append( Paragraph(incidencia.revisado_por.user.get_full_name(), estilo)) estilo.fontName = tt2ps('Times-Roman', 1, 0) pagina.append(Paragraph("INSPECTOR", estilo)) nombreArchivo = "justificante-" + incidencia.fecha.strftime( '%m-%d-%Y') + ".pdf" documento = SimpleDocTemplate(nombreArchivo, pagesize=A6, showBoundary=1, displayDocTitle=1, leftMargin=2, rightMargin=2, topMargin=2, bottomMargin=2, title="Justificante") documento.build(pagina) salida = open(nombreArchivo) response = HttpResponse(salida, content_type='application/pdf') response[ 'Content-Disposition'] = 'inline; filename=' + nombreArchivo return response # return HttpResponseRedirect(reverse('incidencia_justificar_estudiante', args=(estudiante.id,))+"?mensaje=correcto") else: form = JustificarForm(instance=incidencia) return render(request, 'incidencia/justificar/justificar.html', { 'form': form, 'estudiante': estudiante, 'asignatura': asignatura, 'incidencia': incidencia }, context_instance=RequestContext(request))
def get_style_sheet(font_url=None): """Returns a custom stylesheet object""" default_style_sheet = getSampleStyleSheet() if not font_url: return default_style_sheet stylesheet = StyleSheet1() font_name = 'customFont' try: font = TTFont(font_name, font_url) except TTFError: log.warning(u'Cannot load %s', font_url) return default_style_sheet reportlab.rl_config.warnOnMissingFontGlyphs = 0 pdfmetrics.registerFont(font) font_name_bold = tt2ps(font_name, 1, 0) font_name_italic = tt2ps(font_name, 0, 1) font_name_bold_italic = tt2ps(font_name, 1, 1) stylesheet.add( ParagraphStyle(name='Normal', fontName=font_name, fontSize=10, leading=12)) stylesheet.add( ParagraphStyle(name='BodyText', parent=stylesheet['Normal'], spaceBefore=6)) stylesheet.add( ParagraphStyle(name='Italic', parent=stylesheet['BodyText'], fontName=font_name_italic)) stylesheet.add(ParagraphStyle(name='Heading1', parent=stylesheet['Normal'], fontName=font_name_bold, fontSize=18, leading=22, spaceAfter=6), alias='h1') stylesheet.add(ParagraphStyle(name='Title', parent=stylesheet['Normal'], fontName=font_name_bold, fontSize=22, leading=22, alignment=TA_CENTER, spaceAfter=6), alias='title') stylesheet.add(ParagraphStyle(name='Heading2', parent=stylesheet['Normal'], fontName=font_name_bold, fontSize=14, leading=18, spaceBefore=12, spaceAfter=6), alias='h2') stylesheet.add(ParagraphStyle(name='Heading3', parent=stylesheet['Normal'], fontName=font_name_bold_italic, fontSize=12, leading=14, spaceBefore=12, spaceAfter=6), alias='h3') stylesheet.add(ParagraphStyle(name='Heading4', parent=stylesheet['Normal'], fontName=font_name_bold_italic, fontSize=10, leading=12, spaceBefore=10, spaceAfter=4), alias='h4') stylesheet.add(ParagraphStyle(name='Heading5', parent=stylesheet['Normal'], fontName=font_name_bold, fontSize=9, leading=10.8, spaceBefore=8, spaceAfter=4), alias='h5') stylesheet.add(ParagraphStyle(name='Heading6', parent=stylesheet['Normal'], fontName=font_name_bold, fontSize=7, leading=8.4, spaceBefore=6, spaceAfter=2), alias='h6') stylesheet.add(ParagraphStyle(name='Bullet', parent=stylesheet['Normal'], firstLineIndent=0, spaceBefore=3), alias='bu') stylesheet.add(ParagraphStyle(name='Definition', parent=stylesheet['Normal'], firstLineIndent=0, leftIndent=36, bulletIndent=0, spaceBefore=6, bulletFontName=font_name_bold_italic), alias='df') stylesheet.add( ParagraphStyle(name='Code', parent=stylesheet['Normal'], fontName='Courier', fontSize=8, leading=8.8, firstLineIndent=0, leftIndent=36)) return stylesheet
def font_name(self): return tt2ps(self.font_family, self.bold, self.italic)
from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from reportlab.lib.styles import getSampleStyleSheet from reportlab.lib import colors from reportlab.lib import fonts from reportlab.lib.enums import TA_CENTER from reportlab.lib.pagesizes import letter from reportlab.platypus import Paragraph, SimpleDocTemplate, Table, TableStyle pdfmetrics.registerFont(TTFont('Heiti', 'STHeiti Light.ttc')) pdfmetrics.registerFont(TTFont('Heiti-Bold', 'STHeiti Medium.ttc')) fonts.addMapping('heiti', 0, 0, 'Heiti') fonts.addMapping('heiti', 1, 0, 'Heiti-Bold') heiti_font_name = fonts.tt2ps('heiti', 0, 0) heiti_font_name_b = fonts.tt2ps(heiti_font_name, 1, 0) style = copy.deepcopy(getSampleStyleSheet()['Normal']) style.fontName = heiti_font_name style.alignment = TA_CENTER style_bold = copy.deepcopy(getSampleStyleSheet()['Normal']) style_bold.fontName = heiti_font_name_b style_bold.alignment = TA_CENTER data = [ ['股票代码', '股票名称', '调研机构'], [ '000981', '银亿股份', '证券时报 ‖ 每日经济新闻 ‖ 21世纪经济报道 ‖ 东方财富网 ‖ 大众证券报 ‖ 中国经营报 ‖ 华夏时报 ‖ 时代周刊 ‖ 新闻晨报 ‖ 宁波日报 ‖ 宁波晚报 ‖ 东南商报 ‖ 金陵晚报 ‖ 扬子晚报 ‖ 现代快报 ‖ 人民网 ‖ 网易 ‖ 中国新闻网 ‖ 财联社 ‖ 盖世汽车 ‖ 汽车之家 ‖ 汽车与配件 ‖ 荣格工业 ‖ 汽车经营与服务 ‖ 汽车通讯社 ‖ 买车大师 ‖ 猫扑网 ‖ 环球汽车网 ‖ 上海汽车报 ‖ 汽车财经报 ‖ 汽车之友 ‖ 汽车导购 ‖ 驾修杂志 ‖ 车讯 ‖ 中国汽车报 ‖ 乐居网 ‖ 三六五网'
from reportlab.lib.pagesizes import letter from reportlab.platypus import Paragraph, SimpleDocTemplate # 英文字体 Arial # 建立字体的映射关系 registerFont => addMapping => tt2ps pdfmetrics.registerFont(TTFont('Arial', 'Arial.ttf')) pdfmetrics.registerFont(TTFont('Arial-Italic', 'Arial Italic.ttf')) pdfmetrics.registerFont(TTFont('Arial-Bold', 'Arial Bold.ttf')) pdfmetrics.registerFont(TTFont('Arial-BoldItalic', 'Arial Bold Italic.ttf')) fonts.addMapping('arial', 0, 0, 'Arial') fonts.addMapping('arial', 0, 1, 'Arial-Italic') fonts.addMapping('arial', 1, 0, 'Arial-Bold') fonts.addMapping('arial', 1, 1, 'Arial-BoldItalic') arial_font_name = fonts.tt2ps('arial', 0, 0) arial_font_name_i = fonts.tt2ps(arial_font_name, 0, 1) arial_font_name_b = fonts.tt2ps(arial_font_name, 1, 0) arial_font_name_bi = fonts.tt2ps(arial_font_name, 1, 1) # 中文字体 宋体-简 # 正常、斜体、粗体等都在一个字体文件里,需要使用subfontIndex pdfmetrics.registerFont(TTFont('Songti', 'Songti.ttc', subfontIndex=3)) pdfmetrics.registerFont(TTFont('Songti-Italic', 'Songti.ttc', subfontIndex=2)) pdfmetrics.registerFont(TTFont('Songti-Bold', 'Songti.ttc', subfontIndex=1)) pdfmetrics.registerFont( TTFont('Songti-BoldItalic', 'Songti.ttc', subfontIndex=0)) fonts.addMapping('songti', 0, 0, 'Songti') fonts.addMapping('songti', 0, 1, 'Songti-Italic') fonts.addMapping('songti', 1, 0, 'Songti-Bold')
def font(self): font = self.ttfont bold = self.font_weight == 'bold' italic = self.font_style == 'italic' return tt2ps(font, bold, italic)