def Imprimer(self, event=None): # Création du PDF from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, PageBreak from reportlab.platypus.flowables import ParagraphAndImage, Image from reportlab.rl_config import defaultPageSize from reportlab.lib.units import inch, cm from reportlab.lib.utils import ImageReader from reportlab.lib import colors from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle self.hauteur_page = defaultPageSize[1] self.largeur_page = defaultPageSize[0] # Initialisation du PDF PAGE_HEIGHT = defaultPageSize[1] PAGE_WIDTH = defaultPageSize[0] nomDoc = FonctionsPerso.GenerationNomDoc("LISTE_ATTENTE", "pdf") if sys.platform.startswith("win"): nomDoc = nomDoc.replace("/", "\\") doc = SimpleDocTemplate(nomDoc, topMargin=30, bottomMargin=30) story = [] largeurContenu = 520 # Création du titre du document def Header(): dataTableau = [] largeursColonnes = ((420, 100)) dateDuJour = DateEngFr(str(datetime.date.today())) dataTableau.append((_(u"Liste d'attente"), _(u"%s\nEdité le %s") % (UTILS_Organisateur.GetNom(), dateDuJour))) style = TableStyle([ ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('ALIGN', (0, 0), (0, 0), 'LEFT'), ('FONT', (0, 0), (0, 0), "Helvetica-Bold", 16), ('ALIGN', (1, 0), (1, 0), 'RIGHT'), ('FONT', (1, 0), (1, 0), "Helvetica", 6), ]) tableau = Table(dataTableau, largeursColonnes) tableau.setStyle(style) story.append(tableau) story.append(Spacer(0, 20)) # Insère un header Header() # Un tableau par date for date, listeGroupes in self.listeImpression: dataTableau = [] largeursColonnes = [180, 180, 160] dataTableau.append((date, "", "")) # Groupes listeIndexGroupes = [] indexLigne = 0 for nomGroupe, listeIndividus in listeGroupes: indexLigne += 1 listeIndexGroupes.append(indexLigne) dataTableau.append((nomGroupe, "", "")) # Individus for dictIndividu in listeIndividus: placeDispo = dictIndividu["placeDispo"] texteIndividu = dictIndividu["texteIndividu"] texteUnites = dictIndividu["texteUnites"] texteDateSaisie = _( u"Saisie le %s") % dictIndividu["texteDateSaisie"] dataTableau.append(( texteIndividu, texteUnites, texteDateSaisie)) # Paragraph(memo_journee, paraStyle) indexLigne += 1 couleurFond = (0.8, 0.8, 1) # Vert -> (0.5, 1, 0.2) listeStyles = [ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), # Centre verticalement toutes les cases ('FONT', (0, 0), (-1, -1), "Helvetica", 7), # Donne la police de caract. + taille de police ('GRID', (0, 0), (-1, -1), 0.25, colors.black), # Crée la bordure noire pour tout le tableau ('ALIGN', (0, 1), (-1, -1), 'CENTRE'), # Centre les cases ('ALIGN', (0, 1), (-1, 1), 'CENTRE'), # Ligne de labels colonne alignée au centre ('FONT', (0, 1), (-1, 1), "Helvetica", 6 ), # Donne la police de caract. + taille de police des labels ( 'SPAN', (0, 0), (-1, 0) ), # Fusionne les lignes du haut pour faire le titre du groupe ( 'FONT', (0, 0), (0, 0), "Helvetica-Bold", 10 ), # Donne la police de caract. + taille de police du titre de groupe ('BACKGROUND', (0, 0), (-1, 0), couleurFond), # Donne la couleur de fond du titre de groupe ] # Formatage des lignes "Activités" for indexGroupe in listeIndexGroupes: listeStyles.append( ('SPAN', (0, indexGroupe), (-1, indexGroupe))) listeStyles.append(('FONT', (0, indexGroupe), (-1, indexGroupe), "Helvetica-Bold", 7)) listeStyles.append( ('ALIGN', (0, indexGroupe), (-1, indexGroupe), 'LEFT')) # Création du tableau tableau = Table(dataTableau, largeursColonnes) tableau.setStyle(TableStyle(listeStyles)) story.append(tableau) story.append(Spacer(0, 20)) # Enregistrement du PDF doc.build(story) # Affichage du PDF FonctionsPerso.LanceFichierExterne(nomDoc)
def generaServicios(): """Xeramos o informe dos Servizos usando as librerias de reportlab Crease unha lista 'paxina' a que lle engadiremos os elementos seguintes: imaxe -- engadimos unha imaxe cos parametros(desplazamentoX,desplazamentoY,ancho,alto) debuxo -- indicaremos a posicion na que situaremos a imaxe cos parametros (ancho,alto) debuxo.add(imaxe) -- engade a imaxe ao noso debuxo paxina.append(debuxo) -- engade o debuxo a nosa paxina ------------------------------------------------------------------------------------------- A continuación crearemos a conexion a nosa base de datos: bbdd = dbapi.connect("Clinica.dat") -- conecta a base de datos "Clinica.dat" cursor = bbdd.cursor() -- creamos un cursor para executar ordes sobre as taboas ------------------------------------------------------------------------------------------- Pasamos a xerar a tabla no noso informe: columnas -- Creamos as columnas da nosa taboa cursor.execute -- executa a operacion sql deseada taboa -- creamos unha taboa a que lle pasamos as columnas e o resultado da nosa consulta taboa.setStyle -- define o estilo da nosa taboa paxina.append(taboa) -- engade a taboa a nosa paxina -------------------------------------------------------------------------------------------- Por ultimo xeramos o documento pdf para iso debemos realizar o seguinte: *SimpleDocTemplate -- ao que lle pasamos(nome do pdf a xerar,formato da paxina,e borde) *debemos pasarlle unha referencia doc.build(paxina) -- Xera o informe coa configuracion anterior """ try: paxina = [] imaxe = Image(80, 50, 280, 150, "logo.png") # x lateral y horizontal ancho y alto debuxo = Drawing(300, 200) debuxo.add(imaxe) paxina.append(debuxo) # añadimos dibujo a la lista bbdd = dbapi.connect("Clinica.dat") cursor = bbdd.cursor() columnas = [["Servicio", "Precio"]] cursor.execute("select * from servicios") taboa = Table(columnas + cursor.fetchall()) # recupera los datos taboa.setStyle([ ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ("BOX", (0, 0), (-1, -1), 0.25, colors.black), ("BACKGROUND", (0, 0), (-1, -1), colors.lightcyan), ("BACKGROUND", (0, 0), (5, 0), colors.lightgreen), ]) paxina.append(taboa) doc = SimpleDocTemplate("informeServicio.pdf", pagesize=A4, showBoundary=1) # boundary linea a4 doc.build(paxina) except dbapi.OperationalError as e: print("problema " + str(e))
def Imprimer(self, Event=None): # Création du PDF from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, PageBreak from reportlab.platypus.flowables import ParagraphAndImage, Image from reportlab.rl_config import defaultPageSize from reportlab.lib.pagesizes import A4 from reportlab.lib.units import inch, cm from reportlab.lib.utils import ImageReader from reportlab.lib import colors from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle hauteur_page = A4[0] largeur_page = A4[1] # Initialisation du PDF nomDoc = FonctionsPerso.GenerationNomDoc("SYNTHESE_IMPAYES", "pdf") if sys.platform.startswith("win"): nomDoc = nomDoc.replace("/", "\\") doc = SimpleDocTemplate(nomDoc, pagesize=(largeur_page, hauteur_page), topMargin=30, bottomMargin=30, leftMargin=40, rightMargin=40) story = [] # Création du titre du document dataTableau = [] largeursColonnes = ((largeur_page - 175, 100)) dateDuJour = DateEngFr(str(datetime.date.today())) dataTableau.append( (_(u"Synthèse des impayés"), _(u"%s\nEdité le %s") % (UTILS_Organisateur.GetNom(), dateDuJour))) style = TableStyle([ ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('ALIGN', (0, 0), (0, 0), 'LEFT'), ('FONT', (0, 0), (0, 0), "Helvetica-Bold", 16), ('ALIGN', (1, 0), (1, 0), 'RIGHT'), ('FONT', (1, 0), (1, 0), "Helvetica", 6), ]) tableau = Table(dataTableau, largeursColonnes) tableau.setStyle(style) story.append(tableau) story.append(Spacer(0, 10)) # Intro styleA = ParagraphStyle(name="A", fontName="Helvetica", fontSize=6, spaceAfter=20) story.append(Paragraph(self.labelParametres, styleA)) # Tableau dataTableau = [] largeursColonnes = [ 160, ] for x in range(0, len(self.dictImpression["entete"]) - 1): largeursColonnes.append(45) # Entetes labels dataTableau.append(self.dictImpression["entete"]) # Contenu du tableau listeRubriques = ("contenu", "total") for rubrique in listeRubriques: listeLignes = self.dictImpression[rubrique] for ligne in listeLignes: dataTableau.append(ligne) positionLigneTotal = len(self.dictImpression["contenu"]) + 1 listeStyles = [ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), # Centre verticalement toutes les cases ('FONT', (0, 0), (-1, -1), "Helvetica", 7), # Donne la police de caract. + taille de police ('GRID', (0, 0), (-1, -1), 0.25, colors.black), # Crée la bordure noire pour tout le tableau ('ALIGN', (0, 0), (-1, -1), 'CENTRE'), # Centre les cases ## ('ALIGN', (0,1), (-1,1), 'CENTRE'), # Ligne de labels colonne alignée au centre ## ('FONT',(0,1),(-1,1), "Helvetica", 6), # Donne la police de caract. + taille de police des labels ## ## ('SPAN',(0,0),(-1,0)), # Fusionne les lignes du haut pour faire le titre du groupe ## ('FONT',(0,0),(0,0), "Helvetica-Bold", 10), # Donne la police de caract. + taille de police du titre de groupe ('BACKGROUND', (0, 0), (-1, 0), (0.6, 0.6, 0.6) ), # Donne la couleur de fond du label ('BACKGROUND', (0, positionLigneTotal), (-1, positionLigneTotal), (0.6, 0.6, 0.6)), # Donne la couleur de fond du label ] # Formatage des lignes "Activités" for indexColoration in self.dictImpression["coloration"]: listeStyles.append( ('FONT', (0, indexColoration + 1), (-1, indexColoration + 1), "Helvetica-Bold", 7)) listeStyles.append(('BACKGROUND', (0, indexColoration + 1), (-1, indexColoration + 1), (0.8, 0.8, 0.8))) # Création du tableau tableau = Table(dataTableau, largeursColonnes) tableau.setStyle(TableStyle(listeStyles)) story.append(tableau) story.append(Spacer(0, 20)) # Enregistrement du PDF doc.build(story) # Affichage du PDF FonctionsPerso.LanceFichierExterne(nomDoc)
def company_payment(request): # Get selection criteria selected_company = None if request.GET['company']: selected_company = Company.objects.get(id=int(request.GET['company'])) # Fetch data ticket_types = [{ 'name': tt.name, 'payment': tt.payment } for tt in TicketType.objects.filter( festival=request.festival).order_by('name')] ticket_types.append({'name': 'eFringer', 'payment': Decimal('3.00')}) ticket_types.append({'name': 'Volunteer', 'payment': Decimal('0.00')}) companies = [] if selected_company: shows.append( _get_company_tickets_by_type(selected_company, ticket_types)) else: ticketed_company_ids = Show.objects.filter( festival=request.festival, venue__is_ticketed=True).values('company_id').distinct() for company in Company.objects.filter( id__in=ticketed_company_ids).order_by('name'): companies.append( _get_company_tickets_by_type(company, ticket_types)) # Check for HTML format = request.GET['format'] if format.lower() == 'html': # Render tickets context = { 'ticket_types': ticket_types, 'companies': companies, } return render(request, "reports/finance/company_payment.html", context) # Render as PDF response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'inline' doc = SimpleDocTemplate( response, pagesize=portrait(A4), leftMargin=1.5 * cm, rightMargin=1.5 * cm, topMargin=1.5 * cm, bottomMargin=1.5 * cm, ) styles = getSampleStyleSheet() story = [] # Festival banner if request.festival.banner: banner = Image(request.festival.banner.get_absolute_path(), width=16 * cm, height=4 * cm) banner.hAlign = 'CENTER' story.append(banner) story.append(Spacer(1, 1 * cm)) # Companies for company in companies: # Header story.append( Paragraph( f"<para><b>{company['name']}</b>: £{company['payment']}</para>", styles['Normal'])) for show in company['shows']: story.append(Spacer(1, 0.2 * cm)) story.append( Paragraph(f"<para>{show['name']}: £{show['payment']}</para>", styles['Normal'])) table_data = [] table_styles = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('ALIGN', (0, 0), (-1, -1), 'RIGHT'), ] row = [''] for ticket_type in ticket_types: row.append(ticket_type['name']) row.append('Payment') table_data.append(row) #row = [''] #for ticket_type in ticket_types: # row.append(f"£{ticket_type['payment']}") #row.append('') #table_data.append(row) # Performances for performance in show['performances']: row = [ Paragraph( f"<para>{ performance['date']:%a, %b %d } at { performance['time']:%I:%M%p }</para>", styles['Normal']) ] for ticket_type in ticket_types: row.append(performance['tickets'][ticket_type['name']]) row.append(f"£{performance['payment']}") table_data.append(row) colWidths = [5 * cm] for ticket_type in ticket_types: colWidths.append((11 / len(ticket_types)) * cm) colWidths.append(2 * cm) # Add to story table = Table( table_data, colWidths=colWidths, style=table_styles, ) story.append(table) story.append(Spacer(1, 0.5 * cm)) # Render PDF document and return it doc.build(story) return response
# c.drawString(5, 705, "This is a MEAN stack project. Used technologies are Mongo DB, ExpressJs, Angular and NodeJs") # # c.drawString(5, 690, "Total Number of commits:") # c.drawString(150, 690, "134") # c.drawString(5, 675, "Total number of front end:") # c.drawString(150, 675, "94") # c.drawString(5, 660, "Total number of front end:") # c.drawString(150, 660, "40") # # # # c.showPage() doc = SimpleDocTemplate("form_letter.pdf", rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=18) styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY)) Story = [] logo = "image.png" # We really want to scale the image to fit in a box and keep proportions. im = Image(logo, 3 * inch, 3 * inch) Story.append(im) ptext = ''' <seq>. </seq>Some Text<br/>
def createBarCodesv2(buffer, dataDB, lesson=None): elements = [] doc = SimpleDocTemplate(buffer, pagesize=A4, rightMargin=0, leftMargin=1*cm, topMargin=-2.0*cm, bottomMargin=-1.5*cm) #doc = SimpleDocTemplate("tables+barcodes.pdf", pagesize=A4, rightMargin=0, leftMargin=6*cm, topMargin=0*cm, bottomMargin=0) styles = getSampleStyleSheet() styleN = styles['Normal'] styleH = styles['Heading1'] #story = [] # write title lesson_text = reportTitle(lesson) title_text = u"{0}({1})-{2}".format(lesson_text, lesson.category[0:3], Lesson.lexLessonType(Lesson, lesson.type)[0:2]) #title_text = u"{0} {1}".format(ugettext(u"ΜΑΘΗΜΑ"), lesson_text) #valLessonType = (Lesson.lexLessonType(Lesson, dataDB[count]['codeType'])) #Values to generate barcodes from barcode_values = [r['codeBarcode'] for r in dataDB] #barcode_values = ['0004-0000000001', '0004-0000000002','0004-0000000003','0004-0000000004','0004-0000000005',] #print dataDB print barcode_values #Table settings size = len(barcode_values) cols = 2 # needs coreect when barcode =1 rows = (size/cols if size%cols == 0 else size/cols +1) #print "BARCODE TABLE: size(%d) cols(%d) rows(%d)" %(size, cols, rows) #Paragraph styles pageTexStyleHead = ParagraphStyle(name="pageTexStyleLesson", alignment=TA_LEFT, fontSize=16, leftIndent=16, leading=12, spaceBefore=0, spaceAfter=4,) #pageTexStyleHead = ParagraphStyle(name="pageTexStyleLesson", alignment=TA_LEFT, fontSize=16, # leftIndent=16, leading=14, spaceBefore=0, spaceAfter=8,) pageTexStyleTag = ParagraphStyle(name="pageTexStyleExplain", alignment=TA_LEFT, fontSize=14, leftIndent=16, spaceBefore=0, spaceAfter=0,) #[ Paragraph("Occupation", pageTextStyleCenter) , userData['studentDetails'].get('fOccupation', "-")] #Make Table barcodeArray = [] count = 0 while count < size: barcodeRow = [] for j in range(0,cols): parag = [] #header-A """ parag.append(Paragraph(title_text, pageTexStyleHead)) valType = (Folder.lexCodeType(Folder, dataDB[count]['codeType'])) valNo = dataDB[count]['no'] #eg. ΦΑ#1 valBooks= dataDB[count]['books'] #eg. ΦΑ#1 tag1 = u"%s ΦΑΚΕΛΟΣ: %s" %(valType, str(valNo)) tag2 = u"ΤΕΤΡΑΔΙΑ: %s" %(str(valBooks)) parag.append(Paragraph(tag1, pageTexStyleTag)) parag.append(Paragraph(tag2, pageTexStyleTag)) parag.append(Spacer(width=32, height=10)) """ #header-B 2016-07-20 parag.append(Paragraph(title_text, pageTexStyleHead)) valType = (Folder.lexCodeType(Folder, dataDB[count]['codeType'])) valNo = dataDB[count]['no'] #eg. ΦΑ#1 valBooks= dataDB[count]['books'] #eg. ΦΑ#1 tag1 = u"Φ%s%s ΤΕΤΡΑΔΙΑ:%d" %(str(valNo), valType[1:],valBooks) #tag2 = u"ΤΕΤΡΑΔΙΑ: %s" %(str(valBooks)) parag.append(Paragraph(tag1, pageTexStyleTag)) #parag.append(Paragraph(tag2, pageTexStyleTag)) parag.append(Spacer(width=32, height=10)) #parag.append(Spacer(width=32, height=10)) #parag.append(Extended39("A012345B}")) barcode_code128 = code128.Code128(dataDB[count]['codeBarcode'], barHeight=.3*inch, barWidth = 1.3, humanReadable=True) parag.append(barcode_code128) barcodeRow.append(parag) # 2xsame tags for 1-size list if size==1: parag=[] parag.append(Spacer(32, 16)) barcodeRow.append(parag) #print count count += 1 if count == size: break barcodeArray.append(barcodeRow) #print barcodeArray #table = Table(barcodeArray, colWidths=doc.width/2, rowHeights=doc.height/8) table = Table(barcodeArray, colWidths=11*cm, rowHeights=4.45*cm) #parts.append(Spacer(1, 0.5 * inch)) elements.append(table) doc.build(elements) # create document pdf = buffer.getvalue() buffer.close() return pdf
def festival_summary(request): # General stuff date_list = [ datetime.date(2019, 6, 24) + datetime.timedelta(days=d) for d in range(7) ] venue_list = [ v for v in Venue.objects.filter(festival=request.festival, is_ticketed=True).order_by('name') ] boxoffice_list = [ bo for bo in BoxOffice.objects.filter( festival=request.festival).order_by('name') ] # Sales by channel online_pre = Sale.objects.filter(festival=request.festival, created__lt=date_list[0], completed__isnull=False, boxoffice__isnull=True, venue__isnull=True).aggregate( Sum('amount'))['amount__sum'] or 0 online = { 'pre': online_pre, 'dates': [], 'total': online_pre, } venues = OrderedDict([(v.name, { 'dates': [], 'total': 0 }) for v in venue_list]) boxoffices = OrderedDict([(bo.name, { 'dates': [], 'total': 0 }) for bo in boxoffice_list]) totals = { 'pre': online_pre, 'dates': [], 'total': online_pre, } for date in date_list: query = Sale.objects.filter(festival=request.festival, created__date=date, completed__isnull=False) date_total = 0 date_amount = query.filter(boxoffice__isnull=True, venue__isnull=True).aggregate( Sum('amount'))['amount__sum'] or 0 online['dates'].append(date_amount) online['total'] += date_amount date_total += date_amount for venue in venue_list: date_amount = query.filter(venue=venue).aggregate( Sum('amount'))['amount__sum'] or 0 venues[venue.name]['dates'].append(date_amount) venues[venue.name]['total'] += date_amount date_total += date_amount for boxoffice in boxoffice_list: date_amount = query.filter(boxoffice=boxoffice).aggregate( Sum('amount'))['amount__sum'] or 0 boxoffices[boxoffice.name]['dates'].append(date_amount) boxoffices[boxoffice.name]['total'] += date_amount date_total += date_amount totals['dates'].append(date_total) totals['total'] += date_total sales_by_channel = { 'dates': date_list, 'online': online, 'venues': venues, 'boxoffices': boxoffices, 'totals': totals, } # Sales by type efringers_pre = Fringer.objects.filter( user__isnull=False, sale__festival=request.festival, sale__created__lt=date_list[0], sale__completed__isnull=False).aggregate(Sum('cost'))['cost__sum'] or 0 tickets_pre = Ticket.objects.filter( user__isnull=False, sale__festival=request.festival, sale__created__lt=date_list[0], sale__completed__isnull=False).aggregate(Sum('cost'))['cost__sum'] or 0 types = OrderedDict([ ('buttons', { 'title': 'Badges', 'pre': None, 'dates': [], 'total': 0 }), ('fringers', { 'title': 'Paper fringers', 'pre': None, 'dates': [], 'total': 0 }), ('efringers', { 'title': 'eFringers', 'pre': efringers_pre, 'dates': [], 'total': 0 }), ('tickets', { 'title': 'Tickets', 'pre': tickets_pre, 'dates': [], 'total': 0 }), ]) totals = { 'pre': efringers_pre + tickets_pre, 'dates': [], 'total': efringers_pre + tickets_pre, } for date in date_list: date_total = 0 date_amount = Sale.objects.filter( festival=request.festival, created__date=date, completed__isnull=False).aggregate( Sum('buttons'))['buttons__sum'] or 0 types['buttons']['dates'].append(date_amount) types['buttons']['total'] += date_amount date_total += date_amount date_amount = Fringer.objects.filter( user__isnull=True, sale__festival=request.festival, sale__created__date=date, sale__completed__isnull=False).aggregate( Sum('cost'))['cost__sum'] or 0 types['fringers']['dates'].append(date_amount) types['fringers']['total'] += date_amount date_total += date_amount date_amount = Fringer.objects.filter( user__isnull=False, sale__festival=request.festival, sale__created__date=date, sale__completed__isnull=False).aggregate( Sum('cost'))['cost__sum'] or 0 types['efringers']['dates'].append(date_amount) types['efringers']['total'] += date_amount date_total += date_amount date_amount = Ticket.objects.filter(sale__festival=request.festival, sale__created__date=date, sale__completed__isnull=False, refund__isnull=True).aggregate( Sum('cost'))['cost__sum'] or 0 types['tickets']['dates'].append(date_amount) types['tickets']['total'] += date_amount date_total += date_amount totals['dates'].append(date_total) totals['total'] += date_total sales_by_type = { 'dates': date_list, 'types': types, 'totals': totals, } # Tickets tickets = { 'types': [], 'totals': { 'online': 0, 'boxoffice': 0, 'venue': 0, 'total': 0, } } ticket_types = [ tt.name for tt in TicketType.objects.filter( festival=request.festival).order_by('seqno') ] ticket_types.append('eFringer') ticket_types.append('Volunteer') for ticket_type in ticket_types: query = Ticket.objects.filter(description=ticket_type, sale__festival=request.festival, sale__completed__isnull=False, refund__isnull=True) online = query.filter(sale__venue__isnull=True, sale__boxoffice__isnull=True).count() or 0 boxoffice = query.filter(sale__boxoffice__isnull=False).count() or 0 venue = query.filter(sale__venue__isnull=False).count() or 0 tickets['types'].append({ 'description': ticket_type, 'online': online, 'boxoffice': boxoffice, 'venue': venue, 'total': online + boxoffice + venue, }) tickets['totals']['online'] += online tickets['totals']['boxoffice'] += boxoffice tickets['totals']['venue'] += venue tickets['totals']['total'] += online + boxoffice + venue # Paper fringers fringers_sold = Fringer.objects.filter( user__isnull=True, sale__festival=request.festival, sale__completed__isnull=False).count() or 0 fringer_tickets = Ticket.objects.filter(sale__festival=request.festival, sale__completed__isnull=False, refund__isnull=True, description='Fringer').count() or 0 fringers = { 'sold': fringers_sold, 'used': fringer_tickets, 'percent': ((100 * fringer_tickets) / (fringers_sold * 6)) if fringers_sold else 0, } # eFringers efringers_sold = Fringer.objects.filter( user__isnull=False, sale__festival=request.festival, sale__completed__isnull=False).count() or 0 efringer_tickets = Ticket.objects.filter( sale__festival=request.festival, sale__completed__isnull=False, refund__isnull=True, fringer__isnull=False).count() or 0 efringers = { 'sold': efringers_sold, 'used': efringer_tickets, 'percent': ((100 * efringer_tickets) / (efringers_sold * 6)) if efringers_sold else 0, } # Volunteer tickets volunteers_earned = 0 for volunteer in Volunteer.objects.filter(user__festival=request.festival): shifts = volunteer.shifts.count() volunteers_earned += min(shifts, 4) volunteer_tickets = Ticket.objects.filter(description='Volunteer', sale__festival=request.festival, sale__completed__isnull=False, refund__isnull=True).count() or 0 volunteers = { 'earned': volunteers_earned, 'used': volunteer_tickets, 'percent': ((100 * volunteer_tickets) / volunteers_earned) if volunteers_earned else 0, } # Check for HTML format = request.GET['format'] if format == 'HTML': # Render HTML context = { 'dates': date_list, 'sales_by_channel': sales_by_channel, 'sales_by_type': sales_by_type, 'tickets': tickets, 'fringers': fringers, 'efringers': efringers, 'volunteers': volunteers, } return render(request, 'reports/finance/festival_summary.html', context) # Render PDF response = HttpResponse(content_type='application/pdf') doc = SimpleDocTemplate( response, pagesize=portrait(A4), leftMargin=2.5 * cm, rightMargin=2.5 * cm, topMargin=2.5 * cm, bottomMargin=2.5 * cm, ) styles = getSampleStyleSheet() story = [] # Festival banner if request.festival.banner: banner = Image(request.festival.banner.get_absolute_path(), width=16 * cm, height=4 * cm) banner.hAlign = 'CENTER' story.append(banner) story.append(Spacer(1, 1 * cm)) # Render PDF document and return it doc.build(story) return response
#!/usr/bin/env python3 from reportlab.platypus import SimpleDocTemplate from datetime import date from reportlab.platypus import Paragraph, Spacer, Table, Image from reportlab.lib.styles import getSampleStyleSheet styles = getSampleStyleSheet() today = date.today() report = SimpleDocTemplate("processed.pdf") a = "Processed Update on {} {},{}".format(today.strftime("%B"), today.strftime("%d"), today.strftime("%Y")) report_title = Paragraph(a, styles["h1"]) b = "name: Apple\nweight: 500 lbs\n\nname: Avocado\nweight: 200 lbs\n\nname: Blackberry\nweight: 150 lbs\n\nname: Grape\nweight: 200 lbs\n\nname: Kiwifruit\nweight: 250 lbs\n\nname: Lemon\nweight: 300 lbs\n\nname: Mango\nweight: 300 lbs\n\nname: Plum\nweight: 150 lbs\n\nname: Strawberry\nweight: 240 lbs\n\nname: Watermelon\nweight: 500 lbs\n\n" b = b.replace('\n', '<br />\n') report_content = Paragraph(b) report.build([report_title, report_content])
import kanboard from reportlab.lib.pagesizes import A4 from reportlab.lib.styles import getSampleStyleSheet from reportlab.platypus import Paragraph, SimpleDocTemplate styles = getSampleStyleSheet() kb = kanboard.Client( 'http://localhost/jsonrpc.php', 'admin', 'e7c16f5e7565eaceaaadfb1ef55cfe8f15cbe9853966dfcf057d0ecc355a') styleN = styles["Normal"] styleL = styles['UnorderedList'] styleH = styles['Heading1'] story = [] # add some flowables for project in kb.get_my_projects(): print(project['name']) story.append(Paragraph(project['name'], styleH)) text = [] for task in kb.getAllTasks(project_id=project['id'], status_id=1): story.append(Paragraph(task['title'], styleL)) print(" ", task['title']) doc = SimpleDocTemplate('mydoc.pdf', pagesize=A4) doc.build(story)
def pdf_Platypus(request,filtro): response = HttpResponse(content_type='application/pdf')#tipo de rpta #pdf_name = "fotos1.pdf" # nombre para la descarga #response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name #descarga con el nombre indicado buff = BytesIO() #almacena el doc #c = canvas.Canvas(buff) doc = SimpleDocTemplate(buff, pagesize=A4, rightMargin=50,#miderecha leftMargin=50,#mi izquierda topMargin=60, bottomMargin=70,#inferior hoja )#plantilla del doc enlazado al buffer fotos = []#lista para generar doc styles = getSampleStyleSheet()#estilos style = styles['Title'] style1= styles['Normal'] style.spaceAfter = 0.3 * inch style.fontSize = 21 style.fontName = "Times-Roman" style.textColor = "Blue" #style.alignment=TA_JUSTIFY """p = ParagraphStyle('parrafos', fontSize = 28, fontName="Times-Roman")""" header = Paragraph("Listado de Fotos por "+filtro, style)#encabezado doc #header = Paragraph("Listado de Fotos", styles['Heading1'])#encabezado doc #header = Paragraph("Listado de Fotos", p)#encabezado doc """f=Image('static/img/admin.png', width=30, height=30) f.hAlign = 'LEFT' fotos.append(f) fotos.append(Spacer(1, 0.25*inch))""" fotos.append(header)#agrega encabezado del doc a lista headings = ('Nombre', 'Anio', 'descripcion', 'Procede')#cabecera de tabla #filtro=request.GET['tipo'] tipofoto = Tipofoto.objects.get(nombre=filtro) data=tipofoto.foto_set.all() allclientes = [(Paragraph(p.nombre, style1), p.anio, Paragraph(p.descripcion, style1), Paragraph(str(p.procedencia),styles['Normal'])) for p in data]#registros t = Table([headings] + allclientes,colWidths=(50*mm, 10*mm, 70*mm, 30*mm),repeatRows=1)#crea tabla #t = Table([headings] + allclientes,repeatRows=1)#crea tabla t.setStyle(TableStyle( [ ('GRID', (0, 0), (3, -1), 1, colors.dodgerblue), ('LINEBELOW', (0, 0), (-1, 0), 2, colors.darkblue), ('BACKGROUND', (0, 0), (-1, 0), colors.dodgerblue) ] ))#estilos tabla fotos.append(t) #agrega tabla a lista #doc.build(fotos) #genera doc en base a lista doc.title = "Listado de Fotos por "+filtro # si no se coloca aparece anonymous doc.multiBuild(fotos, canvasmaker=FooterCanvas) response.write(buff.getvalue()) #imprimimos el doc que sta en el buffer(pdf) buff.close()#cerramos buffer return response #retornamos pdf
def makePdf(npm_mahasiswa, nama_mahasiswa, tipe_bimbingan, kode_dosen_pembimbing, nama_pembimbing, nidn_pembimbing, tahun_ajaran, photo, judul, total_nilai): checkDir() makeQrcodeVerifySign(link=makeLinkVerify(kode_dosen=kode_dosen_pembimbing, npm_mahasiswa=npm_mahasiswa, tipe_bimbingan=tipe_bimbingan, total_nilai=total_nilai), kode_dosen=kode_dosen_pembimbing, npm_mahasiswa=npm_mahasiswa, tipe_bimbingan=tipe_bimbingan) bulan = date.today().strftime("%m") d2 = date.today().strftime(f"%d {bkd.bulanSwitcher(bulan)} %Y") STUDENT_EMAIL = getStudentEmail(npm_mahasiswa) doc = SimpleDocTemplate( f'./kambing/{npm_mahasiswa}-{kode_dosen_pembimbing}-{STUDENT_EMAIL}.pdf', pagesize=A4, rightMargin=30, leftMargin=30, topMargin=30, bottomMargin=18) doc.pagesize = portrait(A4) elements = [] logo = Image("logoKAMBING.png", 3.5 * inch, 1 * inch) logo.hAlign = "LEFT" elements.append(logo) styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY)) styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER)) styles.add(ParagraphStyle(name='Right', alignment=TA_RIGHT)) ptext = '<font name="Times" size="14">FORMULIR KEGIATAN</font>' elements.append(Paragraph(ptext, styles["Center"])) elements.append(Spacer(1, 12)) ptext = f'<font name="Times" size="14">{tipe_bimbingan}</font>' elements.append(Paragraph(ptext, styles["Center"])) elements.append(Spacer(1, 12)) ptext = '<font name="Times" size="14">TA. ' + tahun_ajaran + '</font>' elements.append(Paragraph(ptext, styles["Center"])) elements.append(Spacer(1, 0.5 * inch)) image = Image(photo, 1.1 * inch, 1.5 * inch) image.hAlign = "RIGHT" elements.append(image) elements.append(Spacer(1, 1.5 * inch)) ptext = '<font size=12> </font>' elements.append(Paragraph(ptext, styles["Center"])) elements.append(Spacer(1, -3 * inch)) table = [[ '<font name="Times" size="12">Nama</font>', '<font name="Times" size="12">: ' + nama_mahasiswa + '</font>' ], [ '<font name="Times" size="12">Npm</font>', '<font name="Times" size="12">: ' + npm_mahasiswa + '</font>' ], [ '<font name="Times" size="12">Judul</font>', '<font name="Times" size="12">: ' + judul + '</font>' ], [ '<font name="Times" size="12">Pembimbing</font>', '<font name="Times" size="12">: ' + nama_pembimbing + '</font>' ]] style = TableStyle([('ALIGN', (1, 1), (-2, -2), 'RIGHT'), ('VALIGN', (0, 0), (0, -1), 'TOP'), ('ALIGN', (0, -1), (-1, -1), 'LEFT'), ('VALIGN', (0, -1), (-1, -1), 'MIDDLE')]) s = getSampleStyleSheet() s = s["BodyText"] s.wordWrap = 'CJK' data1 = [[Paragraph(cell, s) for cell in row] for row in table] tab = Table(data1, hAlign='LEFT', colWidths=[75, 290]) tab.setStyle(style) elements.append(tab) elements.append(Spacer(1, 0.6 * inch)) data = [[ 'Pertemuan', 'Tanggal', 'Sudah Dikerjakan', 'Pekerjaan Selanjutnya', 'Nilai' ]] inner_data_list = makeListDataBimbinganByDosens(npm_mahasiswa, kode_dosen_pembimbing) for i in inner_data_list: data.append(i) nilai_data_list = [ '', '', '', 'Rata-Rata: ', '%.2f' % round(float(total_nilai), 2) ] data.append(nilai_data_list) # Get this line right instead of just copying it from the docs style = TableStyle([('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'), ('ALIGN', (0, 0), (-1, 0), 'CENTER'), ('VALIGN', (0, 0), (0, -1), 'MIDDLE'), ('ALIGN', (0, 0), (0, -1), 'CENTER'), ('VALIGN', (0, -1), (-1, -1), 'MIDDLE'), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('INNERGRID', (0, 0), (-1, -1), 0.50, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black)]) # Configure style and word wrap s = getSampleStyleSheet() s = s["Normal"] s.wordWrap = 'CJK' data2 = [[Paragraph(cell, s) for cell in row] for row in data] t = Table(data2, hAlign='CENTER', colWidths=[62.5, 65, 180, 180, 40]) t.setStyle(style) elements.append(t) elements.append(Spacer(1, 10)) ptext = '<font size=12> </font>' elements.append(Paragraph(ptext, styles["Right"])) elements.append(Spacer(1, .5 * inch)) ptext = '<font name="Times" size="12">Bandung, ' + d2 + '</font>' elements.append(Paragraph(ptext, styles["Right"])) elements.append(Spacer(1, 12)) ptext = '<font name="Times" size="12">Pembimbing,</font>' elements.append(Paragraph(ptext, styles["Right"])) elements.append(Spacer(1, .1 * inch)) data = approve_kambing.getDataPembimbing(npm_mahasiswa, kode_dosen_pembimbing) pembimbingke = approve_kambing.pembimbingPositionAs( data, kode_dosen_pembimbing) if approve_kambing.cekApprovalTrueorFalse(npm_mahasiswa, pembimbingke): qrcode = f"./kambingqrcode/{npm_mahasiswa}-{kode_dosen_pembimbing}-{tipe_bimbingan}.png" else: qrcode = f"./kambingqrcode/whiteimage.png" im = Image(qrcode, 1.5 * inch, 1.5 * inch) im.hAlign = "RIGHT" elements.append(im) ptext = '<font name="Times" size="12">' + nama_pembimbing + '</font>' elements.append(Paragraph(ptext, styles["Right"])) elements.append(Spacer(1, 1)) ptext = '<font name="Times" size="12">NIDN. ' + nidn_pembimbing + '</font>' elements.append(Paragraph(ptext, styles["Right"])) elements.append(Spacer(1, 12)) doc.build(elements)
def get(self, request, *args, **kwargs): response = HttpResponse(content_type='application/pdf')#tipo de rpta #pdf_name = "fotos1.pdf" # nombre para la descarga #response['Content-Disposition'] = 'attachment; filename=%s' % pdf_name #descarga con el nombre indicado buff = BytesIO() #almacena el doc #c = canvas.Canvas(buff) doc = SimpleDocTemplate(buff, pagesize=A4, rightMargin=50,#miderecha leftMargin=50,#mi izquierda topMargin=60, bottomMargin=70,#inferior hoja )#plantilla del doc enlazado al buffer fotos = []#lista para generar doc styles = getSampleStyleSheet()#estilos style = styles['Title'] style1= styles['Normal'] style.spaceAfter = 0.3 * inch style.fontSize = 21 style.fontName = "Times-Roman" style.textColor = "Blue" #style.alignment=TA_JUSTIFY """p = ParagraphStyle('parrafos', fontSize = 28, fontName="Times-Roman")""" filtro = self.kwargs.get('filtro') # El mismo nombre que en tu URL<nombre> #pk = self.kwargs.get('pk') # El mismo nombre que en tu URL fotos.append(Spacer(1, 0.25*inch))#spacio antes del titulo header = Paragraph(self.titulo+filtro, style)#encabezado doc #header = Paragraph("Listado de Fotos", styles['Heading1'])#encabezado doc #header = Paragraph("Listado de Fotos", p)#encabezado doc """f=Image('static/img/admin.png', width=30, height=30) f.hAlign = 'LEFT' fotos.append(f) fotos.append(Spacer(1, 0.25*inch))""" fotos.append(header)#agrega encabezado del doc a lista headings = self.lista_cabeceras#cabecera de tabla #headings = (self.campo1, self.campo2, self.campo3, self.campo4)#cabecera de tabla #filtro=request.GET['tipo'] kwargs1 = {} kwargs1[self.maestrocampo] = filtro #eventos = Evento.objects.filter(**kargs) w objetofk = self.maestro.objects.get(**kwargs1) #tipofoto = self.maestro.objects.get(nombre=filtro) kwargs2 = {} kwargs2[self.modelcampo] = objetofk data=self.model.objects.filter(**kwargs2) #data=self.model.objects.filter(tipofoto=tipofoto) #data=tipofoto.foto_set.all() allclientes=[] for p in data: lista1=self.lista_datos #if f.name==self.lista_campos[0]: for campos in range(len(self.lista_campos)): #campo1=[Paragraph(str(p.campo(self.lista_campos[0])), style1)] lista1[campos]=[Paragraph(str(p.campo(self.lista_campos[campos])), style1)] registro=[lista1[0],lista1[1],lista1[2],lista1[3]] allclientes.append(registro) #allclientes.append([lista1[0],lista1[1],lista1[2],lista1[3]])#agrega cada registro en una lista extendiendola #allclientes.extend([lista]) #allclientes.extend([(Paragraph(p.nombre, style1), p.anio, Paragraph(p.descripcion, style1), Paragraph(str(p.procedencia),styles['Normal']))]) #allclientes = [(Paragraph(p.nombre, style1), p.anio, Paragraph(p.descripcion, style1), Paragraph(str(p.procedencia),styles['Normal'])) for p in data]#registros t = Table([headings] + allclientes,colWidths=self.anchocol,repeatRows=1)#crea tabla #t = Table([headings] + allclientes,repeatRows=1)#crea tabla t.setStyle(TableStyle( [ ('GRID', (0, 0), (3, -1), 1, colors.dodgerblue), ('LINEBELOW', (0, 0), (-1, 0), 2, colors.darkblue), ('BACKGROUND', (0, 0), (-1, 0), colors.dodgerblue) ] ))#estilos tabla fotos.append(t) #agrega tabla a lista #doc.build(fotos) #genera doc en base a lista doc.title = self.titulo+filtro # si no se coloca aparece anonymous doc.multiBuild(fotos, canvasmaker=FooterCanvas) response.write(buff.getvalue()) #imprimimos el doc que sta en el buffer(pdf) buff.close()#cerramos buffer return response #retornamos pdf
class SnowReport: Name = 0 Temp = 0 Time = 0 MountainStatus = 0 RoadStatus = 0 ChainStatus = 0 RoadCondition = 0 Web = 0 ##### Start #### doc = SimpleDocTemplate("form_letter.pdf", pagesize=letter, rightMargin=36, leftMargin=36, topMargin=36, bottomMargin=18) Story = [] styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY)) ########### Head ########## Head = '<b><u><font size=40>Snow Report</font></u></b>' HeadStyle = styles['Heading1'] HeadStyle.alignment = 1 Story.append(Paragraph(Head, HeadStyle)) NewLine(Story) Skifield = ['Remarkable', 'Coronetpeak', 'Cardrona'] for i in Skifield: name = i
def Listado006ProgRuta(ubigeos, WorkSpace, VW_DISTRITO, SEGM_R_RUTAS, SEGM_R_CCPPRUTAS, SEGM_R_AER, EscudoNacional, LogoInei, tipo): # CREADO ESTILOS DE TEXTO h1 = PS( name='Heading1', fontSize=7, leading=8 ) h3 = PS( name='Normal', fontSize=6.5, leading=10, alignment=TA_CENTER ) h4 = PS( name='Normal', fontSize=6.5, leading=10, alignment=TA_LEFT ) h5 = PS( name='Heading1', fontSize=7, leading=8, alignment=TA_RIGHT ) h_sub_tile = PS( name='Heading1', fontSize=10, leading=14, alignment=TA_CENTER ) h_sub_tile_2 = PS( name='Heading1', fontSize=11, leading=14, alignment=TA_CENTER ) for ubigeo in [x for x in arcpy.da.SearchCursor(VW_DISTRITO, ["UBIGEO", "DEPARTAMENTO", "PROVINCIA", "DISTRITO"], "UBIGEO = '{}'".format(ubigeos))]: departamento = ubigeo[1] coddep = ubigeo[0][0:2] provincia = ubigeo[2] codprov = ubigeo[0][2:4] distrito = ubigeo[3] coddist = ubigeo[0][4:6] if tipo == 1: scr_tmp = [x[0] for x in arcpy.da.SearchCursor(SEGM_R_RUTAS, ["SCR"], "UBIGEO = '{}'".format(ubigeo[0]))] scr = u'{} - {}'.format(min(scr_tmp), max(scr_tmp)) else: scr = u'' aerini = min([x[0] for x in arcpy.da.SearchCursor(SEGM_R_AER, ["AER_INI"], "UBIGEO = '{}'".format(ubigeo[0]))]) aerfin = max([x[0] for x in arcpy.da.SearchCursor(SEGM_R_AER, ["AER_FIN"], "UBIGEO = '{}'".format(ubigeo[0]))]) viviendas = sum([x[0] for x in arcpy.da.SearchCursor(SEGM_R_RUTAS, ["N_VIV_RUTA"], "UBIGEO = '{}'".format(ubigeo[0]))]) # LISTA QUE CONTIENE LOS ELEMENTOS A GRAFICAR EN EL PDF Elementos = [] # AGREGANDO IMAGENES, TITULOS Y SUBTITULOS if tipo == 1: Titulo = Paragraph(u'CENSOS NACIONALES 2017: XII DE POBLACIÓN, VII DE VIVIENDA Y III DE COMUNIDADES INDÍGENAS', h_sub_tile) Titulo2 = Paragraph(u'III Censo de Comunidades Nativas y I Censo de Comunidades Campesinas', h_sub_tile) SubTitulo = Paragraph(u'<strong>MARCO DE SECCIONES CENSALES, ÁREAS DE EMPADRONAMIENTO RURAL Y CENTROS POBLADOS DEL DISTRITO</strong>', h_sub_tile_2) else: Titulo = Paragraph(u'CENSO DE LAS ÁREAS AFECTADAS POR ELFENÓMENO DE', h_sub_tile) Titulo2 = Paragraph(u'EL NIÑO COSTERO', h_sub_tile) SubTitulo = Paragraph(u'<strong>MARCO DE ÁREAS DE EMPADRONAMIENTO RURAL Y CENTROS POBLADOS DEL DISTRITO</strong>', h_sub_tile_2) CabeceraPrincipal = [[Titulo, '', ''], [Image(EscudoNacional, width=50, height=50), Titulo2, Image(LogoInei, width=50, height=50)], ['', SubTitulo, '']] Tabla0 = Table(CabeceraPrincipal, colWidths=[2 * cm, 14 * cm, 2 * cm]) Tabla0.setStyle(TableStyle([ ('GRID', (0, 0), (-1, -1), 1, colors.white), ('SPAN', (0, 1), (0, 2)), ('SPAN', (2, 1), (2, 2)), ('SPAN', (0, 0), (2, 0)), ('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE') ])) Elementos.append(Tabla0) Elementos.append(Spacer(0,10)) # CREACION DE LAS TABLAS PARA LA ORGANIZACION DEL TEXTO # Se debe cargar la informacion en aquellos espacios donde se encuentra el texto 'R' Filas = [ ['', '', '', '', Paragraph(u'<b>Doc.CPV.03.159A</b>', h5),''], [Paragraph('<b>A. UBICACIÓN GEOGRÁFICA</b>', h1), '', '', '',Paragraph('<b>B. UBICACIÓN CENSAL</b>', h1), ''], [Paragraph('<b>DEPARTAMENTO</b>', h1), u'{}'.format(coddep), u'{}'.format(departamento), '',Paragraph(u'<b>SECCIÓN Nº</b>', h1), scr], [Paragraph('<b>PROVINCIA</b>', h1), u'{}'.format(codprov), u'{}'.format(provincia), '', Paragraph(u'<b>AER Nº</b>', h1), 'DEL {} AL {}'.format(aerini, aerfin)], [Paragraph('<b>DISTRITO</b>', h1), u'{}'.format(coddist), u'{}'.format(distrito), '', '',''], ['', '','', '',Paragraph('<b>C. TOTAL DE VIVIENDAS DEL DISTRITO.</b>', h1), '{}'.format(viviendas)] ] # Permite el ajuste del ancho de la tabla Tabla = Table(Filas, colWidths=[3.7 * cm, 1 * cm, 7.1 * cm, 0.3 * cm, 4.5 * cm, 2.2 * cm]) # Se cargan los estilos, como bordes, alineaciones, fondos, etc Tabla.setStyle(TableStyle([ ('FONTSIZE', (0, 0), (-1, -1), 7), ('TEXTCOLOR', (0, 0), (5, 0), colors.black), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ALIGN', (5, 2), (5, 5), 'CENTER'), ('ALIGN', (1, 2), (1, 4), 'CENTER'), ('GRID', (0, 1), (2, 4), 1, colors.black), ('GRID', (4, 5), (5, 5), 1, colors.black), ('GRID', (4, 1), (5, 3), 1, colors.black), ('GRID', (4, 3), (5, 3), 1, colors.black), ('SPAN', (0, 1), (2, 1)), ('SPAN', (4, 1), (5, 1)), ('SPAN', (4, 0), (5, 0)), ('BACKGROUND', (0, 1), (2, 1), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (0, 2), (0, 4), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (4, 1), (4, 3), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (4, 5), (4, 5), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)), ('BACKGROUND', (4, 1), (5, 1), colors.Color(220.0 / 255, 220.0 / 255, 220.0 / 255)) ])) # AGREGANDO LAS TABLAS A LA LISTA DE ELEMENTOS DEL PDF Elementos.append(Tabla) Elementos.append(Spacer(0,10)) # AGREGANDO CABECERA N° 2 Filas2 = [ [Paragraph(e, h3) for e in [u"<strong>D. INFORMACIÓN DE LAS SECCIONES CENSALES Y ÁREAS DE EMPADRONAMIENTO DEL DISTRITO</strong>", "", "", "","", "", "", "", ""]], [Paragraph(e, h3) for e in [u"<strong>SECCIÓN Nº</strong>", u"<strong>AER N°</strong>", "", u"<strong>RUTA</strong>", u"<strong>EMP</strong>", u"<strong>CENTRO POBLADO</strong>", "", "",u"<strong>N° ESTIMADO DE VIVIENDAS</strong>"]], [Paragraph(e, h3) for e in ["", u"<strong>INICIAL</strong>", u"<strong>FINAL</strong>", "", "", u"<strong>CÓDIGO</strong>", u"<strong>NOMBRE</strong>", u"<strong>CATEGORÍA</strong>", ""]] ] Tabla2 = Table(Filas2, colWidths = [1.5 * cm, 1.5 * cm, 1.5 * cm, 1.5 * cm, 1.5 * cm, 1.5 * cm, 5.5 * cm, 2 * cm, 2.3 * cm]) Tabla2.setStyle(TableStyle( [ ('GRID', (0, 0), (-1, -1), 1, colors.black), ('VALIGN', (0, 0), (-1, -1), 'CENTER'), ('FONTSIZE', (0, 0), (-1, -1), 7), ('BACKGROUND', (0, 0), (-1, -1), colors.Color(220.0/255, 220.0/255, 220.0/255)), ('SPAN', (0, 1), (0, 2)), ('SPAN', (0, 0), (8, 0)), ('SPAN', (1, 1), (2, 1)), ('SPAN', (3, 1), (3, 2)), ('SPAN', (4, 1), (4, 2)), ('SPAN', (5, 1), (7, 1)), ('SPAN', (8, 1), (8, 2)), ] )) Elementos.append(Tabla2) #CUERPO QUE CONTIENE LOS LA INFORMACION A MOSTRAR nrows = len([x[0] for x in arcpy.da.SearchCursor(SEGM_R_CCPPRUTAS, ["CODCCPP"], "UBIGEO = '{}'".format(ubigeo[0]))]) cursor = [x for x in arcpy.da.SearchCursor(SEGM_R_CCPPRUTAS, ["SCR", "AER_INI", "AER_FIN", "RUTA", "CODCCPP", "NOMCCPP", "CAT_CCPP", "VIV_CCPP", "OR_CCPP", "IDRUTA"] , "UBIGEO = '{}'".format(ubigeo[0]))] cursor.sort(key = lambda n:(n[0], n[3], n[-1])) if nrows > 26: SeccionesRegistros = registros(nrows) SeccionesRegistros.append((0, 26)) SeccionesRegistros.sort(key = lambda n:n[0]) for rangos in SeccionesRegistros: for ccpp in cursor[rangos[0]:rangos[1]]: scr = ccpp[0] if tipo == 1 else u'' aeriniccpp = ccpp[1] aerfinccpp = ccpp[2] rutaccpp = ccpp[3] emp = empadronadorEtiqueta(ccpp[9]) codccpp = ccpp[4] nomccpp = ccpp[5] categoriaccpp = ccpp[6] numviv = ccpp[7] registrosdist = [[scr, u'{}'.format(aeriniccpp), u'{}'.format(aerfinccpp), u'{}'.format(rutaccpp), u'{}'.format(emp), u'{}'.format(codccpp), Paragraph(u'{}'.format(nomccpp), h4), Paragraph(u'{}'.format(categoriaccpp), h4), u'{}'.format(numviv)]] RegistrosIngresados = Table(registrosdist, colWidths = [1.5 * cm, 1.5 * cm, 1.5 * cm, 1.5 * cm, 1.5 * cm, 1.5 * cm, 5.5 * cm, 2 * cm, 2.3 * cm], rowHeights=[0.7 * cm]) RegistrosIngresados.setStyle(TableStyle( [ ('GRID', (0, 0), (-1, -1), 1, colors.black), ('FONTSIZE', (0, 0), (-1, -1), 7), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ALIGN', (0, 0), (5, 0), 'CENTER'), ] )) Elementos.append(RegistrosIngresados) Elementos.append(PageBreak()) Elementos.append(Tabla2) del Elementos[-1] del Elementos[-1] else: for ccpp in cursor: scr = ccpp[0] if tipo == 1 else u'' aeriniccpp = ccpp[1] aerfinccpp = ccpp[2] rutaccpp = ccpp[3] emp = empadronadorEtiqueta(ccpp[9]) codccpp = ccpp[4] nomccpp = ccpp[5] categoriaccpp = ccpp[6] numviv = ccpp[7] registrosdist = [[scr, u'{}'.format(aeriniccpp), u'{}'.format(aerfinccpp), u'{}'.format(rutaccpp), u'{}'.format(emp), u'{}'.format(codccpp), Paragraph(u'{}'.format(nomccpp), h4), Paragraph(u'{}'.format(categoriaccpp), h4), u'{}'.format(numviv)]] RegistrosIngresados = Table(registrosdist, colWidths = [1.5 * cm, 1.5 * cm, 1.5 * cm, 1.5 * cm, 1.5 * cm, 1.5 * cm, 5.5 * cm, 2 * cm, 2.3 * cm], rowHeights=[0.7 * cm]) RegistrosIngresados.setStyle(TableStyle( [ ('GRID', (0, 0), (-1, -1), 1, colors.black), ('FONTSIZE', (0, 0), (-1, -1), 7), ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ALIGN', (0, 0), (5, 0), 'CENTER'), ] )) Elementos.append(RegistrosIngresados) # SE DETERMINAN LAS CARACTERISTICAS DEL PDF (RUTA DE ALMACENAJE, TAMAÑO DE LA HOJA, ETC) if tipo == 1: PathPDF = r"{}\Rural\{}\{}.pdf".format(WorkSpace, ubigeo[0], ubigeo[0]) else: PathPDF = r"{}\Rural_FEN\{}\{}.pdf".format(WorkSpace, ubigeo[0], ubigeo[0]) print PathPDF pdfsec = SimpleDocTemplate(PathPDF, pagesize=A4, rightMargin=65, leftMargin=65, topMargin=0.5*cm, bottomMargin=0.5*cm,) # GENERACION DEL PDF FISICO pdfsec.build(Elementos) # IMPRESION DE FINALIZADO finalizado = "Finalizado" return finalizado
def make_doc(): pdfmetrics.registerFont(TTFont('HelvRu', 'helv_ru.ttf')) pdf = io.BytesIO() doc = SimpleDocTemplate(pdf, leftMargin=30, rightMargin=30, topMargin=20, bottomMargin=0, pagesize=landscape(A4)) story = [] data = [[ 'Title', 'Last Name', 'First Name', 'Middle Name', 'Extension', 'Mobile phone', 'E-Mail', 'Birthday' ]] cur = g.db.execute( 'SELECT position, lastname, firstname, middlename, intphone, cellphone, email, birthday FROM persons WHERE active ORDER BY lastname' ) for row in cur.fetchall(): data.append([ row[0], row[1], row[2], row[3], row[4], row[5], row[6], row[7], ]) t = Table(data) data_len = len(data) for each in range(data_len): if each == 0: bg_color = colors.lightblue elif each % 2 == 0: bg_color = colors.whitesmoke else: bg_color = colors.lightgrey t.setStyle( TableStyle([('BACKGROUND', (0, each), (-1, each), bg_color)])) t.setStyle( TableStyle([("BOX", (0, 0), (-1, -1), 0.25, colors.black), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('FONT', (0, 0), (-1, 100), font, 9)])) text_content = datetime.datetime.now().strftime("%d.%m.%Y %H:%M:%S") styles = getSampleStyleSheet() # styleN = styles['Normal'] styleN = ParagraphStyle( name='Normal', fontName=font, fontSize=5, ) styleH = ParagraphStyle( name='Normal', fontName=font, fontSize=16, alignment=1, leading=20, ) styleH1 = ParagraphStyle( name='Normal', fontName=font, fontSize=10, alignment=1, leading=15, ) p = Paragraph(text_content, styleN) h = Paragraph(header_content, styleH) h1 = Paragraph(header_content1, styleH1) story.append(h) story.append(h1) story.append(t) story.append(p) doc.build(story) pdf.seek(0) return pdf
def makePDFAll(): c = canvas.Canvas("", pagesize=A4) doc = SimpleDocTemplate("./Informe_.pdf", pagesize=A4, rightMargin=40, leftMargin=40, topMargin=100, bottomMargin=45) #print "BLE" width, height = A4 contents = [] logo = "./Toyota.png" im = Image(logo, 4 * cm, 2 * cm) im.hAlign = 'LEFT' #contents.append(im) texto1 = "Informe Toyota" styles = getSampleStyleSheet() title = Paragraph("Informe Recertificación Usuarios TFSE", styles["Title"]) styles.add( ParagraphStyle(name='Justify', alignment=TA_JUSTIFY, fontSize=13, leading=20, leftIndent=55)) styles.add( ParagraphStyle(name='Justify0', alignment=TA_JUSTIFY, fontSize=12, spaceBefore=5, leading=10, leftIndent=60)) styles.add( ParagraphStyle(name='Justify1', alignment=TA_JUSTIFY, fontSize=12, spaceBefore=20, leading=18, leftIndent=60)) styles.add( ParagraphStyle(name='Justify2', alignment=TA_JUSTIFY, fontSize=11, leading=13, rightIndent=80, leftIndent=60, backColor='#F0F0F0', textColor='black', bulletIndent=75, bulletFontSize=5)) styles.add( ParagraphStyle(name='Justify3', alignment=TA_JUSTIFY, fontSize=11, leading=13, borderPadding=(0, 0, 3, 0), rightIndent=80, leftIndent=60, backColor='#F0F0F0', textColor='blue', bulletIndent=83)) styles.add( ParagraphStyle(name='Justify3r', alignment=TA_JUSTIFY, fontSize=11, leading=13, borderPadding=(0, 0, 3, 0), rightIndent=80, leftIndent=60, backColor='#F0F0F0', textColor='red', bulletIndent=83)) valor1 = [] uidss = [] #contents.append(title) uidss = getAllUserForPDF() contador = 0 for uidd in uidss: print "\n==========================================================" print "\n\n+Doing user ....\n" print "\t*UID:" + uidd puestoTrabajo, rolesPuesto, rolesDeMas, rolesDeMenos = rellenarUserForPDF( uidd) print "\n\tPUESTO TRABAJO ES: " + puestoTrabajo conts = contentsForEachUserForPDF(uidd, puestoTrabajo, rolesPuesto, rolesDeMas, rolesDeMenos, styles, contador) print "\n\tCreada con éxito página pdf con datos del usuario... " contents = contents + conts contador = contador + 1 doc.build(contents, onFirstPage=addPageNumberFirstPage, onLaterPages=addPageNumber) print "\n\n\nFin de PDF .....\n"
def report(self, weather_history, title): # set some characteristics for pdf document doc = SimpleDocTemplate( self.buffer, rightMargin=72, leftMargin=72, topMargin=30, bottomMargin=72, pagesize=self.pageSize) # a collection of styles offer by the library styles = getSampleStyleSheet() # add custom paragraph style styles.add(ParagraphStyle( name="TableHeader", fontSize=11, alignment=TA_CENTER, fontName="FreeSansBold")) styles.add(ParagraphStyle( name="ParagraphTitle", fontSize=11, alignment=TA_JUSTIFY, fontName="FreeSansBold")) styles.add(ParagraphStyle( name="Justify", alignment=TA_JUSTIFY, fontName="FreeSans")) # list used for elements added into document data = [] data.append(Paragraph(title, styles['Title'])) # insert a blank space data.append(Spacer(1, 12)) table_data = [] # table header table_data.append([ Paragraph('Date', styles['TableHeader']), Paragraph('Town', styles['TableHeader']), Paragraph('Max temp', styles['TableHeader']), Paragraph('Min temp', styles['TableHeader']), Paragraph('Wind speed', styles['TableHeader']), Paragraph('Precip', styles['TableHeader']), Paragraph('Precip probab', styles['TableHeader'])]) for wh in weather_history: data.append(Paragraph(u'{0}'.format(wh), styles['ParagraphTitle'])) data.append(Spacer(1, 12)) data.append(Paragraph(wh.observations, styles['Justify'])) data.append(Spacer(1, 24)) # add a row to table table_data.append( [wh.date, Paragraph(wh.town.name, styles['Justify']), u"{0} °C".format(wh.max_temperature), u"{0} °C".format(wh.min_temperature), u"{0} km/h".format(wh.wind_speed), u"{0} mm".format(wh.precipitation), u"{0} %".format(wh.precipitation_probability)]) # create table wh_table = Table(table_data, colWidths=[doc.width/7.0]*7) wh_table.hAlign = 'LEFT' wh_table.setStyle(TableStyle( [('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.5, colors.black), ('VALIGN', (0, 0), (-1, 0), 'MIDDLE'), ('BACKGROUND', (0, 0), (-1, 0), colors.gray)])) data.append(wh_table) data.append(Spacer(1, 48)) # add line chart temperatures, days = get_temperatures(weather_history) line_chart = self.line_chart_draw(temperatures, days) data.append(line_chart) data.append(Spacer(1, 48)) data.append(Spacer(1, 48)) # add bar chart wind_speed, towns = get_wind_speed(weather_history) days = get_str_days() bar_chart = self.vertical_bar_chart_draw(wind_speed, days, towns) data.append(bar_chart) data.append(Spacer(1, 48)) data.append(Spacer(1, 48)) # add pie chart prec_percentage = precip_prob_sum(weather_history) llabels = ['0-20 %', '21-40 %', '41-60 %', '61-80 %', '81-100 %'] pie_chart = self.pie_chart_draw(prec_percentage, llabels) data.append(pie_chart) # create document doc.build(data, onFirstPage=self.pageNumber, onLaterPages=self.pageNumber) pdf = self.buffer.getvalue() self.buffer.close() return pdf
def makePDF(uid, puestoTrabajo, rolesPuesto, rolesDeMas, rolesDeMenos): c = canvas.Canvas("./Informe.pdf", pagesize=A4) doc = SimpleDocTemplate("./Informe_" + uid + ".pdf", pagesize=A4, rightMargin=20, leftMargin=20, topMargin=20, bottomMargin=15) width, height = A4 contents = [] logo = "./Toyota.png" im = Image(logo, 4 * cm, 2 * cm) im.hAlign = 'LEFT' contents.append(im) texto1 = "Informe Toyota" styles = getSampleStyleSheet() title = Paragraph("Informe Recertificación Usuarios TFSE", styles["Title"]) styles.add( ParagraphStyle(name='Justify', alignment=TA_JUSTIFY, fontSize=14, leftIndent=60)) styles.add( ParagraphStyle(name='Justify1', alignment=TA_JUSTIFY, fontSize=12, leftIndent=65)) styles.add( ParagraphStyle(name='Justify2', alignment=TA_JUSTIFY, fontSize=12, textColor='black', bulletIndent=75, bulletFontSize=5)) styles.add( ParagraphStyle(name='Justify3', alignment=TA_JUSTIFY, fontSize=12, textColor='blue', bulletIndent=83)) styles.add( ParagraphStyle(name='Justify3r', alignment=TA_JUSTIFY, fontSize=12, textColor='red', bulletIndent=83)) valor1 = [] ptext = '<font size=12>%s</font>' % texto1 contents.append(title) contents.append(Spacer(2 * cm, 1 * cm)) contents.append( Paragraph("<b>Identificador: " + uid + "</b>", styles["Justify"])) contents.append(Spacer(3 * cm, 0.5 * cm)) contents.append( Paragraph("Puesto de trabajo: " + puestoTrabajo, styles["Justify1"])) contents.append(Spacer(3 * cm, 0.3 * cm)) contents.append( Paragraph( "El puesto de trabajo " + puestoTrabajo + " tiene los siguientes roles", styles["Justify1"])) contents.append(Spacer(3 * cm, 0.2 * cm)) for rp in rolesPuesto: rp = re.sub('<br>', '', rp) if rp.startswith('-'): if '*' in rp: valor1 = rp.split('*') contents.append( Paragraph(re.sub('-', '', valor1[0]) + ":", styles["Justify2"], bulletText="\xe2\x96\xaa")) contents.append( Paragraph(valor1[1], styles["Justify3"], bulletText="\xe2\x80\xa2")) elif rp.startswith('*'): contents.append( Paragraph(re.sub('\*', '', rp), styles["Justify3"], bulletText="\xe2\x80\xa2")) contents.append(Spacer(3 * cm, 0.5 * cm)) contents.append( Paragraph( "Además de los roles de puesto de trabajo, el usuario tiene los siguientes roles adicionales:", styles["Justify1"])) contents.append(Spacer(3 * cm, 0.2 * cm)) # valor1=[] for rpm in rolesDeMas: rpm = re.sub('<br>', '', rpm) if rpm.startswith('-'): if '*' in rpm: valor1 = rpm.split('*') contents.append( Paragraph(re.sub('-', '', valor1[0]) + ":", styles["Justify2"], bulletText="\xe2\x96\xaa")) contents.append( Paragraph(valor1[1], styles["Justify3r"], bulletText="\xe2\x80\xa2")) elif rpm.startswith('*'): contents.append( Paragraph(re.sub('\*', '', rpm), styles["Justify3r"], bulletText='*')) contents.append(Spacer(3 * cm, 0.5 * cm)) contents.append( Paragraph( "El usuario carece de los siguientes roles que pertenecen a la definición del puesto de trabajo:", styles["Justify1"])) contents.append(Spacer(3 * cm, 0.2 * cm)) # valor1=[] for rpm in rolesDeMenos: # rp = re.sub('<br>', '', rp) # contents.append(Paragraph(rp, styles["Justify2"], bulletText='-')) rpm = re.sub('<br>', '', rpm) if rpm.startswith('-'): if '*' in rpm: valor1 = rpm.split('*') contents.append( Paragraph(re.sub('-', '', valor1[0]) + ":", styles["Justify2"], bulletText="\xe2\x97\xbe")) contents.append( Paragraph(valor1[1], styles["Justify3r"], bulletText='*')) elif rpm.startswith('*'): contents.append( Paragraph(re.sub('\*', '', rpm), styles["Justify3r"], bulletText="\xe2\x80\xa2")) #doc.build(contents, onFirstPage=addPageNumber(c, doc), onLaterPages=addPageNumber(c,doc)) doc.build(contents)
def admission_pdf(request, performance_uuid): # Get performance performance = get_object_or_404(ShowPerformance, uuid=performance_uuid) # Create admission list as a Platypus story response = HttpResponse(content_type="application/pdf") response["Content-Disposition"] = f"filename=admission{performance.id}.pdf" doc = SimpleDocTemplate( response, pagesize=portrait(A4), leftMargin=2.5 * cm, rightMargin=2.5 * cm, topMargin=2.5 * cm, bottomMargin=2.5 * cm, ) styles = getSampleStyleSheet() story = [] # Festival banner if performance.show.festival.banner: banner = Image(os.path.join(settings.MEDIA_ROOT, performance.show.festival.banner.path), width=16 * cm, height=4 * cm) banner.hAlign = 'CENTER' story.append(banner) story.append(Spacer(1, 1 * cm)) # Show and performance table = Table(( (Paragraph("<para><b>Show:</b></para>", styles['Normal']), performance.show), (Paragraph("<para><b>ShowPerformance:</b></para>", styles['Normal']), f"{performance.date:%a, %e %b} at {performance.time:%I:%M %p}"), ), colWidths=(4 * cm, 12 * cm), hAlign='LEFT') story.append(table) story.append(Spacer(1, 1 * cm)) # Tickets tableData = [] tableData.append( (Paragraph(f"<para><b>Ticket No</b></para>", styles['Normal']), Paragraph(f"<para><b>Customer</b></para>", styles['Normal']), Paragraph(f"<para><b>Type</b></para>", styles['Normal']))) for ticket in performance.tickets.filter( sale__completed__isnull=False).order_by('id'): if ticket.refund: tableData.append( (Paragraph(f"<para><strike>{ticket.id}</strike></para>", styles['Normal']), Paragraph( f"<para><strike>{ticket.sale.customer}</strike></para>", styles['Normal']), Paragraph( f"<para><strike>{ticket.description}</strike></para>", styles['Normal']))) else: tableData.append((Paragraph(f"<para>{ticket.id}</para>", styles['Normal']), Paragraph(f"<para>{ticket.sale.customer}</para>", styles['Normal']), Paragraph(f"<para>{ticket.description}</para>", styles['Normal']))) table = Table( tableData, colWidths=(4 * cm, 8 * cm, 4 * cm), hAlign='LEFT', ) story.append(table) # Create PDF document and return it doc.build(story) return response
def album_pdf(request, id): """ Produces a printable PDF of the album sutable for slipping in a CD case. """ obj = models.Album.objects.get(pk=id) styles = { 'normal': ParagraphStyle(name='normal', fontName='Times-Roman', fontSize=0.5 * cm, leading=0.45 * cm), 'small': ParagraphStyle(name='small', fontName='Times-Roman', fontSize=0.3 * cm, leading=0.29 * cm), 'review': ParagraphStyle(name='review', fontName='Times-Roman', fontSize=10, leading=10.2), 'song': ParagraphStyle(name='song', fontName='Times-Roman', fontSize=0.4 * cm, alignment=1), 'location': ParagraphStyle(name='location', fontName="Helvetica-Bold", fontSize=0.4 * cm) } # Build the artist/album header art_alb_style = [('BACKGROUND', (0, 0), (-1, 0), colors.black), ('TEXTCOLOR', (0, 0), (-1, 0), colors.white), ('LEFTPADDING', (0, 0), (-1, 0), 0.4 * cm), ('FONT', (0, 0), (-1, 0), 'Helvetica', 0.3 * cm), ('LEFTPADDING', (0, 1), (-1, 1), 0.2 * cm), ('RIGHTPADDING', (0, 1), (-1, 1), 1), ('TOPPADDING', (0, 0), (-1, -1), -0.27 * cm), ('BOTTOMPADDING', (0, 0), (-1, -1), 0), ('LINEAFTER', (0, 1), (0, 1), 0.3, colors.black), ('VALIGN', (0, 1), (-1, -1), 'MIDDLE')] album = Paragraph(escape(obj.album), styles['normal']) if obj.artist: artist = Paragraph(escape(obj.artist.artist), styles['normal']) # Change the style and spacing if they're too big artist.wrap(5.8 * cm, 1 * cm) if artist.minWidth() > 5.8 * cm or len( artist.getActualLineWidths0()) > 2: artist = Paragraph(artist.text, styles['small']) art_alb_style.append(('TOPPADDING', (0, 1), (0, 1), -0.1 * cm)) album.wrap(5.8 * cm, 1 * cm) if album.minWidth() > 5.8 * cm or len( album.getActualLineWidths0()) > 2: album = Paragraph(album.text, styles['small']) art_alb_style.append(('TOPPADDING', (1, 1), (1, 1), -0.1 * cm)) artist_album = Table([[u'Artist', u'Album'], [artist, album]], colWidths=[6 * cm, 6 * cm], rowHeights=[0.3 * cm, 1.3 * cm], style=art_alb_style) else: #compilation artist_album = Table([[u'Album'], [album]], colWidths=[12 * cm], rowHeights=[0.3 * cm, 1.3 * cm], style=art_alb_style) # Build the song section song_style = [('TOPPADDING', (0, 0), (-1, -1), -2), ('BOTTOMPADDING', (0, 0), (-1, -1), 0), ('LEFTPADDING', (0, 0), (-1, -1), 0), ('RIGHTPADDING', (0, 0), (-1, -1), 0), ('BACKGROUND', (0, 0), (-1, 0), colors.black), ('TEXTCOLOR', (0, 0), (-1, 0), colors.white), ('FONT', (0, 0), (-1, 0), 'Helvetica', 0.31 * cm), ('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('LEFTPADDING', (1, 0), (1, 0), 0.4 * cm), ('ALIGN', (1, 0), (1, -1), 'LEFT'), ('INNERGRID', (0, 1), (-1, -1), 0.3, colors.black), ('LINEBELOW', (0, -1), (-1, -1), 0.3, colors.black), ('VALIGN', (0, 1), (-1, -1), 'MIDDLE'), ('TOPPADDING', (1, 1), (1, -1), -1), ('BOTTOMPADDING', (1, 1), (1, -1), 0.2 * cm), ('LEFTPADDING', (1, 1), (1, -1), 0.1 * cm)] song_data = [[u'#', u'Song Title', u'In', u'Tempo', u'Time', u'End']] good_songs = obj.song_set.filter(rating__gt=3).order_by('-rating') for i in range(0, 5): if i >= len(good_songs): song_data.append(['', '', '', '', '', '']) continue if good_songs[i].comp_artist: song_name = u'%s — %s' % (good_songs[i].song, good_songs[i].artist.artist) else: song_name = good_songs[i].song song_name = Paragraph(escape(song_name), styles['normal']) song_name.wrap(6.1 * cm, cm) if len(song_name.getActualLineWidths0()) > 1: song_name = Paragraph(song_name.text, styles['small']) song_style.append(('BOTTOMPADDING', (1, i + 1), (1, i + 1), 2)) if good_songs[i].rating > 4: track = u'<b><u>%s</u></b>' % escape(good_songs[i].track) else: track = escape(good_songs[i].track) song_data.append([ Paragraph(track, styles['song']), song_name, Paragraph(escape(good_songs[i].ramp), styles['song']), Paragraph(escape(good_songs[i].tempo), styles['song']), Paragraph(escape(good_songs[i].length), styles['song']), Paragraph(escape(good_songs[i].post), styles['song']) ]) songs = Table( song_data, colWidths=[0.9 * cm, 6.2 * cm, 1.2 * cm, 1.2 * cm, 1.3 * cm, 1.2 * cm], style=song_style) # build the review review = Paragraph(escape(obj.review), styles['review']) # build the other track listing other_style = [('TOPPADDING', (0, 0), (0, -1), 0), ('BOTTOMPADDING', (0, 0), (0, -1), 0), ('BACKGROUND', (0, 0), (0, -1), colors.black), ('TEXTCOLOR', (0, 0), (0, -1), colors.white), ('RIGHTPADDING', (0, 0), (0, -1), 0.2 * cm), ('FONT', (0, 0), (0, -1), 'Helvetica-Bold', 0.3 * cm), ('ALIGN', (0, 0), (0, -1), 'RIGHT'), ('LINEABOVE', (1, 0), (1, 1), 0.3, colors.black), ('LINEABOVE', (0, 0), (0, 0), 0.3, colors.black), ('VALIGN', (1, 0), (1, 1), 'TOP'), ('TOPPADDING', (1, 0), (1, -1), -1.5)] also_play = list(obj.song_set.filter(rating__gt=1, rating__lt=4)) + good_songs[5:] also_play = u', '.join([ ((u'<b><u>%s</u></b>' % x.track) if x.rating > 2 else x.track) for x in also_play ]) also_play = Paragraph(also_play, styles['review']) do_not_play = u', '.join( obj.song_set.filter(rating=0).values_list('track', flat=True)) do_not_play = Paragraph(do_not_play, styles['review']) other_tracks = Table( [[u'Also recommended:', also_play], [u'DO NOT PLAY:', do_not_play]], colWidths=[4 * cm, 8 * cm], rowHeights=[0.35 * cm, 0.35 * cm], style=other_style) #Put them all together final_style = [('BOX', (0, 0), (-1, -1), 1, colors.black), ('LEFTPADDING', (0, 0), (-1, -1), 0), ('TOPPADDING', (0, 0), (-1, -1), 0), ('RIGHTPADDING', (0, 0), (-1, -1), 0), ('BOTTOMPADDING', (0, 0), (-1, -1), 0), ('VALIGN', (0, 0), (0, 2), 'TOP'), ('RIGHTPADDING', (0, 2), (0, 2), 0.1 * cm), ('LEFTPADDING', (0, 2), (0, 2), 0.2 * cm)] elems = [] elems.append( Table([[artist_album], [songs], [review], [other_tracks]], colWidths=[12 * cm], rowHeights=[1.6 * cm, 3.9 * cm, 5.8 * cm, 0.7 * cm], style=final_style)) # For the CD location on the edge elems.append(Paragraph(escape(obj.location), styles['location'])) response = HttpResponse(mimetype='application/pdf') doc = SimpleDocTemplate(response, pagesize=letter, title=u"Insert for the CD") doc.build(elems) return response
def venue_summary(request): # Get selection criteria venue = Venue.objects.get(id=int(request.GET['venue'])) date = datetime.datetime.strptime(request.GET['date'], '%Y%m%d') # First/last checkpoints periods = [] first = Checkpoint.objects.filter(created__date=date, venue=venue).order_by('created').first() last = Checkpoint.objects.filter(created__date=date, venue=venue).order_by('created').last() if first and last and first != last: sales_cash = Sale.objects.filter(venue=venue, created__date=date).aggregate( Sum('amount'))['amount__sum'] or 0 sales_fringers = Fringer.objects.filter( sale__venue=venue, sale__created__date=date).count() or 0 sales_buttons = Sale.objects.filter( venue=venue, created__date=date).aggregate( Sum('buttons'))['buttons__sum'] or 0 periods.append({ 'title': f"Daily Summary: {first.created.astimezone():%I:%M%p} to {last.created.astimezone():%I:%M%p}", 'open': first, 'close': last, 'sales': { 'cash': sales_cash, 'fringers': sales_fringers, 'buttons': sales_buttons, }, 'variance': { 'cash': last.cash - first.cash - sales_cash, 'fringers': last.fringers - first.fringers + sales_fringers, 'buttons': last.buttons - first.buttons + sales_buttons, }, }) else: periods.append({ 'title': 'Daily Summary', 'open': first, 'close': last, }) # Individual performances for performance in ShowPerformance.objects.filter( show__venue=venue, date=date).order_by('time'): open = performance.open_checkpoint if performance.has_open_checkpoint else None close = performance.close_checkpoint if performance.has_close_checkpoint else None if open and close: sales_cash = Sale.objects.filter( venue=venue, created__gt=open.created, created__lt=close.created).aggregate( Sum('amount'))['amount__sum'] or 0 sales_fringers = Fringer.objects.filter( sale__venue=venue, sale__created__gt=open.created, sale__created__lt=close.created).count() or 0 sales_buttons = Sale.objects.filter( venue=venue, created__gt=open.created, created__lt=close.created).aggregate( Sum('buttons'))['buttons__sum'] or 0 periods.append({ 'title': f"{performance.time:%I:%M%p} {performance.show.name}", 'open': open, 'close': close, 'sales': { 'cash': sales_cash, 'fringers': sales_fringers, 'buttons': sales_buttons, }, 'variance': { 'cash': close.cash - open.cash - sales_cash, 'fringers': close.fringers - open.fringers + sales_fringers, 'buttons': close.buttons - open.buttons + sales_buttons, }, }) else: periods.append({ 'title': f"{performance.time:%I:%M%p} {performance.show.name}", 'open': open, 'close': close, }) # Check for HTML format = request.GET['format'] if format == 'HTML': # Render HTML context = { 'venue': venue, 'date': date, 'periods': periods, } return render(request, 'reports/finance/venue_summary.html', context) # Render PDF response = HttpResponse(content_type='application/pdf') doc = SimpleDocTemplate( response, pagesize=portrait(A4), leftMargin=2.5 * cm, rightMargin=2.5 * cm, topMargin=2.5 * cm, bottomMargin=2.5 * cm, ) styles = getSampleStyleSheet() story = [] # Festival banner if venue.festival.banner: banner = Image(venue.festival.banner.get_absolute_path(), width=16 * cm, height=4 * cm) banner.hAlign = 'CENTER' story.append(banner) story.append(Spacer(1, 1 * cm)) # Venue and date table = Table( ( (Paragraph('<para><b>Venue:</b></para>', styles['Normal']), venue.name), (Paragraph('<para><b>Date:</b></para>', styles['Normal']), f"{date:%A, %d %B}"), ), colWidths=(4 * cm, 12 * cm), ) story.append(table) story.append(Spacer(1, 0.5 * cm)) # Periods for period in periods: table_data = [] table_styles = [ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('ALIGN', (0, 0), (-1, -1), 'RIGHT'), ] table_data.append((Paragraph(f"<para><b>{period['title']}</b></para>", styles['Normal']), )) table_styles.append(('SPAN', (0, 0), (4, 0))) table_styles.append(('ALIGN', (0, 0), (0, 0), 'LEFT')) table_data.append(( '', 'Open', 'Sales', 'Close', 'Variance', )) table_data.append(( 'Cash', f"£{ period['open'].cash }" if period.get('open', None) else '', f"£{ period['sales']['cash'] }" if period.get('sales', None) else '', f"£{ period['close'].cash }" if period.get('close', None) else '', f"£{ period['variance']['cash'] }" if period.get('variance', None) else '', )) table_data.append(( 'Fringers', period['open'].fringers if period.get('open', None) else '', period['sales']['fringers'] if period.get('sales', None) else '', period['close'].fringers if period.get('close', None) else '', period['variance']['fringers'] if period.get('variance', None) else '', )) table_data.append(( 'Buttons', period['open'].buttons if period.get('open', None) else '', period['sales']['buttons'] if period.get('sales', None) else '', period['close'].buttons if period.get('close', None) else '', period['variance']['buttons'] if period.get('variance', None) else '', )) if period['open'] and period['open'].notes: table_data.append(( 'Open notes', Paragraph(period['open'].notes, styles['Normal']), )) row = len(table_data) - 1 table_styles.append(('SPAN', (1, row), (4, row))) if period['close'] and period['close'].notes: table_data.append(( 'Close notes', Paragraph(period['close'].notes, styles['Normal']), )) row = len(table_data) - 1 table_styles.append(('SPAN', (1, row), (4, row))) table = Table( table_data, colWidths=(3 * cm, 3 * cm, 3 * cm, 3 * cm, 3 * cm), style=table_styles, ) story.append(table) story.append(Spacer(1, 0.5 * cm)) # Render PDF document and return it doc.build(story) return response
def testBidi(self): fontName = getAFont() # create styles based on the registered font stySTD = ParagraphStyle('STD', fontName=fontName) styRJ = ParagraphStyle('RJ', parent=stySTD, alignment=TA_RIGHT) styLTR = ParagraphStyle('LTR', parent=stySTD, wordWrap='LTR') styRTL = ParagraphStyle('RTL', parent=stySTD, alignment=TA_RIGHT, wordWrap='RTL', spaceAfter=12) # strings for testing Normal & LTR styles ltrStrings = [ # English followed by Arabic. b'English followed by \xd8\xb9\xd8\xb1\xd8\xa8\xd9\x8a.', # English with Arabic in the middle b'English with \xd8\xb9\xd8\xb1\xd8\xa8\xd9\x8a in the middle.', # English symbols (!@#$%^&*) Arabic b'English symbols (!@#$%^&*) \xd8\xb9\xd8\xb1\xd8\xa8\xd9\x8a.', # ((testing integers in LTR)) b'123 LTR 123 Integers 123.', # ((testing decimals in LTR)) b'456.78 LTR 456.78 Decimals 456.78.', # Long English text with RTL script in the middle, splitting over multiple lines b'Long \xd8\xb7\xd9\x88\xd9\x8a\xd9\x84 English text' b' \xd9\x86\xd8\xb5 \xd8\xb9\xd8\xb1\xd8\xa8\xd9\x8a with RTL script' b' \xd9\x83\xd8\xaa\xd8\xa7\xd8\xa8\xd8\xa9 \xd9\x85\xd9\x86' b' \xd8\xa7\xd9\x84\xd9\x8a\xd9\x85\xd9\x8a\xd9\x86 \xd8\xa5\xd9\x84\xd9\x89' b' \xd8\xa7\xd9\x84\xd9\x8a\xd8\xb3\xd8\xa7\xd8\xb1 in the middle,' b' \xd9\x81\xd9\x8a \xd8\xa7\xd9\x84\xd9\x88\xd8\xb3\xd8\xb7\xd8\x8c' b' splitting \xd9\x85\xd9\x82\xd8\xb3\xd9\x85 over \xd8\xb9\xd9\x84\xd9\x89' b' multiple lines \xd8\xb9\xd8\xaf\xd8\xa9 \xd8\xb3\xd8\xb7\xd9\x88\xd8\xb1.', ] # strings for testing RTL rtlStrings = [ # Arabic followed by English b'\xd8\xb9\xd8\xb1\xd8\xa8\xd9\x8a \xd9\x85\xd8\xaa\xd8\xa8\xd9\x88\xd8\xb9' b' \xd8\xa8\xd9\x80 English.', # Arabic with English in the middle b'\xd8\xb9\xd8\xb1\xd8\xa8\xd9\x8a \xd9\x85\xd8\xb9 English \xd9\x81\xd9\x8a' b' \xd8\xa7\xd9\x84\xd9\x85\xd9\x86\xd8\xaa\xd8\xb5\xd9\x81.', # Arabic symbols (!@##$%^&*) English b'\xd8\xb1\xd9\x85\xd9\x88\xd8\xb2 \xd8\xb9\xd8\xb1\xd8\xa8\xd9\x8a\xd8\xa9' b' (!@#$%^&*) English.', # 123 from right to left 123 integer numbers 123. ((testing integers in RTL)) b'123 \xd9\x85\xd9\x86 \xd8\xa7\xd9\x84\xd9\x8a\xd9\x85\xd9\x8a\xd9\x86' b' \xd8\xa5\xd9\x84\xd9\x89 \xd8\xa7\xd9\x84\xd9\x8a\xd8\xb3\xd8\xa7\xd8\xb1' b' 123 \xd8\xa3\xd8\xb1\xd9\x82\xd8\xa7\xd9\x85' b' \xd8\xb5\xd8\xad\xd9\x8a\xd8\xad\xd8\xa9 123.', # 456.78 from right to left 456.78 decimal numbers 456.78. ((testing decimals in RTL)) b'456.78 \xd9\x85\xd9\x86 \xd8\xa7\xd9\x84\xd9\x8a\xd9\x85\xd9\x8a\xd9\x86' b' \xd8\xa5\xd9\x84\xd9\x89 \xd8\xa7\xd9\x84\xd9\x8a\xd8\xb3\xd8\xa7\xd8\xb1' b' 456.78 \xd8\xa3\xd8\xb1\xd9\x82\xd8\xa7\xd9\x85' b' \xd8\xb9\xd8\xb4\xd8\xb1\xd9\x8a\xd8\xa9 456.78.', # Long Arabic text with LTR text in the middle, splitting over multiple lines b'\xd9\x86\xd8\xb5 \xd8\xb9\xd8\xb1\xd8\xa8\xd9\x8a \xd8\xb7\xd9\x88\xd9\x8a\xd9\x84' b' Long Arabic text \xd9\x85\xd8\xb9 with \xd9\x83\xd8\xaa\xd8\xa7\xd8\xa8\xd8\xa9' b' \xd9\x85\xd9\x86 \xd8\xa7\xd9\x84\xd9\x8a\xd8\xb3\xd8\xa7\xd8\xb1' b' \xd8\xa5\xd9\x84\xd9\x89 \xd8\xa7\xd9\x84\xd9\x8a\xd9\x85\xd9\x8a\xd9\x86' b' LTR script \xd9\x81\xd9\x8a \xd8\xa7\xd9\x84\xd9\x88\xd8\xb3\xd8\xb7\xd8\x8c' b' in the middle, \xd9\x85\xd9\x82\xd8\xb3\xd9\x85 splitted' b' \xd8\xb9\xd9\x84\xd9\x89 over \xd8\xb9\xd8\xaf\xd8\xa9' b' \xd8\xb3\xd8\xb7\xd9\x88\xd8\xb1 multiple lines.' ] assert len(ltrStrings) == len(rtlStrings) n = len(ltrStrings) # create a store to be printed story = [] story.append( Paragraph( "<b><i>Following pairs of left justified texts have style.wordWrap=None & 'LTR'.</i></b><br/>", stySTD)) # write every LTR string and its corresponding RTL string to be matched. for i in xrange(n): story.append(Paragraph(ltrStrings[i], stySTD)) story.append(Paragraph(ltrStrings[i], styLTR)) story.append( Paragraph( "<br/><b><i>Following pairs of right justfied texts have style.wordWrap=None & 'RTL'.</i></b><br/>", stySTD)) for i in xrange(n): story.append(Paragraph(rtlStrings[i], styRJ)) story.append(Paragraph(rtlStrings[i], styRTL)) story.append( Paragraph( "<b><i><br/>Following texts have style.wordWrap='RTL'</i></b>", stySTD)) # a few additional scripts for testing. story.append( Paragraph( b'\xd9\x87\xd8\xb0\xd9\x87 \xd9\x81\xd9\x82\xd8\xb1\xd8\xa9' b' \xd8\xb9\xd8\xa7\xd8\xaf\xd9\x8a\xd8\xa9. ', styRTL)) story.append( Paragraph( b'\xd9\x87\xd8\xb0\xd9\x87 \xd8\xa7\xd9\x84\xd9\x81\xd9\x82\xd8\xb1\xd8\xa9' b' \xd9\x84\xd8\xaf\xd9\x8a\xd9\x87\xd8\xa7 12' b' \xd9\x86\xd9\x82\xd8\xb7\xd8\xa9 \xd9\x82\xd8\xa8\xd9\x84\xd9\x87\xd8\xa7' b' \xd9\x88\xd8\xa8\xd8\xb9\xd8\xaf\xd9\x87\xd8\xa7. ', styRTL)) story.append( Paragraph( b'<para spacebefore="12" spaceafter="12">' b'\xd9\x87\xd8\xb0\xd9\x87 \xd8\xa7\xd9\x84\xd9\x81\xd9\x82\xd8\xb1\xd8\xa9' b' \xd9\x84\xd8\xaf\xd9\x8a\xd9\x87\xd8\xa7 12 \xd9\x86\xd9\x82\xd8\xb7\xd8\xa9' b' \xd9\x82\xd8\xa8\xd9\x84\xd9\x87\xd8\xa7' b' \xd9\x88\xd8\xa8\xd8\xb9\xd8\xaf\xd9\x87\xd8\xa7\xd8\x8c' b' \xd9\x85\xd8\xad\xd8\xaf\xd8\xaf\xd8\xa9 \xd8\xa8\xd9\x80 XML.' b' \xd8\xa5\xd9\x86\xd9\x87\xd8\xa7 \xd8\xaa\xd8\xb9\xd9\x85\xd9\x84' b' \xd8\xa3\xd9\x8a\xd8\xb6\xd8\xa7! \xd9\x80.' b'</para>', styRTL)) # TODO: add more RTL scripts to the test (Farsi, Hebrew, etc.) template = SimpleDocTemplate( outputfile('test_paragraphs_bidi.pdf')) template.build(story)
def sale_pdf(request, sale_uuid): # Get sale to be printed sale = get_object_or_404(Sale, uuid=sale_uuid) # Create receipt as a Platypus story response = HttpResponse(content_type="application/pdf") response["Content-Disposition"] = f"filename=sale{sale.id}.pdf" doc = SimpleDocTemplate( response, pagesize=portrait(A4), leftMargin=2.5 * cm, rightMargin=2.5 * cm, topMargin=2.5 * cm, bottomMargin=2.5 * cm, ) styles = getSampleStyleSheet() story = [] # Festival banner if sale.festival.banner: banner = Image(sale.festival.banner.get_absolute_path(), width=16 * cm, height=4 * cm) banner.hAlign = 'CENTER' story.append(banner) story.append(Spacer(1, 1 * cm)) # Customer and sale number table = Table(( (Paragraph("<para><b>Customer:</b></para>", styles['Normal']), sale.customer), (Paragraph("<para><b>Sale no:</b></para>", styles['Normal']), sale.id), ), colWidths=(4 * cm, 12 * cm), hAlign='LEFT') story.append(table) story.append(Spacer(1, 1 * cm)) # Buttons and fringers if sale.buttons or sale.fringers.count(): tableData = [] if sale.buttons: tableData.append((Paragraph("<para><b>Buttons</b></para>", styles['Normal']), sale.buttons, f"£{sale.button_cost}")) if sale.fringers.count(): tableData.append( (Paragraph("<para><b>Fringers</b></para>", styles['Normal']), sale.fringers.count(), f"£{sale.fringer_cost}")) table = Table(tableData, colWidths=(8 * cm, 4 * cm, 4 * cm), hAlign='LEFT', style=(('ALIGN', (2, 0), (2, -1), 'RIGHT'), )) story.append(table) story.append(Spacer(1, 0.5 * cm)) # Tickets is_first = True for performance in sale.performances: if not is_first: story.append(Spacer(1, 0.5 * cm)) is_first = False tableData = [] tableData.append((Paragraph( f"<para>{performance['date']:%a, %e %b} at {performance['time']:%I:%M %p} - <b>{performance['show']}</b></para>", styles['Normal']), "", "", "")) for ticket in performance['tickets']: tableData.append((f"{ticket['id']}", "", ticket['description'], f"£{ticket['cost']}")) table = Table(tableData, colWidths=(4 * cm, 4 * cm, 4 * cm, 4 * cm), hAlign='LEFT', style=( ('SPAN', (0, 0), (3, 0)), ('ALIGN', (0, 1), (0, -1), 'RIGHT'), ('ALIGN', (3, 1), (3, -1), 'RIGHT'), )) story.append(table) # Total story.append(Spacer(1, 1 * cm)) table = Table( (("", Paragraph("<para><b>Total:</b></para>", styles['Normal']), f"£{sale.total_cost}"), ), colWidths=(8 * cm, 4 * cm, 4 * cm), hAlign='LEFT', style=(('ALIGN', (2, 0), (2, 0), 'RIGHT'), )) story.append(table) # Create PDF document and return it doc.build(story) return response
def testRTLBullets(self): try: import mwlib.ext except ImportError: pass font_name = getAFont() doc = SimpleDocTemplate(outputfile('test_rtl_bullets.pdf'), showBoundary=True) p_style = ParagraphStyle('default') p_style.leftIndent = 0 p_style.rightIndent = 0 list_styles = [ParagraphStyle('list%d' % n) for n in range(3)] all_styles = list_styles[:] all_styles.append(p_style) direction = 'rtl' for s in all_styles: s.fontSize = 15 s.leading = s.fontSize * 1.2 s.fontName = font_name if direction == 'rtl': s.wordWrap = 'RTL' s.alignment = TA_RIGHT else: s.alignment = TA_JUSTIFY indent_amount = 20 for list_lvl, list_style in enumerate(list_styles): list_lvl += 1 list_style.bulletIndent = indent_amount * (list_lvl - 1) if direction == 'rtl': list_style.rightIndent = indent_amount * list_lvl else: list_style.leftIndent = indent_amount * list_lvl elements = [] TEXTS = [ b'\xd7\xa9\xd7\xa8 \xd7\x94\xd7\x91\xd7\x99\xd7\x98\xd7\x97\xd7\x95\xd7\x9f, \xd7\x94\xd7\x95\xd7\x90 \xd7\x94\xd7\xa9\xd7\xa8 \xd7\x94\xd7\x90\xd7\x97\xd7\xa8\xd7\x90\xd7\x99 \xd7\xa2\xd7\x9c \xd7\x9e\xd7\xa9\xd7\xa8\xd7\x93 \xd7\x96\xd7\x94. \xd7\xaa\xd7\xa4\xd7\xa7\xd7\x99\xd7\x93 \xd7\x96\xd7\x94 \xd7\xa0\xd7\x97\xd7\xa9\xd7\x91 \xd7\x9c\xd7\x90\xd7\x97\xd7\x93 \xd7\x94\xd7\xaa\xd7\xa4\xd7\xa7\xd7\x99\xd7\x93\xd7\x99\xd7\x9d \xd7\x94\xd7\x91\xd7\x9b\xd7\x99\xd7\xa8\xd7\x99\xd7\x9d \xd7\x91\xd7\x9e\xd7\x9e\xd7\xa9\xd7\x9c\xd7\x94. \xd7\x9c\xd7\xa9\xd7\xa8 \xd7\x94\xd7\x91\xd7\x99\xd7\x98\xd7\x97\xd7\x95\xd7\x9f \xd7\x9e\xd7\xaa\xd7\x9e\xd7\xa0\xd7\x94 \xd7\x9c\xd7\xa8\xd7\x95\xd7\x91 \xd7\x92\xd7\x9d \xd7\xa1\xd7\x92\xd7\x9f \xd7\xa9\xd7\xa8.', b'\xd7\xa9\xd7\xa8 \xd7\x94\xd7\x91\xd7\x99\xd7\x98\xd7\x97\xd7\x95\xd7\x9f, <b>\xd7\x94\xd7\x95\xd7\x90 \xd7\x94\xd7\xa9\xd7\xa8 \xd7\x94\xd7\x90\xd7\x97\xd7\xa8\xd7\x90\xd7\x99 \xd7\xa2\xd7\x9c \xd7\x9e\xd7\xa9\xd7\xa8\xd7\x93 \xd7\x96\xd7\x94.</b> \xd7\xaa\xd7\xa4\xd7\xa7\xd7\x99\xd7\x93 \xd7\x96\xd7\x94 <i>\xd7\xa0\xd7\x97\xd7\xa9\xd7\x91 \xd7\x9c\xd7\x90\xd7\x97\xd7\x93</i> \xd7\x94\xd7\xaa\xd7\xa4\xd7\xa7\xd7\x99\xd7\x93\xd7\x99\xd7\x9d <b><i>\xd7\x94\xd7\x91\xd7\x9b\xd7\x99\xd7\xa8\xd7\x99\xd7\x9d \xd7\x91\xd7\x9e\xd7\x9e\xd7\xa9\xd7\x9c\xd7\x94</i></b>. \xd7\x9c\xd7\xa9\xd7\xa8 \xd7\x94\xd7\x91\xd7\x99\xd7\x98\xd7\x97\xd7\x95\xd7\x9f \xd7\x9e\xd7\xaa\xd7\x9e\xd7\xa0\xd7\x94 \xd7\x9c\xd7\xa8\xd7\x95\xd7\x91 \xd7\x92\xd7\x9d \xd7\xa1\xd7\x92\xd7\x9f \xd7\xa9\xd7\xa8.', u'<bullet>\u2022</bullet>\u05e9\u05e8 \u05d4\u05d1\u05d9\u05d8\u05d7\u05d5\u05df, <b>\u05d4\u05d5\u05d0 \u05d4\u05e9\u05e8 \u05d4\u05d0\u05d7\u05e8\u05d0\u05d9 \u05e2\u05dc \u05de\u05e9\u05e8\u05d3 \u05d6\u05d4.</b> \u05ea\u05e4\u05e7\u05d9\u05d3 \u05d6\u05d4 <i>\u05e0\u05d7\u05e9\u05d1 \u05dc\u05d0\u05d7\u05d3</i> \u05d4\u05ea\u05e4\u05e7\u05d9\u05d3\u05d9\u05dd <b><i>\u05d4\u05d1\u05db\u05d9\u05e8\u05d9\u05dd \u05d1\u05de\u05de\u05e9\u05dc\u05d4</i></b>. \u05dc\u05e9\u05e8\u05d4\u05d1\u05d9\u05d8\u05d7\u05d5\u05df \u05de\u05ea\u05de\u05e0\u05d4 \u05dc\u05e8\u05d5\u05d1 \u05d2\u05dd \u05e1\u05d2\u05df \u05e9\u05e8.', ] # simple text in a paragraph # working with patch from Hosam Aly p = Paragraph(TEXTS[0], p_style) elements.append(p) elements.append(Spacer(0, 40)) # uses intra paragraph markup -> style text p = Paragraph(TEXTS[1], p_style) elements.append(p) elements.append(Spacer(0, 40)) # list item (just a paragraph with a leading <bullet> element for list_style in list_styles: p = Paragraph(TEXTS[2], list_style) elements.append(p) doc.build(elements)
def land_title_pdf_generator(name,land_id,cukai_tahunan,negeri,daerah,bandar,tempat,lot_no,luas_lot,land_usage,pelembaran_piawai,permohonan_ukur,fail_number,time,tarik_pemberi,previous_owner_id,NRIC): doc = SimpleDocTemplate(land_id + ".pdf", rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=18) styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY)) styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY)) styles.add(ParagraphStyle('Center', alignment=TA_LEFT, leftIndent=20)) styles.add(ParagraphStyle('one', alignment=TA_LEFT, leftIndent=10)) styles.add(ParagraphStyle('two', alignment=TA_JUSTIFY, leftIndent=100)) styles.add(ParagraphStyle('t1', alignment=TA_JUSTIFY, leftIndent=20)) styles.add(ParagraphStyle('left', alignment=TA_LEFT)) Story = [] ptext='Kanun Tanah Negara' ptext3=Paragraph(ptext,styles['Title']) ptext1 = '<font size=15><b>BORANG 11BK<br/><br/>(Jadual Keempat Belas)</b></font>' ptext_1 = Paragraph(ptext1, styles['Title']) ptext2='<font size=10><b>GERAN</b></font>' ptext_2 = Paragraph(ptext2,styles['Title']) able = [['',ptext3, ''], ['', ptext_1, ''], ['', ptext_2, '']] t = Table(able, (2.5 * cm, 12 * cm, 2.5 * cm)) t.setStyle(TableStyle([ ('ALIGN', (0, 0), (-1, -1), 'CENTER'), #('INNERGRID', (0, 0), (-1, -1), 0.3, colors.white), ('VALIGN', (0, 0), (-1, -1), 'TOP'), #('BOX', (0, 0), (-1, -1), 1.50, colors.black), ])) Story.append(t) ptext="<font size=11><br/>No H.S.(M)<br/><br/></font>" ptext1= Paragraph(ptext,styles['left']) ptext2="<font size=11><br/>Cukai Tahunan : RM%s<br/><br/></font>" %cukai_tahunan ptext_2= Paragraph(ptext2,styles['left']) able=[[ptext1,ptext_2]] t = Table(able,(10 * cm, 10 * cm)) t.setStyle(TableStyle([ ('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('INNERGRID', (0, 0), (-1, -1), 1.5, colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('BOX', (0, 0), (-1, -1), 1.50, colors.black), ])) Story.append(t) Story.append(Spacer(1, 11)) Story.append(Spacer(1, 11)) Story.append(Spacer(1, 11)) ptext1 ="Negeri " ptext2 ="%s" %negeri ptext_1 = Paragraph(ptext1,styles['one']) ptext_2 = Paragraph(ptext2,styles['left']) ptext3 = "Daerah " ptext4 = "%s" % daerah ptext_3 = Paragraph(ptext3, styles['one']) ptext_4 = Paragraph(ptext4, styles['left']) ptext5 = "Bandar/Pekan/Mukim/Country " ptext6 = "%s" % bandar ptext_5 = Paragraph(ptext5, styles['one']) ptext_6 = Paragraph(ptext6, styles['left']) ptext7 = "Tempat" ptext8 = "%s" % tempat ptext_7 = Paragraph(ptext7, styles['one']) ptext_8 = Paragraph(ptext8, styles['left']) ptext9 = "No. PT" ptext10 = "%s" % lot_no ptext_9 = Paragraph(ptext9, styles['one']) ptext_10 = Paragraph(ptext10, styles['left']) ptext11 = "Luas Sementara" ptext12 = "%s Meter Persegi"% luas_lot ptext_11 = Paragraph(ptext11, styles['one']) ptext_12 = Paragraph(ptext12, styles['left']) ptext13 = "Kategori Pengunaan Tanah" ptext14 = "%s" % land_usage ptext_13 = Paragraph(ptext13, styles['one']) ptext_14= Paragraph(ptext14, styles['left']) ptext15 = "No. Lembaran Piawai" ptext16="%s" % pelembaran_piawai ptext_15 = Paragraph(ptext15, styles['one']) ptext_16 = Paragraph(ptext16, styles['left']) ptext17 = "No. Permohonan Ukur" ptext18 = "%s" % permohonan_ukur ptext_17 = Paragraph(ptext17, styles['one']) ptext_18 = Paragraph(ptext18, styles['left']) ptext19 = "No. Fail" ptext20 = "%s" % fail_number ptext_19 = Paragraph(ptext19, styles['one']) ptext_20 = Paragraph(ptext20, styles['left']) able = [[ptext_1,':', ptext_2],[ptext_3,":",ptext_4],[ptext_5,':',ptext_6], [ptext_7,":",ptext_8],[ptext_9,":",ptext_10],[ptext_11,':',ptext_12], [ptext_13,":",ptext_14],[ptext_15,":",ptext_16],[ptext_17,":",ptext_18],[ptext_19,":",ptext_20]] t = Table(able, (6 * cm,1*cm, 6 * cm)) t.setStyle(TableStyle([ ('ALIGN', (0, 0), (-1, -1), 'CENTER'), #('INNERGRID', (0, 0), (-1, -1), 1.5, colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), #('BOX', (0, 0), (-1, -1), 1.50, colors.black), ])) Story.append(t) Story.append(Spacer(1, 11)) Story.append(Spacer(1, 11)) ptext="Geran untuk selama-lamanya" ptext1= Paragraph(ptext,styles['Justify']) Story.append(ptext1) Story.append(Spacer(1, 11)) ptext = "Didaftarkan pada <br/>%s" %time ptext1 = Paragraph(ptext, styles['Justify']) ptext3= ".........................<br/><br/>Pendaftar" ptext_3 = Paragraph(ptext3,styles['two']) ptext2 = "Document hakmilik keluaran dikeluarkan pada <br/>%s" % time ptext_2 = Paragraph(ptext2, styles['Justify']) ptext4 = ".........................<br/><br/>Pendaftar" ptext_4= Paragraph(ptext4,styles['two']) able = [[ptext1,ptext_3],[ptext_2,ptext_4]] t = Table(able, (7 * cm, 7 * cm)) t.setStyle(TableStyle([ ('ALIGN', (0, 0), (-1, -1), 'CENTER'), #('INNERGRID', (0, 0), (-1, -1), 1.5, colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), #('BOX', (0, 0), (-1, -1), 1.50, colors.black), ])) Story.append(t) Story.append(Spacer(1, 11)) Story.append(Spacer(1, 11)) Story.append(PageBreak()) ptext = "Pelan tanah, bagi maksud pengenalan, adalah dikepikan pada Borang B1." ptext_1= Paragraph(ptext,styles['Justify']) Story.append(ptext_1) ptext= "<font size=9><b>SYARAT-SYARAT NYATA</b></font>" ptext_1= Paragraph(ptext,styles['Title']) ptext2="<font size=9>(FIRST GRADE)</font>" ptext_2 = Paragraph(ptext2,styles['left']) ptext3 = "<font size=9>The Land comprised in this title:<br/> (a) shall not be affected by any provision of the National Land Code limiting the compensation payable on the exercise by the State Authority of a right of access or use conferred by Chapter 3 of Part Three of the Code or on the creation of a Land Adminstrator's right of way;<br/> and<br/>(b) subject to the implied condition that land is liable to be re-entered if it is abandoned for more than three years shall revert to the State only if the proprietor for the time being dies without heirs; <br/><br/> and the title shall confer the absolute right to all foret produce and to all oil, mineral and other natural deposits on or below the surface of the land(including the right to work or extract any such produce or deposits and remove it beyond the boundaries of the land)</font>" ptext_3 = Paragraph(ptext3, styles['left']) ptext4 = "<font size=9><b>SEKATAN-SEKATAN KEPENTINGAN</b><br/>Tiada</font>" ptext_4 = Paragraph(ptext4,styles['Title']) able = [['', ptext_1, ''],['',ptext_2,''],['',ptext_3,''],['','',''],['',ptext_4,'']] t = Table(able, (5*cm, 9 * cm, 5 * cm)) t.setStyle(TableStyle([ ('ALIGN', (0, 0), (-1, -1), 'CENTER'), #('INNERGRID', (0, 0), (-1, -1), 1.5, colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), #('BOX', (0, 0), (-1, -1), 1.50, colors.black), ])) Story.append(t) Story.append(Spacer(1, 11)) Story.append(Spacer(1, 11)) line = MCLine(400) Story.append(line) ptext='<font size=9><i>Hendaklah dipenuhkan apabila hakmilik dikeluarkan bagi sambungan</i></font>' ptext_1 = Paragraph(ptext,styles['Center']) Story.append(ptext_1) Story.append(Spacer(1, 11)) ptext='<font size=9>Tarik mula-mula pemberimilikan</font>' ptext_1 = Paragraph(ptext, styles['Justify']) ptext2 = ': %s ' % tarik_pemberi ptext_2 = Paragraph(ptext2,styles['Justify']) ptext3 = '<font size=9>No. hakmilik asal (Tetap atau sementara)</font>' ptext_3 = Paragraph(ptext3, styles['Justify']) ptext4 = ':' ptext_4 = Paragraph(ptext4, styles['Justify']) ptext5 = '<font size=9>No. hakmilik yang terdahulu daripada ini <br/><i>(jika berlainan daripada di atas)</i></font>' ptext_5 = Paragraph(ptext5, styles['Justify']) ptext6 = '<font size=9>: %s</font>' %previous_owner_id ptext_6 = Paragraph(ptext6, styles['Justify']) able=[[ptext_1,ptext_2,''],[ptext_3,ptext_4,''],[ptext_5,ptext_6,'']] t = Table(able, (7 * cm, 5 * cm, 3 * cm)) t.setStyle(TableStyle([ ('ALIGN', (0, 0), (-1, -1), 'CENTER'), #('INNERGRID', (0, 0), (-1, -1), 1.5, colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), #('BOX', (0, 0), (-1, -1), 1.50, colors.black), ])) Story.append(t) Story.append(Spacer(1, 11)) line = MCLine(400) Story.append(line) ptext='<font size=9><b>REKOD KETUANPUNYAAN</b></font>' ptext_1 = Paragraph(ptext,styles['Title']) Story.append(ptext_1) ptext='%s, NO K/P Baru: %s, Warganegara Malaysia' %(name,NRIC) ptext_1= Paragraph(ptext,styles['Justify']) able=[[ptext_1,'','']] t = Table(able, (7 * cm, 5 * cm, 3 * cm)) t.setStyle(TableStyle([ ('ALIGN', (0, 0), (-1, -1), 'CENTER'), # ('INNERGRID', (0, 0), (-1, -1), 1.5, colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), # ('BOX', (0, 0), (-1, -1), 1.50, colors.black), ])) Story.append(t) Story.append(Spacer(1, 11)) ptext = '<font size=9><b>REKOD URUSANN</b></font>' ptext_1 = Paragraph(ptext, styles['Title']) Story.append(ptext_1) Story.append(Spacer(1, 11)) ptext = '<font size=9><b>PERKARA LAIN YANG MELIBATKAN HAKMILIK</b></font>' ptext_1 = Paragraph(ptext, styles['Title']) Story.append(ptext_1) ptext = '<font size=9><b>...............<br/>Pendaftar</b></font>' ptext_1 = Paragraph(ptext, styles['Title']) able = [['', '', ptext_1]] t = Table(able, (7 * cm, 5 * cm, 3 * cm)) t.setStyle(TableStyle([ ('ALIGN', (0, 0), (-1, -1), 'CENTER'), # ('INNERGRID', (0, 0), (-1, -1), 1.5, colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), # ('BOX', (0, 0), (-1, -1), 1.50, colors.black), ])) Story.append(t) Story.append(Spacer(1, 11)) Story.append(Spacer(1, 11)) line = MCLine(400) Story.append(line) doc.multiBuild(Story, onFirstPage=myFirstPage, onLaterPages=myLaterPages)
def test0(self): """Test... The story should contain... Features to be visually confirmed by a human being are: 1. ... 2. ... 3. ... """ story = [] SA = story.append #need a style styNormal = ParagraphStyle('normal') styGreen = ParagraphStyle('green', parent=styNormal, textColor=green) styDots = ParagraphStyle('styDots', parent=styNormal, endDots='.') styDots1 = ParagraphStyle('styDots1', parent=styNormal, endDots=ABag(text=' -', dy=2, textColor='red')) styDotsR = ParagraphStyle('styDotsR', parent=styNormal, alignment=TA_RIGHT, endDots=' +') styDotsC = ParagraphStyle('styDotsC', parent=styNormal, alignment=TA_CENTER, endDots=' *') styDotsJ = ParagraphStyle('styDotsJ', parent=styNormal, alignment=TA_JUSTIFY, endDots=' =') istyDots = ParagraphStyle('istyDots', parent=styNormal, firstLineIndent=12, leftIndent=6, endDots='.') istyDots1 = ParagraphStyle('istyDots1', parent=styNormal, firstLineIndent=12, leftIndent=6, endDots=ABag(text=' -', dy=2, textColor='red')) istyDotsR = ParagraphStyle('istyDotsR', parent=styNormal, firstLineIndent=12, leftIndent=6, alignment=TA_RIGHT, endDots=' +') istyDotsC = ParagraphStyle('istyDotsC', parent=styNormal, firstLineIndent=12, leftIndent=6, alignment=TA_CENTER, endDots=' *') istyDotsJ = ParagraphStyle('istyDotsJ', parent=styNormal, firstLineIndent=12, leftIndent=6, alignment=TA_JUSTIFY, endDots=' =') styNormalCJK = ParagraphStyle('normal', wordWrap='CJK') styDotsCJK = ParagraphStyle('styDots', parent=styNormalCJK, endDots='.') styDots1CJK = ParagraphStyle('styDots1', parent=styNormalCJK, endDots=ABag(text=' -', dy=2, textColor='red')) styDotsRCJK = ParagraphStyle('styDotsR', parent=styNormalCJK, alignment=TA_RIGHT, endDots=' +') styDotsCCJK = ParagraphStyle('styDotsC', parent=styNormalCJK, alignment=TA_CENTER, endDots=' *') styDotsJCJK = ParagraphStyle('styDotsJ', parent=styNormalCJK, alignment=TA_JUSTIFY, endDots=' =') istyDotsCJK = ParagraphStyle('istyDots', parent=styNormalCJK, firstLineIndent=12, leftIndent=6, endDots='.') istyDots1CJK = ParagraphStyle('istyDots1', parent=styNormalCJK, firstLineIndent=12, leftIndent=6, endDots=ABag(text=' -', dy=2, textColor='red')) istyDotsRCJK = ParagraphStyle('istyDotsR', parent=styNormalCJK, firstLineIndent=12, leftIndent=6, alignment=TA_RIGHT, endDots=' +') istyDotsCCJK = ParagraphStyle('istyDotsC', parent=styNormalCJK, firstLineIndent=12, leftIndent=6, alignment=TA_CENTER, endDots=' *') istyDotsJCJK = ParagraphStyle('istyDotsJ', parent=styNormalCJK, firstLineIndent=12, leftIndent=6, alignment=TA_JUSTIFY, endDots=' =') # some to test stySpaced = ParagraphStyle('spaced', parent=styNormal, spaceBefore=12, spaceAfter=12) SA(Paragraph("This is a normal paragraph. " + randomText(), styNormal)) SA( Paragraph("There follows a paragraph with only \"<br/>\"", styNormal)) SA(Paragraph("<br/>", styNormal)) SA( Paragraph( "This has 12 points space before and after, set in the style. " + randomText(), stySpaced)) SA(Paragraph("This is normal. " + randomText(), styNormal)) SA( Paragraph( """<para spacebefore="12" spaceafter="12"> This has 12 points space before and after, set inline with XML tag. It works too.""" + randomText() + "</para>", styNormal)) SA(Paragraph("This is normal. " + randomText(), styNormal)) styBackground = ParagraphStyle('MyTitle', fontName='Helvetica-Bold', fontSize=24, leading=28, textColor=white, backColor=navy) SA(Paragraph("This is a title with a background. ", styBackground)) SA( Paragraph( """<para backcolor="pink">This got a background from the para tag</para>""", styNormal)) SA( Paragraph( """<para>\n\tThis has newlines and tabs on the front but inside the para tag</para>""", styNormal)) SA( Paragraph( """<para> This has spaces on the front but inside the para tag</para>""", styNormal)) SA( Paragraph( """\n\tThis has newlines and tabs on the front but no para tag""", styNormal)) SA( Paragraph(""" This has spaces on the front but no para tag""", styNormal)) SA( Paragraph( """This has <font color=blue backcolor=pink>blue text with pink background</font> here.""", styNormal)) SA( Paragraph( """<span color=blue backcolor=pink> Nothing but blue text with pink background. </span>""", styNormal)) SA(Paragraph("""This has <i>italic text</i> here.""", styNormal)) SA(Paragraph("""This has <b>bold text</b> here.""", styNormal)) SA(Paragraph("""This has <u>underlined text</u> here.""", styNormal)) SA( Paragraph( """This has <font color=blue><u>blue and <font color=red>red</font> underlined text</u></font> here.""", styNormal)) SA(Paragraph("""<u>green underlining</u>""", styGreen)) SA( Paragraph( """<u>green <font size="+4"><i>underlining</i></font></u>""", styGreen)) SA( Paragraph("""This has m<super>2</super> a superscript.""", styNormal)) SA( Paragraph( """This has m<sub>2</sub> a subscript. Like H<sub>2</sub>O!""", styNormal)) SA( Paragraph( """This has a font change to <font name=Helvetica>Helvetica</font>.""", styNormal)) #This one fails: #SA(Paragraph("""This has a font change to <font name=Helvetica-Oblique>Helvetica-Oblique</font>.""", styNormal)) SA( Paragraph( """This has a font change to <font name=Helvetica><i>Helvetica in italics</i></font>.""", styNormal)) SA( Paragraph( '''This one uses upper case tags and has set caseSensitive=0: Here comes <FONT FACE="Helvetica" SIZE="14pt">Helvetica 14</FONT> with <STRONG>strong</STRONG> <EM>emphasis</EM>.''', styNormal, caseSensitive=0)) SA( Paragraph( '''The same as before, but has set not set caseSensitive, thus the tags are ignored: Here comes <FONT FACE="Helvetica" SIZE="14pt">Helvetica 14</FONT> with <STRONG>strong</STRONG> <EM>emphasis</EM>.''', styNormal)) SA( Paragraph( '''This one uses fonts with size "14pt" and also uses the em and strong tags: Here comes <font face="Helvetica" size="14pt">Helvetica 14</font> with <Strong>strong</Strong> <em>emphasis</em>.''', styNormal, caseSensitive=0)) SA( Paragraph( '''This uses a font size of 3cm: Here comes <font face="Courier" size="3cm">Courier 3cm</font> and normal again.''', styNormal, caseSensitive=0)) SA( Paragraph( '''This is just a very long silly text to see if the <FONT face="Courier">caseSensitive</FONT> flag also works if the paragraph is <EM>very</EM> long. ''' * 20, styNormal, caseSensitive=0)) SA(Indenter("1cm")) SA( Paragraph( "<para><bullet bulletIndent='-0.7cm' bulletOffsetY='2'>1.1</bullet>sample bullet default anchor</para>", styNormal)) SA( Paragraph( "<para><bullet bulletIndent='-0.7cm' bulletOffsetY='2'>1.22</bullet>sample bullet default anchor</para>", styNormal)) SA( Paragraph( "<para><bullet bulletIndent='-0.7cm' bulletOffsetY='2' anchor='start'>1.1</bullet>sample bullet start align</para>", styNormal)) SA( Paragraph( "<para><bullet bulletIndent='-0.7cm' bulletOffsetY='2' anchor='start'>1.22</bullet>sample bullet start align</para>", styNormal)) SA( Paragraph( "<para><bullet bulletIndent='-0.7cm' bulletOffsetY='2' anchor='middle'>1.1</bullet>sample bullet middle align</para>", styNormal)) SA( Paragraph( "<para><bullet bulletIndent='-0.7cm' bulletOffsetY='2' anchor='middle'>1.22</bullet>sample bullet middle align</para>", styNormal)) SA( Paragraph( "<para><bullet bulletIndent='-0.7cm' bulletOffsetY='2' anchor='end'>1.1</bullet>sample bullet end align</para>", styNormal)) SA( Paragraph( "<para><bullet bulletIndent='-0.7cm' bulletOffsetY='2' anchor='end'>1.22</bullet>sample bullet end align</para>", styNormal)) SA( Paragraph( "<para><bullet bulletIndent='-0.7cm' bulletOffsetY='2' anchor='numeric'>1.1</bullet>sample bullet numeric align</para>", styNormal)) SA( Paragraph( "<para><bullet bulletIndent='-0.7cm' bulletOffsetY='2' anchor='numeric'>1.22</bullet>sample bullet numeric align</para>", styNormal)) SA( Paragraph( "<para><bullet bulletIndent='-0.7cm' bulletOffsetY='2' anchor='numeric'><span color='red'>1</span><span color='green'>.</span><span color='blue'>3</span></bullet>sample bullet numeric align</para>", styNormal)) SA( Paragraph( "<para><bullet bulletIndent='-1cm' bulletOffsetY='2'><seq id='s0'/>)</bullet>Indented list bulletOffsetY=2. %s</para>" % randomText(), styNormal)) SA( Paragraph( "<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>" % randomText(), styNormal)) SA( Paragraph( "<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>" % randomText(), styNormal)) SA(Indenter("1cm")) SA( XPreformatted( "<para leftIndent='0.5cm' backcolor=pink><bullet bulletIndent='-1cm'><seq id='s1'/>)</bullet>Indented list.</para>", styNormal)) SA( XPreformatted( "<para leftIndent='0.5cm' backcolor=palegreen><bullet bulletIndent='-1cm'><seq id='s1'/>)</bullet>Indented list.</para>", styNormal)) SA(Indenter("-1cm")) SA( Paragraph( "<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>" % randomText(), styNormal)) SA(Indenter("-1cm")) SA( Paragraph( "<para>Indented list using seqChain/Format<seqChain order='s0 s1 s2 s3 s4'/><seqReset id='s0'/><seqFormat id='s0' value='1'/><seqFormat id='s1' value='a'/><seqFormat id='s2' value='i'/><seqFormat id='s3' value='A'/><seqFormat id='s4' value='I'/></para>", stySpaced)) SA(Indenter("1cm")) SA( Paragraph( "<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>" % randomText(), styNormal)) SA( Paragraph( "<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>" % randomText(), styNormal)) SA( Paragraph( "<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>" % randomText(), styNormal)) SA(Indenter("1cm")) SA( XPreformatted( "<para backcolor=pink boffsety='-3'><bullet bulletIndent='-1cm'><seq id='s1'/>)</bullet>Indented list bulletOffsetY=-3.</para>", styNormal)) SA( XPreformatted( "<para backcolor=pink><bullet bulletIndent='-1cm'><seq id='s1'/>)</bullet>Indented list.</para>", styNormal)) SA(Indenter("-1cm")) SA( Paragraph( "<para><bullet bulletIndent='-1cm'><seq id='s0'/>)</bullet>Indented list. %s</para>" % randomText(), styNormal)) SA(Indenter("1cm")) SA( XPreformatted( "<para backcolor=palegreen><bullet bulletIndent='-1cm'><seq id='s1'/>)</bullet>Indented list.</para>", styNormal)) SA(Indenter("1cm")) SA( XPreformatted( "<para><bullet bulletIndent='-1cm'><seq id='s2'/>)</bullet>Indented list. line1</para>", styNormal)) SA( XPreformatted( "<para><bullet bulletIndent='-1cm'><seq id='s2'/>)</bullet>Indented list. line2</para>", styNormal)) SA(Indenter("-1cm")) SA( XPreformatted( "<para backcolor=palegreen><bullet bulletIndent='-1cm'><seq id='s1'/>)</bullet>Indented list.</para>", styNormal)) SA(Indenter("-1cm")) SA(Indenter("-1cm")) for i in range(2): SA(PageBreak()) SA( Paragraph( '''%s dotted paragraphs''' % (i and 'CJK' or 'Normal'), styNormal)) SA( Paragraph('''Simple paragraph with dots''', i and styDotsCJK or styDots)) SA( Paragraph('''Simple indented paragraph with dots''', i and istyDotsCJK or istyDots)) SA( Paragraph('''Simple centred paragraph with stars''', i and styDotsCCJK or styDotsC)) SA( Paragraph('''Simple centred indented paragraph with stars''', i and istyDotsCCJK or istyDotsC)) SA( Paragraph( '''Simple right justified paragraph with pluses, but no pluses''', i and styDotsRCJK or styDotsR)) SA( Paragraph( '''Simple right justified indented paragraph with pluses, but no pluses''', i and istyDotsRCJK or istyDotsR)) SA( Paragraph('''Simple justified paragraph with equals''', i and styDotsJCJK or styDotsJ)) SA( Paragraph( '''Simple justified indented paragraph with equals''', i and istyDotsJCJK or istyDotsJ)) SA( Paragraph('''A longer simple paragraph with dots''', i and styDotsCJK or styDots)) SA( Paragraph('''A longer simple indented paragraph with dots''', i and istyDotsCJK or istyDots)) SA( Paragraph( 'A very much' + 50 * ' longer' + ' simple paragraph with dots', i and styDotsCJK or styDots)) SA( Paragraph( 'A very much' + 50 * ' longer' + ' simple indented paragraph with dots', i and istyDotsCJK or istyDots)) SA( Paragraph( 'A very much' + 50 * ' longer' + ' centred simple paragraph with stars', i and styDotsCCJK or styDotsC)) SA( Paragraph( 'A very much' + 50 * ' longer' + ' centred simple indented paragraph with stars', i and istyDotsCCJK or istyDotsC)) SA( Paragraph( 'A very much' + 50 * ' longer' + ' right justified simple paragraph with pluses, but no pluses', i and styDotsRCJK or styDotsR)) SA( Paragraph( 'A very much' + 50 * ' longer' + ' right justified simple indented paragraph with pluses, but no pluses', i and istyDotsRCJK or istyDotsR)) SA( Paragraph( 'A very much' + 50 * ' longer' + ' justified simple paragraph with equals', i and styDotsJCJK or styDotsJ)) SA( Paragraph( 'A very much' + 50 * ' longer' + ' justified simple indented paragraph with equals', i and istyDotsJCJK or istyDotsJ)) SA( Paragraph( '''Simple paragraph with dashes that have a dy and a textColor.''', i and styDots1CJK or styDots1)) SA( Paragraph( '''Simple indented paragraph with dashes that have a dy and a textColor.''', i and istyDots1CJK or istyDots1)) SA( Paragraph( '''Complex <font color="green">paragraph</font> with dots''', i and styDotsCJK or styDots)) SA( Paragraph( '''Complex <font color="green">indented paragraph</font> with dots''', i and istyDotsCJK or istyDots)) SA( Paragraph( '''Complex centred <font color="green">paragraph</font> with stars''', i and styDotsCCJK or styDotsC)) SA( Paragraph( '''Complex centred <font color="green">indented paragraph</font> with stars''', i and istyDotsCCJK or istyDotsC)) SA( Paragraph( '''Complex right justfied <font color="green">paragraph</font> with pluses, but no pluses''', i and styDotsRCJK or styDotsR)) SA( Paragraph( '''Complex right justfied <font color="green">indented paragraph</font> with pluses, but no pluses''', i and istyDotsRCJK or istyDotsR)) SA( Paragraph( '''Complex justfied <font color="green">paragraph</font> with equals''', i and styDotsJCJK or styDotsJ)) SA( Paragraph( '''Complex justfied <font color="green">indented paragraph</font> with equals''', i and istyDotsJCJK or istyDotsJ)) SA( Paragraph( '''A longer complex <font color="green">paragraph</font> with dots''', i and styDotsCJK or styDots)) SA( Paragraph( '''A longer complex <font color="green">indented paragraph</font> with dots''', i and istyDotsCJK or istyDots)) SA( Paragraph( 'A very much' + 50 * ' longer' + ' complex <font color="green">paragraph</font> with dots', i and styDotsCJK or styDots)) SA( Paragraph( 'A very much' + 50 * ' longer' + ' complex <font color="green">indented paragraph</font> with dots', i and istyDotsCJK or istyDots)) SA( Paragraph( '''Complex <font color="green">paragraph</font> with dashes that have a dy and a textColor.''', i and styDots1CJK or styDots1)) SA( Paragraph( '''Complex <font color="green">indented paragraph</font> with dashes that have a dy and a textColor.''', i and istyDots1CJK or istyDots1)) SA( Paragraph( 'A very much' + 50 * ' longer' + ' centred complex <font color="green">paragraph</font> with stars', i and styDotsCCJK or styDotsC)) SA( Paragraph( 'A very much' + 50 * ' longer' + ' centred complex <font color="green">indented paragraph</font> with stars', i and istyDotsCCJK or istyDotsC)) SA( Paragraph( 'A very much' + 50 * ' longer' + ' right justified <font color="green">complex</font> paragraph with pluses, but no pluses', i and styDotsRCJK or styDotsR)) SA( Paragraph( 'A very much' + 50 * ' longer' + ' right justified <font color="green">complex</font> indented paragraph with pluses, but no pluses', i and istyDotsRCJK or istyDotsR)) SA( Paragraph( 'A very much' + 50 * ' longer' + ' justified complex <font color="green">paragraph</font> with equals', i and styDotsJCJK or styDotsJ)) SA( Paragraph( 'A very much' + 50 * ' longer' + ' justified complex <font color="green">indented paragraph</font> with equals', i and istyDotsJCJK or istyDotsJ)) template = SimpleDocTemplate(outputfile('test_paragraphs.pdf'), showBoundary=1) template.build(story, onFirstPage=myFirstPage, onLaterPages=myLaterPages)
def export_pdf(request, id, uidb64=None, token=None): """ Generates a PDF with the contents of a nutrition plan See also * http://www.blog.pythonlibrary.org/2010/09/21/reportlab * http://www.reportlab.com/apis/reportlab/dev/platypus.html """ # Load the plan if uidb64 is not None and token is not None: if check_token(uidb64, token): plan = get_object_or_404(NutritionPlan, pk=id) else: return HttpResponseForbidden() else: if request.user.is_anonymous: return HttpResponseForbidden() plan = get_object_or_404(NutritionPlan, pk=id, user=request.user) plan_data = plan.get_nutritional_values() # Create the HttpResponse object with the appropriate PDF headers. response = HttpResponse(content_type='application/pdf') # Create the PDF object, using the response object as its "file." doc = SimpleDocTemplate( response, pagesize=A4, title=_('Nutritional plan'), author='wger Workout Manager', subject=_('Nutritional plan for %s') % request.user.username, topMargin=1 * cm, ) # container for the 'Flowable' objects elements = [] data = [] # Iterate through the Plan meal_markers = [] ingredient_markers = [] # Meals i = 0 for meal in plan.meal_set.select_related(): i += 1 meal_markers.append(len(data)) if not meal.time: p = Paragraph( u'<para align="center"><strong>{nr} {meal_nr}</strong></para>'. format(nr=_('Nr.'), meal_nr=i), styleSheet["SubHeader"]) else: p = Paragraph( u'<para align="center"><strong>' u'{nr} {meal_nr} - {meal_time}' u'</strong></para>'.format( nr=_('Nr.'), meal_nr=i, meal_time=meal.time.strftime("%H:%M")), styleSheet["SubHeader"]) data.append([p]) # Ingredients for item in meal.mealitem_set.select_related(): ingredient_markers.append(len(data)) p = Paragraph(u'<para>{0}</para>'.format(item.ingredient.name), styleSheet["Normal"]) if item.get_unit_type() == MEALITEM_WEIGHT_GRAM: unit_name = 'g' else: unit_name = ' × ' + item.weight_unit.unit.name data.append([ Paragraph(u"{0:.0f}{1}".format(item.amount, unit_name), styleSheet["Normal"]), p ]) # Add filler data.append([Spacer(1 * cm, 0.6 * cm)]) # Set general table styles table_style = [] # Set specific styles, e.g. background for title cells for marker in meal_markers: # Set background colour for headings table_style.append( ('BACKGROUND', (0, marker), (-1, marker), header_colour)) table_style.append( ('BOX', (0, marker), (-1, marker), 1.25, colors.black)) # Make the headings span the whole width table_style.append(('SPAN', (0, marker), (-1, marker))) # has the plan any data? if data: t = Table(data, style=table_style) # Manually set the width of the columns t._argW[0] = 3.5 * cm # There is nothing to output else: t = Paragraph( _('<i>This is an empty plan, what did you expect on the PDF?</i>'), styleSheet["Normal"]) # Add site logo elements.append(get_logo()) elements.append(Spacer(10 * cm, 0.5 * cm)) # Set the title (if available) if plan.description: p = Paragraph( '<para align="center"><strong>%(description)s</strong></para>' % {'description': plan.description}, styleSheet["HeaderBold"]) elements.append(p) # Filler elements.append(Spacer(10 * cm, 1.5 * cm)) # append the table to the document elements.append(t) elements.append(Paragraph('<para> </para>', styleSheet["Normal"])) # Create table with nutritional calculations data = [] data.append([ Paragraph( u'<para align="center">{0}</para>'.format(_('Nutritional data')), styleSheet["SubHeaderBlack"]) ]) data.append([ Paragraph(_('Macronutrients'), styleSheet["Normal"]), Paragraph(_('Total'), styleSheet["Normal"]), Paragraph(_('Percent of energy'), styleSheet["Normal"]), Paragraph(_('g per body kg'), styleSheet["Normal"]) ]) data.append([ Paragraph(_('Energy'), styleSheet["Normal"]), Paragraph(str(plan_data['total']['energy']), styleSheet["Normal"]) ]) data.append([ Paragraph(_('Protein'), styleSheet["Normal"]), Paragraph(str(plan_data['total']['protein']), styleSheet["Normal"]), Paragraph(str(plan_data['percent']['protein']), styleSheet["Normal"]), Paragraph(str(plan_data['per_kg']['protein']), styleSheet["Normal"]) ]) data.append([ Paragraph(_('Carbohydrates'), styleSheet["Normal"]), Paragraph(str(plan_data['total']['carbohydrates']), styleSheet["Normal"]), Paragraph(str(plan_data['percent']['carbohydrates']), styleSheet["Normal"]), Paragraph(str(plan_data['per_kg']['carbohydrates']), styleSheet["Normal"]) ]) data.append([ Paragraph(" " + _('Sugar content in carbohydrates'), styleSheet["Normal"]), Paragraph(str(plan_data['total']['carbohydrates_sugar']), styleSheet["Normal"]) ]) data.append([ Paragraph(_('Fat'), styleSheet["Normal"]), Paragraph(str(plan_data['total']['fat']), styleSheet["Normal"]), Paragraph(str(plan_data['percent']['fat']), styleSheet["Normal"]), Paragraph(str(plan_data['per_kg']['fat']), styleSheet["Normal"]) ]) data.append([ Paragraph(_('Saturated fat content in fats'), styleSheet["Normal"]), Paragraph(str(plan_data['total']['fat_saturated']), styleSheet["Normal"]) ]) data.append([ Paragraph(_('Fibres'), styleSheet["Normal"]), Paragraph(str(plan_data['total']['fibres']), styleSheet["Normal"]) ]) data.append([ Paragraph(_('Sodium'), styleSheet["Normal"]), Paragraph(str(plan_data['total']['sodium']), styleSheet["Normal"]) ]) table_style = [] table_style.append(('BOX', (0, 0), (-1, -1), 1.25, colors.black)) table_style.append(('GRID', (0, 0), (-1, -1), 0.40, colors.black)) table_style.append(('SPAN', (0, 0), (-1, 0))) # Title table_style.append(('SPAN', (1, 2), (-1, 2))) # Energy table_style.append(('BACKGROUND', (0, 3), (-1, 3), row_color)) # Protein table_style.append( ('BACKGROUND', (0, 4), (-1, 4), row_color)) # Carbohydrates table_style.append(('SPAN', (1, 5), (-1, 5))) # Sugar table_style.append(('LEFTPADDING', (0, 5), (0, 5), 15)) table_style.append(('BACKGROUND', (0, 6), (-1, 6), row_color)) # Fats table_style.append(('SPAN', (1, 7), (-1, 7))) # Saturated fats table_style.append(('LEFTPADDING', (0, 7), (0, 7), 15)) table_style.append(('SPAN', (1, 8), (-1, 8))) # Fibres table_style.append(('SPAN', (1, 9), (-1, 9))) # Sodium t = Table(data, style=table_style) t._argW[0] = 6 * cm elements.append(t) # Footer, date and info elements.append(Spacer(10 * cm, 0.5 * cm)) elements.append( render_footer(request.build_absolute_uri(plan.get_absolute_url()))) doc.build(elements) response[ 'Content-Disposition'] = 'attachment; filename=nutritional-plan.pdf' response['Content-Length'] = len(response.content) return response
def build_index_Tafonomia(self, records, sito): if os.name == 'posix': home = os.environ['HOME'] elif os.name == 'nt': home = os.environ['HOMEPATH'] home_DB_path = ('%s%s%s') % (home, os.sep, 'pyarchinit_DB_folder') logo_path = ('%s%s%s') % (home_DB_path, os.sep, 'logo.jpg') logo = Image(logo_path) logo.drawHeight = 1.5 * inch * logo.drawHeight / logo.drawWidth logo.drawWidth = 1.5 * inch logo.hAlign = "LEFT" styleSheet = getSampleStyleSheet() styNormal = styleSheet['Normal'] styNormal.fontSize = 8 styBackground = ParagraphStyle('background', parent=styNormal, backColor=colors.pink) styH1 = styleSheet['Heading3'] data = self.datestrfdate() ###################### ELENCO SCHEDE TAFONOMICHE ########### lst = [] lst.append(logo) lst.append( Paragraph( "<b>ELENCO SCHEDE TAFONOMICHE</b><br/><b>Scavo: %s, Data: %s</b>" % (sito, data), styH1)) table_data = [] for i in range(len(records)): exp_index = Tafonomia_index_pdf_sheet(records[i]) table_data.append(exp_index.getTable()) styles = exp_index.makeStyles() colWidths = [50, 80, 80, 80, 100, 60, 50, 60, 60, 60, 60, 150] table_data_formatted = Table(table_data, colWidths, style=styles) table_data_formatted.hAlign = "LEFT" lst.append(table_data_formatted) #lst.append(Spacer(0,2)) filename = ('%s%s%s') % (self.PDF_path, os.sep, 'elenco_tafonomia.pdf') f = open(filename, "wb") doc = SimpleDocTemplate(f, pagesize=(29 * cm, 21 * cm), showBoundary=0) doc.build(lst, canvasmaker=NumberedCanvas_TAFONOMIAindex) f.close() ###################### ELENCO SCHEDE STRUTTURE TAFONOMICHE ########### lst = [] lst.append(logo) lst.append( Paragraph( "<b>ELENCO SCHEDE STRUTTURE TAFONOMICHE</b><br/><b>Scavo: %s, Data: %s</b>" % (sito, data), styH1)) table_data = [] for i in range(len(records)): exp_index = Tafonomia_index_II_pdf_sheet(records[i]) table_data.append(exp_index.getTable()) styles = exp_index.makeStyles() colWidths = [50, 50, 40, 100, 60, 50, 50, 60, 60, 60, 80] table_data_formatted = Table(table_data, colWidths, style=styles) table_data_formatted.hAlign = "LEFT" lst.append(table_data_formatted) #lst.append(Spacer(0,2)) filename = ('%s%s%s') % (self.PDF_path, os.sep, 'elenco_strutture_tafonomia.pdf') f = open(filename, "wb") doc = SimpleDocTemplate(f, pagesize=(29 * cm, 21 * cm), showBoundary=0) doc.build(lst, canvasmaker=NumberedCanvas_TAFONOMIAindex) f.close()
AIY5HEc5+9AAheCKsvAFT2B+91+PIdoDjCmNfhy3eA4vBCjZ6PHwBC+AJApYaxjxG+AFAp ipoA34ihA0BRQWhF+AJAneJfJwz7DnsTwhcAKsULIXwBoMhAeJu6AYDiCWNeZh4CoPi80O sYKgAUFSB+bXk5hgoAucLYpgCrr3YMFQByqVhmYQOGCABFDWN7jP1pSwgAOcU/S7DFUfcW whcACqKGEldpAAhhTA1fKzE0B4u/kfgyhkENY/m/dcrf/NlXBX0bXG3PiwG6BcyoYSwfoI VV0q9+1fa8EMKKhzH+6agWDAkAChvGOn/1kBPOOjAkACiqF8LmYZE5UD2GwTkPmlbB8LUx Dc8GqzC3+PczZpEdqFD7O9PwbGpyuRxQgTAHggAQBIAgAARBAAgCQBAAggAQBAEgCABBAA gCQBAEgCAABAEgCABBEACCABAEgCAABAEgCAJAUFn1jwADAAvNtoNwyDwhAAAAAElFTkSu QmCC """ IMGFILE = StringIO(base64.decodestring(LOGOBASE64)) IMGFILE.seek(0) LOGOIMAGE = PILImage.open(IMGFILE) IMAGE = LOGOIMAGE DOC = SimpleDocTemplate(PDFREPORTNAME, topMargin=65, pagesize=A4) # Container of flowable objects ELEMENTSOFDOC = [] # Putting the table arcpy.AddMessage("Formatting Table...") # Drawing the webmap if len(arcpy.GetParameterAsText(2).strip()) > 0: #pylint: disable=E1103 WEBMAPJSON = json.loads(arcpy.GetParameterAsText(2).strip()) arcpy.AddMessage("Printing the Webmap...") #To override the outputsize and dpi and obtain the extent of the webmap if "exportOptions" in WEBMAPJSON.keys(): LISTATT = WEBMAPJSON["exportOptions"]
def CreationPDF(self, nomDoc=FonctionsPerso.GenerationNomDoc( "COMMANDE_REPAS", "pdf"), afficherDoc=True): dictChampsFusion = {} # Récupération des données nom_commande = self.ctrl_nom.GetValue() date_debut = self.ctrl_date_debut.GetDate() date_fin = self.ctrl_date_fin.GetDate() dictDonnees = self.ctrl_repas.GetDonnees() # Récupération des options d'impression global DICT_INFOS_IMPRESSION DICT_INFOS_IMPRESSION = { "date_debut": date_debut, "date_fin": date_fin } dlg = DLG_Options_impression_pdf.Dialog(self, categorie="commande_repas", ctrl=CTRL_Options_impression) if dlg.ShowModal() == wx.ID_OK: dictOptions = dlg.GetOptions() dlg.Destroy() else: dlg.Destroy() return False # Création du PDF from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle from reportlab.platypus.flowables import ParagraphAndImage, Image from reportlab.lib.pagesizes import A4 from reportlab.lib import colors from reportlab.lib.styles import ParagraphStyle if dictOptions["orientation"] == "portrait": largeur_page, hauteur_page = A4 else: hauteur_page, largeur_page = A4 # Initialisation du PDF if sys.platform.startswith("win"): nomDoc = nomDoc.replace("/", "\\") doc = SimpleDocTemplate(nomDoc, pagesize=(largeur_page, hauteur_page), topMargin=30, bottomMargin=30) story = [] largeurContenu = largeur_page - 75 # Création du titre du document def Header(): dataTableau = [] largeursColonnes = ((largeurContenu - 100, 100)) dateDuJour = UTILS_Dates.DateEngFr(str(datetime.date.today())) dataTableau.append( (_(u"Commande des repas"), _(u"%s\nEdité le %s") % (UTILS_Organisateur.GetNom(), dateDuJour))) style = TableStyle([ ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('ALIGN', (0, 0), (0, 0), 'LEFT'), ('FONT', (0, 0), (0, 0), "Helvetica-Bold", 16), ('ALIGN', (1, 0), (1, 0), 'RIGHT'), ('FONT', (1, 0), (1, 0), "Helvetica", 6), ]) tableau = Table(dataTableau, largeursColonnes) tableau.setStyle(style) story.append(tableau) story.append(Spacer(0, 10)) # Insère un header Header() # Insère le nom et la période de la commande style_titre_commande = ParagraphStyle( name="1", alignment=1, fontName="Helvetica-Bold", fontSize=dictOptions["taille_texte_titre"], leading=8, spaceAfter=14) story.append( Paragraph( _(u"<para>%s - Du %s au %s</para>") % (nom_commande, UTILS_Dates.DateDDEnFr(date_debut), UTILS_Dates.DateDDEnFr(date_fin)), style_titre_commande)) # Styles style_entete = ParagraphStyle(name="1", alignment=1, fontName="Helvetica-Bold", fontSize=dictOptions["taille_texte"], leading=8, spaceAfter=2) style_numerique = ParagraphStyle(name="2", alignment=2, fontName="Helvetica", fontSize=dictOptions["taille_texte"], leading=8, spaceAfter=2) style_total = ParagraphStyle(name="3", alignment=2, fontName="Helvetica-Bold", fontSize=dictOptions["taille_texte"], leading=8, spaceAfter=2) style_texte = ParagraphStyle(name="4", alignment=0, fontName="Helvetica", fontSize=dictOptions["taille_texte"], leading=8, spaceAfter=2) # Calcule des largeurs de colonne largeur_colonne_date = dictOptions["largeur_colonne_date"] largeur_colonnes = largeurContenu - largeur_colonne_date dictLargeurs = {} if dictOptions["largeur_colonnes_auto"] == True: total_largeurs_colonnes = 0 for dictColonne in dictDonnees["liste_colonnes"]: total_largeurs_colonnes += dictColonne["largeur"] for dictColonne in dictDonnees["liste_colonnes"]: dictLargeurs[dictColonne["IDcolonne"]] = 1.0 * dictColonne[ "largeur"] / total_largeurs_colonnes * largeur_colonnes # Dessin du tableau de données dataTableau = [] largeursColonnes = [ largeur_colonne_date, ] # Dessin des noms de colonnes ligne = [ Paragraph(_(u"Date"), style_entete), ] for dictColonne in dictDonnees["liste_colonnes"]: valeur = dictColonne["nom_colonne"] ligne.append(Paragraph(valeur, style_entete)) if dictLargeurs.has_key(dictColonne["IDcolonne"]): largeur = dictLargeurs[dictColonne["IDcolonne"]] else: largeur = dictColonne["largeur"] / 1.5 largeursColonnes.append(largeur) dataTableau.append(ligne) # Dessin des lignes for numLigne in range(0, len(dictDonnees["liste_dates"])): ligne = [] # Ajout de la date à la ligne date = dictDonnees["liste_dates"][numLigne] if type(date) == datetime.date: valeur = UTILS_Dates.DateComplete(date) else: valeur = date ligne.append(Paragraph(valeur, style_entete)) # Ajout des cases à la ligne numColonne = 0 for dictColonne in dictDonnees["liste_colonnes"]: # Recherche la valeur valeur = "" if dictDonnees["cases"].has_key((numLigne, numColonne)): case = dictDonnees["cases"][(numLigne, numColonne)] valeur = case.GetValeur() # Recherche le style à appliquer if "numerique" in case.categorieColonne: style = style_numerique if "total" in case.categorieColonne or numLigne == len( dictDonnees["liste_dates"]) - 1: style = style_total else: style = style_texte valeur = valeur.replace("\n", "<br/>") ligne.append(Paragraph(unicode(valeur), style)) numColonne += 1