def genererFicheValidation(nomFichier, projet): """ """ # # Styles # title_style = ParagraphStyle(name="TitleStyle", fontName="Helvetica", textColor = colors.red, fontSize=20, alignment=TA_LEFT, ) normal_style = ParagraphStyle(name="NormalStyle", fontName="Helvetica", fontSize=10, leading = 12, alignment=TA_LEFT, ) entete_style = ParagraphStyle(name="EnteteStyle", fontName="Helvetica", textColor = colors.gray, fontSize=9, alignment=TA_LEFT, ) # To make a SimpleDocTemplate, just supply a file name for your PDF, and the # page margins. You can optionally supply non-flowing elements such as headers # and footers. I will introduce that feature in a later demonstration. doc = SimpleDocTemplate(nomFichier, pagesize=A4, leftMargin=10*mm, rightMargin=10*mm, topMargin=10*mm, bottomMargin=10*mm) story = [] # Fill this list with flowable objects ref = projet.GetReferentiel() prj = projet.GetProjetRef() # # En-tête # story.append(Paragraph(u"Fiche de validation du projet", title_style )) story.append(Spacer(1, 5*mm)) if projet.GetTypeEnseignement() == 'SSI': en_tete = [u"Bulletin officiel n°39 du 23 octobre 2014", u"Annexe 4 à la note de service n° 2014-131 du 9-10-2014", u"Baccalauréat général, série S, sciences de l'ingénieur - Épreuve orale, projet interdisciplinaire"] elif ref.Famille == 'STI': en_tete = [u"Bulletin officiel n°39 du 23 octobre 2014", u"Annexe 9 à la note de service n° 2014-132 du 13-10-2014", u"Baccalauréat technologique, série STI2D - Épreuve de projet en enseignement spécifique à la spécialité"] for l in en_tete: story.append(Paragraph(l, entete_style)) story.append(Spacer(1, 1*mm)) story.append(Spacer(1, 4*mm)) # # Première zone # NP = [] for p in projet.equipe: np = p.GetNomPrenom() if p.referent: np = gras(np) if p.discipline != 'Tec': np = italic(np) NP.append(Paragraph(np, normal_style)) data= [[[Paragraph(gras(u'Établissement : '), normal_style), Paragraph(projet.classe.etablissement, normal_style)], [Paragraph(gras(u"Année scolaire : ")+getAnneeScolaireStr(), normal_style), Paragraph(gras(u"Nombre d’élèves concernés : ")+str(len(projet.eleves)), normal_style)]], [Paragraph(gras(u"Spécialité : ")+ ref.Enseignement[0], normal_style), Paragraph(gras(u"Nombre de groupes d’élèves : ")+str(projet.nbrParties), normal_style)], [Paragraph(gras(u"Noms et prénoms des enseignants responsables :"), normal_style), NP]] t = Table(data, style = [('VALIGN', (0,0),(-1,-1),'TOP')]) story.append(t) story.append(Spacer(1, 5*mm)) styleSheet = getSampleStyleSheet() # # Deuxième zone (tableau) # # print ref.attributs_prj # Colonne de gauche ppi = Paragraph(gras(u'Intitulé du projet'),normal_style) ppo = Paragraph(gras(u'Origine de la proposition'),normal_style) ppb = [Paragraph(gras(u'Problématique - Énoncé général du besoin'),normal_style)] ppb.append(splitParagraph(prj.attributs['PB'][1], entete_style)) pco = [Paragraph(gras(u'Contraintes imposées au projet'),normal_style)] pco.append(splitParagraph(prj.attributs['CCF'][1], entete_style)) ppig = Paragraph(gras(u'Intitulé des parties du projet confiées à chaque groupe'),normal_style) ppbg = Paragraph(gras(u'Énoncé du besoin pour la partie du projet confiée à chaque groupe'),normal_style) ppr = [Paragraph(gras(u'Production finale attendue'),normal_style)] ppr.append(splitParagraph(prj.attributs['OBJ'][1], entete_style)) # Colonne de droite contenu = [projet.intitule, projet.origine, projet.problematique, projet.contraintes, projet.intituleParties, projet.besoinParties, projet.production] p = [] tot = 0 for c in contenu: t = ellipsizer(c, LONG_MAX_FICHE_VALID) tot += len(t) normal_style.fontSize = max(8, 11 - int(len(t)/250)) normal_style.leading = normal_style.fontSize * 1.2 p.append(splitParagraph(t, normal_style)) normal_style.fontSize = 10 normal_style.leading = 12 larg = max(50, min(150, 190*tot/800))*mm data= [[ppi, p[0]], [ppo, p[1]], [ppb, p[2]], [pco, p[3]], [ppig, p[4]], [ppbg, p[5]], [ppr, p[6]]] t=Table(data, style=[('GRID', (0,0),(-1,-1), 1,colors.black), ('VALIGN', (0,0),(-1,-1), 'TOP')], colWidths = [None, larg]) story.append(t) # # Zone des signatures # story.append(Spacer(1, 5*mm)) V1 = [Paragraph(u"Visa du chef d’établissement", normal_style), Paragraph(u"(Nom, prénom, date et signature)", entete_style)] V2 = [Paragraph(u"Visa du ou des IA-IPR", normal_style), Paragraph(u"(Noms, prénoms, qualités, dates et signatures)", entete_style)] data= [[V1, V2]] t=Table(data,style=[('VALIGN', (0,0),(-1,-1),'TOP')]) story.append(t) try: doc.build(story) except doctemplate.LayoutError, err: print "Paragraphe trop grand" # print err.message # print type(err) # print dir(err) return False
def createCardReport(fileName): global currentCard, questions, aChoices, bChoices, cChoices, tChoices, fChoices, answers questionCards = ReportPage(fileName + "_questions.pdf", pagesize=letter) xOffset = 25 * mm yOffset = 12 * mm card = 0 for y in range(4, -1, -1): for x in range(0, 2, 1): firstLinePos = 40 * mm xPos = x * (89 * mm) + xOffset yPos = y * (51 * mm) + yOffset # Draw the question. style = ParagraphStyle('Bigger') style.fontSize = 12 question = Paragraph(questions[card], style) aW = 70 * mm # available width and height aH = 20 * mm _, h = question.wrap(aW, aH) firstLinePos -= h question.drawOn(questionCards, xPos, yPos + firstLinePos) firstLinePos -= 10 * mm xPos += 15 * mm # Process the choices. choice = aChoices[card] if choice != "": questionCards.drawString(xPos, yPos + firstLinePos, "a. " + choice) firstLinePos -= 6 * mm choice = bChoices[card] if choice != "": questionCards.drawString(xPos, yPos + firstLinePos, "b. " + choice) firstLinePos -= 6 * mm choice = cChoices[card] if choice != "": questionCards.drawString(xPos, yPos + firstLinePos, "c. " + choice) firstLinePos -= 6 * mm choice = tChoices[card] if choice != "": questionCards.drawString(xPos, yPos + firstLinePos, "t. " + choice) firstLinePos -= 6 * mm elif answers[card] == 4 or answers[card] == 5: questionCards.drawString(xPos, yPos + firstLinePos, "True") firstLinePos -= 6 * mm choice = fChoices[card] if choice != "": questionCards.drawString(xPos, yPos + firstLinePos, "f. " + choice) elif answers[card] == 4 or answers[card] == 5: questionCards.drawString(xPos, yPos + firstLinePos, "False") card += 1 questionCards.save() answerCards = ReportPage(fileName + "_answers.pdf", pagesize=letter) xOffset = 32 * mm yOffset = 15 * mm card = 0 for y in range(4, -1, -1): for x in range(1, -1, -1): xPos = x * (89 * mm) + xOffset yPos = y * (51 * mm) + yOffset answerCards.drawInlineImage( getCode(answers[card]) + " QR Code.png", xPos, yPos, 50 * mm, 50 * mm) card += 1 answerCards.save()
def create(*args): print("llegoo") outfilepath = os.path.join(os.path.expanduser("~"), "Documents/Reportes") if not os.path.exists(outfilepath): os.mkdir(outfilepath) styles = getSampleStyleSheet() styleN = styles['Normal'] styleH = styles['Heading1'] pdfmetrics.registerFont( TTFont('Vera', '../otros_recursos/Fuentes/Vera.ttf')) pdfmetrics.registerFont( TTFont('VeraB', '../otros_recursos/Fuentes/VeraBd.ttf')) pdfmetrics.registerFontFamily('Vera', normal='Vera', bold='VeraB') # Estilos parrafos del header en medio de las imagenes headstyle = ParagraphStyle(name='MyHeader', fontName='VeraB', fontSize=14, alignment=TA_CENTER) # Estilo de los parrafos que estan debajo de las imagenes prostyle = ParagraphStyle(name='MyDoctorHeader', fontName='Vera', fontSize=10, spaceAfter=4, alignment=TA_LEFT) prostyle2 = ParagraphStyle(name='MyDoctorHeader', fontName='Vera', fontSize=10, spaceAfter=4, alignment=TA_RIGHT) prostyleJ = ParagraphStyle(name='MyDoctorHeader', fontName='Vera', fontSize=10, spaceAfter=4, alignment=TA_JUSTIFY) styleT = ParagraphStyle(name='table', fontName='Vera', fontSize=8, alignment=TA_CENTER) footerstyle = ParagraphStyle(name='MyDoctorHeader', fontName='Vera', alignment=TA_CENTER, fontSize=10, spaceAfter=4) now = datetime.now() if args[6] == 0: outfilename = 'ReporteEntra-{0}-{1}-{2}-{3}-{4}.pdf'.format( now.year, now.month, now.day, now.hour, now.second) if args[6] == 1: outfilename = 'ReporteSal-{0}-{1}-{2}-{3}-{4}.pdf'.format( now.year, now.month, now.day, now.hour, now.second) outfilepath = os.path.join(os.path.expanduser("~"), "Documents/Reportes", outfilename) doc = BaseDocTemplate(outfilepath, pagesize=A4, rightMargin=20, leftMargin=20, topMargin=20, bottomMargin=60) frame = Frame(doc.leftMargin, doc.bottomMargin, doc.width, doc.height - 2 * cm, id='normal') if args[6] == 0: header_content = Paragraph( "<b>Instituto de salud</b>" + "<br/>" + "<b>Entrada de almacen</b>", headstyle) if args[6] == 1: header_content = Paragraph( "<b>Instituto de salud</b>" + "<br/>" + "<b>Salida de almacen</b>", headstyle) template = PageTemplate(id='test', frames=frame, onPage=partial(header, content=header_content)) doc.addPageTemplates([template]) if args[6] == 0: colOne = [[ Paragraph("<b>Entrada almacen del proveedor:</b> " + args[1], style=prostyle) ], [ Paragraph("<b>Numero entrada:</b> " + str(args[2]), style=prostyle) ]] colThree = [[ Paragraph("<b>Fecha de referencia:</b> " + args[3], style=prostyle2) ], [Paragraph("<b>Fecha de entrada:</b> " + args[4], style=prostyle2)]] if args[6] == 1: colOne = [[ Paragraph("<b>Salida de almacén con destino a:</b> " + args[1], style=prostyle) ], [ Paragraph("<b>Numero salida:</b> " + str(args[2]), style=prostyle) ]] colThree = [[ Paragraph("<b>Fecha de solicitud:</b> " + args[3], style=prostyle2) ], [ Paragraph("<b>Fecha de surtimiento:</b> " + args[4], style=prostyle2) ]] tblrow2 = Table([[colOne, colThree]]) tblrow2.setStyle( TableStyle([ ('ALIGN', (1, 0), (1, 0), 'RIGHT'), ('VALIGN', (1, 0), (1, 0), 'MIDDLE'), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('SPAN', (0, 3), (1, 3)), ])) text = [] text.append(tblrow2) text.append(Spacer(1, 10)) if args[6] == 1: if not len(args[5]) > 0: text.append( Paragraph("<b>Observaciones:</b> No hay observaciones", style=prostyleJ)) else: text.append( Paragraph("<b>Observaciones:</b> " + args[5], style=prostyleJ)) data = args[0] newdata = [] temp = [] for i in range(len(data)): for j in range(len(data[1])): if j == 1: if i > 0: desc = data[i][j] temp.append(Paragraph(desc[:50] + "...", styleT)) else: temp.append(Paragraph(data[i][j], styleT)) if j != 1: t = Paragraph(data[i][j], styleT) temp.append(t) newdata.append(temp) temp = [] tableData = Table(newdata, repeatRows=1) tableData.setStyle( TableStyle([ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('TEXTCOLOR', (0, 0), (-1, 0), colors.white), ('BACKGROUND', (0, 0), (-1, 0), '#0097e6'), ('GRID', (0, 1), (-1, -1), 0.5, '#CFEAD4'), ])) text.append(Spacer(1, 10)) text.append(tableData) Fcol1 = [[Paragraph("Nombre y firma de entregado", style=footerstyle)]] Fcol2 = [[Paragraph("", style=footerstyle)]] Fcol3 = [[Paragraph("Nombre y firma de recicido", style=footerstyle)]] tblrow = Table([[Fcol1, Fcol2, Fcol3]]) tblrow.setStyle( TableStyle([ ('LINEABOVE', (0, 0), (0, 0), 0.25, colors.black), ('LINEABOVE', (2, 0), (2, 0), 0.25, colors.black), ])) text.append(TopPadder(tblrow)) doc.build(text, canvasmaker=NumberedCanvas) os.startfile(outfilepath)
VERY_LARGE_FONTSIZE = 14 LARGE_FONTSIZE = 12 MEDIUM_FONTSIZE = 10 SMALL_FONTSIZE = 8 PARAGRAPH_BOTTOM_MARGIN = 5 SECTION_BUFFER_HEIGHT = 10 DATE_FORMAT = '%d/%m/%Y' styles = getSampleStyleSheet() styles.add( ParagraphStyle(name='InfoTitleLargeCenter', fontName=BOLD_FONTNAME, fontSize=LARGE_FONTSIZE, spaceAfter=PARAGRAPH_BOTTOM_MARGIN, alignment=enums.TA_CENTER)) styles.add( ParagraphStyle(name='InfoTitleVeryLargeCenter', fontName=BOLD_FONTNAME, fontSize=VERY_LARGE_FONTSIZE, spaceAfter=PARAGRAPH_BOTTOM_MARGIN * 2, alignment=enums.TA_CENTER)) styles.add( ParagraphStyle(name='InfoTitleLargeLeft', fontName=BOLD_FONTNAME, fontSize=LARGE_FONTSIZE, spaceAfter=PARAGRAPH_BOTTOM_MARGIN, alignment=enums.TA_LEFT, leftIndent=PAGE_WIDTH / 10,
characters_per_line = 61 frame_height = 12 * lines_per_page frame_width = characters_per_line * 72 / 10.0 # Courier pitch is 10 chars/inch page_width, page_height = pagesizes.letter left_margin = 1.5 * inch right_margin = page_width - left_margin - frame_width top_margin = 1 * inch bottom_margin = page_height - top_margin - frame_height character_width = 1.0 / 10 * inch default_style = ParagraphStyle( 'default', fontName='Courier', fontSize=12, leading=12, spaceBefore=0, spaceAfter=0, leftIndent=0, rightIndent=0, ) centered_style = ParagraphStyle( 'default-centered', default_style, alignment=TA_CENTER, ) # Screenplay styles character_style = ParagraphStyle( 'character', default_style, spaceBefore=12, leftIndent=19 * character_width, keepWithNext=1,
#!/usr/bin/python from io import BytesIO from reportlab.lib import enums from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, KeepTogether, Table, TableStyle from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.lib.pagesizes import letter from reportlab.lib.units import inch from courseevaluations.models import QuestionSet, MultipleChoiceQuestionAnswer, FreeformQuestionAnswer title_style = ParagraphStyle(getSampleStyleSheet()["Normal"]) question_set_style = ParagraphStyle(getSampleStyleSheet()["Normal"]) question_style = ParagraphStyle(getSampleStyleSheet()["Normal"]) multiple_choice_option_style = ParagraphStyle(getSampleStyleSheet()["Normal"]) multiple_choice_count_style = ParagraphStyle(getSampleStyleSheet()["Normal"]) freeform_answer_style = ParagraphStyle(getSampleStyleSheet()["Normal"]) title_style.fontSize = 20 title_style.leading = 24 title_style.alignment = enums.TA_RIGHT title_style.fontName = 'Times-BoldItalic' question_style.spaceBefore = 10 question_style.fontName = 'Times-Bold' question_style.fontSize = 12 multiple_choice_option_style.alignment = enums.TA_CENTER multiple_choice_count_style.alignment = enums.TA_CENTER
def _get_stylesheet(self): stylesheet = super()._get_stylesheet() stylesheet.add(ParagraphStyle(name='Sender', fontName=self.font_regular, fontSize=8, leading=10)) stylesheet['InvoiceFrom'].alignment = TA_RIGHT return stylesheet
def style_options(): styles = getSampleStyleSheet() options = {'paragraph': {}} colors = {'black':'#000000', 'dark_blue':'#01429a', 'grey':'#e8e8e8', 'red':'#c11e2e'} normalFontSize = 8 subheadingFontSize = 13 headingFontSize = 20 options.update({'normalFontSize':normalFontSize, 'subheadingFontSize':subheadingFontSize, 'headingFontSize':headingFontSize, 'color_swatch':ColorSwatch(**colors)}) #Add T-Account style style_config = [ ('ALIGN',(0,0),(-1,-1),'CENTER'), ('BACKGROUND', (2,0),(2,-1), colors['grey']), ('BACKGROUND', (-1,0),(-1,-1), colors['grey']), ('FONTSIZE', (0, 0), (-1, -1), normalFontSize), ('LINEBELOW', (0, 0), (-1, 0), 1, colors['black']), ('LINEABOVE', (0, 0), (-1, 0), 1, colors['black']), ('LINEAFTER', (2, 0), (2, -1), 1, colors['black']) ] t_acc_option = PDFTableStyle('t_account',OPEXATableStyle(style_config)) options.update({t_acc_option.name:t_acc_option}) #Add Trial Balance style trial_bal_config = [ ('ALIGN',(1,0),(-1,-1),'RIGHT'), # Grid ('LINEAFTER', (0, 0), (-1, -1), 1, colors['black']), ('LINEBEFORE', (0, 0), (-1, -1), 1, colors['black']), ('LINEABOVE', (0, 0), (-1, 0), 1, colors['black']), ('LINEBELOW', (0, -1), (-1, -1), 1, colors['black']), ] trial_bal_option = PDFTableStyle('trial_balance',OPEXATableStyle(trial_bal_config)) options.update({trial_bal_option.name:trial_bal_option}) #Add Trial Balance style pl_option = [ ('ALIGN',(1,0),(-1,-1),'CENTER'), # Grid ('LINEAFTER', (0, 0), (-1, -1), 1, colors['black']), ('LINEBEFORE', (0, 0), (-1, -1), 1, colors['black']), ('LINEABOVE', (0, 0), (-1, 0), 1, colors['black']), ('LINEBELOW', (0, -1), (-1, -1), 1, colors['black']) ] pl_option = PDFTableStyle('profit_and_loss',OPEXATableStyle(trial_bal_config)) options.update({pl_option.name:pl_option}) #Paragraph Styles sub_heading_style = ParagraphStyle('Sub-Heading') sub_heading_style.textColor = 'black' sub_heading_style.fontSize = subheadingFontSize sub_heading_style.alignment = TA_CENTER options['paragraph'].update({'sub_heading':sub_heading_style}) heading_style = ParagraphStyle('Heading') heading_style.textColor = 'black' heading_style.fontSize = headingFontSize heading_style.alignment = TA_CENTER options['paragraph'].update({'heading':heading_style}) default_style = copy.copy(styles["Normal"]) options['paragraph'].update({'default':default_style}) centered = copy.copy(styles["Normal"]) centered.alignment = TA_CENTER options['paragraph'].update({'centered':centered}) centered_sub_heading = copy.copy(centered) centered_sub_heading.fontSize = subheadingFontSize options['paragraph'].update({'centered_sub_heading':centered_sub_heading}) return options
from reportlab.lib.utils import ImageReader from reportlab.lib import colors from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.ttfonts import TTFont from . import gen_title from .customization import DATE_FMT, labels_text from .custom_bill import draw_head, draw_bvr from .signature import datamatrix LEFT_MARGIN = 1.7*cm RIGHT_MARGIN = 1.2*cm TOP_MARGIN = 1*cm BOTTOM_MARGIN = 2.5*cm DEFAULT_STYLE = ParagraphStyle('default') TITLE_STYLE = ParagraphStyle('title', DEFAULT_STYLE, fontSize=18, fontName=DEFAULT_STYLE.fontName+'-Bold', leading=22) BASE_TSTYLE = [('TOPPADDING', (0, 0), (-1, -1), 0), ('BOTTOMPADDING', (0, 0), (-1, -1), 0), ('LEFTPADDING', (0, 0), (-1, -1), 2), ('RIGHTPADDING', (0, 0), (-1, -1), 0), ] BOXED_TSTYLE = BASE_TSTYLE + [('FONT', (0, 0), (0, -1), TITLE_STYLE.fontName, 8, 12), ('FONT', (1, 0), (-1, -1), DEFAULT_STYLE.fontName, 8, 12), ('BOX', (0, 0), (-1, -1), 0.5, colors.black), ] THERAPEUTE_TSTYLE = BOXED_TSTYLE + [('SPAN', (0, 1), (0, 2)), ('SPAN', (0, 3), (0, 4)), ('SPAN', (1, 0), (-1, 0)), ('LEADING', (0, 1), (0, -1), 8), ('VALIGN', (0, 1), (0, -1), 'TOP'),
def build_doc(title, name, institution_name, voting_start, voting_end, extended_until, data, language, filename="election_results.pdf", new_page=True, score=False, parties=False): with translation.override(language[0]): pageinfo = _("Zeus Elections - Poll Results") title = _('Results') DATE_FMT = "%d/%m/%Y %H:%M" if isinstance(voting_start, datetime.datetime): voting_start = _('Start: %(date)s') % { 'date': voting_start.strftime(DATE_FMT) } if isinstance(voting_end, datetime.datetime): voting_end = _('End: %(date)s') % { 'date': voting_end.strftime(DATE_FMT) } if extended_until and isinstance(extended_until, datetime.datetime): extended_until = _('Extension: %(date)s') % { 'date': extended_until.strftime(DATE_FMT) } else: extended_until = "" if not isinstance(data, list): data = [(name, data)] # reset pdfdoc timestamp in order to force a fresh one to be used in # pdf document metadata. pdfdoc._NOWT = None elements = [] doc = SimpleDocTemplate(filename, pagesize=A4) styles = getSampleStyleSheet() styles.add( ParagraphStyle(name='Zeus', fontName=DEFAULT_FONT, fontSize=12, leading=16, alignment=TA_JUSTIFY)) styles.add( ParagraphStyle(name='ZeusBold', fontName=DEFAULT_FONT, fontSize=12, leading=16, alignment=TA_JUSTIFY)) styles.add( ParagraphStyle(name='ZeusSubHeading', fontName=DEFAULT_FONT, fontSize=14, alignment=TA_JUSTIFY, spaceAfter=16)) styles.add( ParagraphStyle(name='ZeusHeading', fontName=DEFAULT_FONT, fontSize=16, alignment=TA_CENTER, spaceAfter=16)) intro_contents = [voting_start, voting_end, extended_until] make_heading(elements, styles, [title, name, institution_name]) make_intro(elements, styles, intro_contents) make_election_voters(elements, styles, data) for poll_name, poll_results, q_repr_data, qdata, poll_voters in data: poll_intro_contents = [poll_name] parties_results = [] candidates_results = {} load_results_fn = load_results if score: load_results_fn = load_score_results if parties: load_results_fn = load_parties_results total_votes, blank_votes, parties_results, candidates_results = \ load_results_fn(poll_results, q_repr_data, qdata) if new_page: elements.append(PageBreak()) elements.append(Spacer(1, 12)) elements.append(Spacer(1, 12)) elements.append(Spacer(1, 12)) make_subheading(elements, styles, poll_intro_contents) elements.append(Spacer(1, 12)) make_intro(elements, styles, intro_contents) make_poll_voters(elements, styles, poll_voters) elements.append(Spacer(1, 12)) make_results(elements, styles, total_votes, blank_votes, parties_results, candidates_results) doc.build(elements, onFirstPage=make_first_page_hf, onLaterPages=make_later_pages_hf(pageinfo))
def build_unigov_doc(title, name, institution_name, voting_start, voting_end, extended_until, results, language, filename="election_results.pdf", new_page=True, score=False, parties=False): with translation.override(language[0]): pageinfo = _("Zeus Elections - Poll Results") title = _('Results') DATE_FMT = "%d/%m/%Y %H:%M" if isinstance(voting_start, datetime.datetime): voting_start = _('Start: %(date)s') % { 'date': voting_start.strftime(DATE_FMT) } if isinstance(voting_end, datetime.datetime): voting_end = _('End: %(date)s') % { 'date': voting_end.strftime(DATE_FMT) } if extended_until and isinstance(extended_until, datetime.datetime): extended_until = _('Extension: %(date)s') % { 'date': extended_until.strftime(DATE_FMT) } else: extended_until = "" # reset pdfdoc timestamp in order to force a fresh one to be used in # pdf document metadata. pdfdoc._NOWT = None elements = [] doc = SimpleDocTemplate(filename, pagesize=A4) styles = getSampleStyleSheet() styles.add( ParagraphStyle(name='Zeus', fontName=DEFAULT_FONT, fontSize=12, leading=16, alignment=TA_JUSTIFY)) styles.add( ParagraphStyle(name='ZeusBold', fontName=DEFAULT_FONT, fontSize=12, leading=16, alignment=TA_JUSTIFY)) styles.add( ParagraphStyle(name='ZeusSubHeading', fontName=DEFAULT_FONT, fontSize=14, alignment=TA_JUSTIFY, spaceAfter=16)) styles.add( ParagraphStyle(name='ZeusHeading', fontName=DEFAULT_FONT, fontSize=16, alignment=TA_CENTER, spaceAfter=16)) intro_contents = [voting_start, voting_end, extended_until] make_heading(elements, styles, [title, name, institution_name]) make_intro(elements, styles, intro_contents) group_a = results['group_a'] group_b = results['group_b'] totals = results['totals'] elements.append(Spacer(1, 12)) elements.append(Spacer(1, 12)) elements.append(Spacer(1, 12)) groups_table = [] for g in [group_a, group_b]: group_elements = [] make_subheading(group_elements, styles, [g['name']]) _total_voters = g['voters'] _excluded_voters = g['excluded'] group_elements.append( Paragraph(escape(_("Voters") + ": " + str(_total_voters)), styles['Zeus'])) group_elements.append( Paragraph(escape(_('Total votes: %d') % g['voted']), styles['Zeus'])) group_elements.append( Paragraph(escape(_('Blank: %d') % g['blank']), styles['Zeus'])) if _excluded_voters > 0: group_elements.append( Paragraph( escape( _("Excluded voters") + ": " + str(_excluded_voters)), styles['Zeus'])) group_elements.append(Spacer(1, 12)) group_elements.append(Spacer(1, 12)) group_elements.append(Spacer(1, 12)) group_elements.append(Spacer(1, 12)) group_elements.append(Spacer(1, 12)) groups_table.append(group_elements) t = Table(list(zip(*groups_table))) table_style = TableStyle([('FONT', (0, 0), (-1, -1), DEFAULT_FONT)]) t.setStyle(table_style) elements.append(t) questions = OrderedDict() for q in list(results['totals']['counts'].keys()): total_counts = totals['counts'][q] total_counts_rounded = totals['counts_rounded'][q] group_a_counts = group_a['counts'][q] group_b_counts = group_b['counts'][q] questions[q] = {} for candidate in list(totals['counts'][q].keys()): questions[q][candidate] = { 'total': total_counts[candidate], 'total_rounded': int(total_counts_rounded[candidate]), 'group_a': group_a_counts[candidate], 'group_b': group_b_counts[candidate], } elements.append(PageBreak()) for question, candidates in questions.items(): make_heading(elements, styles, [question]) elements.append(Spacer(1, 12)) elements.append(Spacer(1, 12)) elements.append(Spacer(1, 12)) group_a_name = group_a['name'].split( " ", 1)[1] if " " in group_a['name'] else group_a['name'] group_b_name = group_b['name'].split( " ", 1)[1] if " " in group_b['name'] else group_b['name'] candidates_table = [[ Paragraph(escape(_("Candidate")), styles['ZeusBold']), Paragraph(escape(_("Total")), styles['ZeusBold']), Paragraph(escape(group_a_name), styles['ZeusBold']), Paragraph(escape(group_b_name), styles['ZeusBold']) ]] table_data = [] for candidate, counts in candidates.items(): table_data.append([ Paragraph(escape(candidate), styles['Zeus']), counts['total_rounded'], counts['group_a'], counts['group_b'], ]) candidates_table += sorted(table_data, key=lambda x: -x[1]) from reportlab.lib.units import inch t = Table(candidates_table, colWidths=[4 * inch] + [1.2 * inch] * 3) table_style = TableStyle([ ('FONT', (0, 0), (-1, -1), DEFAULT_FONT), ('ALIGN', (1, 1), (-2, -2), 'RIGHT'), ]) table_style = TableStyle([ ('FONT', (0, 0), (-1, -1), DEFAULT_FONT), ('ALIGN', (1, 1), (-2, -2), 'LEFT'), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ]) t.setStyle(table_style) elements.append(t) elements.append(PageBreak()) doc.build(elements, onFirstPage=make_first_page_hf, onLaterPages=make_later_pages_hf(pageinfo))
def build_stv_doc(title, name, institution_name, voting_start, voting_end, extended_until, data, language, filename="election_results.pdf", new_page=True): with translation.override(language[0]): pageinfo = _("Zeus Elections - Poll Results") title = _('Results') DATE_FMT = "%d/%m/%Y %H:%M" if isinstance(voting_start, datetime.datetime): voting_start = _('Start: %(date)s') % { 'date': voting_start.strftime(DATE_FMT) } if isinstance(voting_end, datetime.datetime): voting_end = _('End: %(date)s') % { 'date': voting_end.strftime(DATE_FMT) } if extended_until and isinstance(extended_until, datetime.datetime): extended_until = _('Extension: %(date)s') % { 'date': extended_until.strftime(DATE_FMT) } else: extended_until = "" if not isinstance(data, list): data = [(name, data)] # reset pdfdoc timestamp in order to force a fresh one to be used in # pdf document metadata. pdfdoc._NOWT = None elements = [] doc = SimpleDocTemplate(filename, pagesize=A4) styles = getSampleStyleSheet() styles.add( ParagraphStyle(name='Zeus', fontName=DEFAULT_FONT, fontSize=12, leading=16, alignment=TA_JUSTIFY)) styles.add( ParagraphStyle(name='ZeusBold', fontName=DEFAULT_FONT, fontSize=12, leading=16, alignment=TA_JUSTIFY)) styles.add( ParagraphStyle(name='ZeusSubHeading', fontName=DEFAULT_FONT, fontSize=14, alignment=TA_JUSTIFY, spaceAfter=16)) styles.add( ParagraphStyle(name='ZeusHeading', fontName=DEFAULT_FONT, fontSize=16, alignment=TA_CENTER, spaceAfter=16)) intro_contents = [voting_start, voting_end, extended_until] make_heading(elements, styles, [title, name, institution_name]) make_intro(elements, styles, intro_contents) make_election_voters(elements, styles, data, stv=True) for poll_name, poll_results, questions, poll_voters in data: poll_intro_contents = [poll_name] #total_votes, blank_votes, parties_results, candidates_results = \ # load_results(poll_results) if new_page: elements.append(PageBreak()) elements.append(Spacer(1, 12)) elements.append(Spacer(1, 12)) elements.append(Spacer(1, 12)) make_subheading(elements, styles, poll_intro_contents) elements.append(Spacer(1, 12)) make_intro(elements, styles, intro_contents) make_poll_voters(elements, styles, poll_voters) elements.append(Spacer(1, 12)) #make dict with indexing as key and name as value counter = 0 indexed_cands = {} for item in questions[0]['answers']: indexed_cands[str(counter)] = item counter += 1 elected = [[_('Elected')]] json_data = poll_results[0] for item in json_data: elected.append([indexed_cands[item[0]]]) t = Table(elected) my_table_style = TableStyle([ ('FONT', (0, 0), (-1, -1), DEFAULT_FONT), ('ALIGN', (1, 1), (-2, -2), 'LEFT'), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.black), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ]) t.setStyle(my_table_style) elements.append(t) actions_desc = { 'elect': _('Elect'), 'eliminate': _('Eliminated'), 'quota': _('Eliminated due to quota restriction') } table_header = [_('Candidate'), _('Votes'), _('Draw'), _('Action')] stv = STVParser(poll_results[2]) rounds = list(stv.rounds()) for num, round in rounds: round_name = _('Round ') round_name += str(num) elements.append(Paragraph(round_name, styles['Zeus'])) round_table = [] temp_table = [] temp_table.append(table_header) for name, cand in round['candidates'].items(): actions = [x[0] for x in cand['actions']] draw = _("NO") if 'random' in actions: draw = _("YES") action = None if len(actions): action = actions_desc.get(actions[-1]) votes = cand['votes'] cand_name = indexed_cands[str(name)] cand_name = cand_name.split(':')[0] row = [cand_name, votes, draw, action] temp_table.append(row) round_table = Table(temp_table) round_table.setStyle(my_table_style) elements.append(round_table) elements.append(Spacer(1, 12)) doc.build(elements, onFirstPage=make_first_page_hf, onLaterPages=make_later_pages_hf(pageinfo))
make_header(pdf_rep1, sizex, sizey, sizex, 180. , color_RGB2, color_RGB3, path_elem,\ title_pdf1, str_semana) make_footer(pdf_rep1, 0, 0, sizex, 120. , color_RGB2, path_elem) # contenido panel 1 pdf_rep1.setFillColorRGB(color_RGB1[0]/255., color_RGB1[1]/255., color_RGB1[2]/255.) pdf_rep1.rect(10., 150., 545., 815., fill = False, stroke = True) pdf_rep1.rect(10., 940., 470., 50., fill = True, stroke = True) pdf_rep1.setFillColorRGB(1,1,1) pdf_rep1.setFont("Avenir", 24) pdf_rep1.drawString(25., 955.,'Precipitaciones sobre el Valle de Aburrá') pdf_rep1.drawImage(path_elem+'ppt_rad/Evento.png', \ 25., 400., 520., 520., mask = 'auto') style1 = ParagraphStyle(name='Justify', alignment=TA_JUSTIFY, fontName='Avenir', fontSize=20,\ leading = 24) par1 = Paragraph (u'Imagen de reflectividad del radar a las 06:44 del 04 de agosto, \ correspondiente al evento de precipitación con número de informe \ 1176, en el cual se observa que durante el evento las precipitaciones \ alcanzaron a cubrir por completo el Valle de Aburrá con intensidades \ predominantemente bajas y algunos núcleos de intensidades medias \ en la ladera occidental de Medellín.', style1) par1.wrap(515, 890) par1.drawOn(pdf_rep1, 25., 165) # contenido panel 2 pdf_rep1.setFillColorRGB(color_RGB1[0]/255., color_RGB1[1]/255., color_RGB1[2]/255.) pdf_rep1.rect(565., 575., 1100., 395., fill = False, stroke = True) pdf_rep1.rect(565., 940., 737., 50., fill = True, stroke = True)
def export_rel_pdf(self): Story = [] home = os.environ['PYARCHINIT_HOME'] home_DB_path = '{}{}{}'.format(home, os.sep, 'pyarchinit_DB_folder') logo_path = '{}{}{}'.format(home_DB_path, os.sep, 'logo.jpg') logo = Image(logo_path) ## if test_image.drawWidth < 800: logo.drawHeight = 1.5 * inch * logo.drawHeight / logo.drawWidth logo.drawWidth = 1.5 * inch magName = "Pythonista" subPrice = "99.00" limitedDate = "03/05/2010" freeGift = "tin foil hat" # DATI INTESTAZIONE formatted_time = time.ctime() full_name = "Responsabile: Luca Mandolesi" address_parts = [ "Sito: Via Cavour 60, Ravenna", "Indirizzo: Via Cavour 60", "Comune: Ravenna" ] Story.append(PageBreak()) #im = Image(logo) Story.append(logo) styles = getSampleStyleSheet() styles.add( ParagraphStyle(name='Justify', alignment=TA_JUSTIFY, bulletText='-')) ptext = '<font size=12>%s</font>' % formatted_time Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 12)) # Create return address ptext = '<font size=12>%s</font>' % full_name Story.append(Paragraph(ptext, styles["Normal"])) for part in address_parts: ptext = '<font size=12>%s</font>' % part.strip() Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 12)) ptext = '<font size=12>Dear %s:</font>' % full_name.split()[0].strip() Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 12)) Story.append(PageBreak()) ###Sezione 2 - SITO # Titolo descrizione sito # funzioni di ricerca search_dict = {'sito': "'" + str(self.SITO) + "'"} self.DATA_LIST = self.DB_MANAGER.query_bool(search_dict, "SITE") # formattazione del testo ptext = '<font size=14><b>Sito: %s</b></font>' % self.DATA_LIST[0].sito Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 12)) # Descrizione sito ptext = '<font size=12> <b>Descrizione del sito </b><br/> %s </font>' % self.DATA_LIST[ 0].descrizione Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 12)) # Titolo descrizione periodo # cerca se e' presente una scansione cronologica del sito self.DATA_LIST = [] periodizzazione_records = self.search_records('sito', self.SITO, 'PERIODIZZAZIONE') if bool(periodizzazione_records): Story.append(PageBreak()) # crea l'intestazione della Periodizzazione ptext = '<font size=16 ><b>Periodizzazione di scavo</b><br/><br/></font>' Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 12)) # estrae gli id dai record id_list_periodo = self.extract_id_list(periodizzazione_records, 'id_perfas') # carica i record di periodo ordinati in base al codice di periodo self.load_data_sorted(id_list_periodo, ['cont_per'], 'asc', 'PERIODIZZAZIONE', 'id_perfas') for sing_rec in range(len(self.DATA_LIST)): ptext = '<font size=12 ><b>Periodo: %s - Fase %s - Datazione estesa: %s</b></font><br/>' % ( self.DATA_LIST[sing_rec].periodo, self.DATA_LIST[sing_rec].fase, self.DATA_LIST[sing_rec].datazione_estesa) Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 12)) Story.append(PageBreak()) for sing_rec in range(len(self.DATA_LIST)): ptext = '<font size=12 ><b>Periodo: %s - Fase %s </b></font><br/>' % ( self.DATA_LIST[sing_rec].periodo, self.DATA_LIST[sing_rec].fase) Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 12)) # Descrizione periodo ptext = '<font size=12> %s </font><br/><br/>' % ( self.DATA_LIST[sing_rec].descrizione) Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 12)) # Titolo descrizione struttura # cerca se sono presenti strutture self.DATA_LIST = [] strutture_records = self.search_records('sito', self.SITO, 'STRUTTURA') if bool(strutture_records): Story.append(PageBreak()) # crea l'intestazione delle Strutture ptext = '<font size=16 ><b>Strutture di scavo</b><br/><br/></font>' Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 12)) # estrae gli id dai record id_list_strutture = self.extract_id_list(strutture_records, 'id_struttura') # carica i record di struttura ordinati in base alla sigla struttura e il suo numero self.load_data_sorted(id_list_strutture, ['sigla_struttura', 'numero_struttura'], 'asc', 'STRUTTURA', 'id_struttura') # crea l'intestazione dell'elenco delle sigle struttura presenti nel DB ptext = '<font size=16 >Elenco Strutture<br/></font>' Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 12)) # Viene stampata la prima sigla di struttura rec_sigla_struttura = self.search_records( 'sigla', self.DATA_LIST[0].sigla_struttura, 'PYARCHINIT_THESAURUS_SIGLE') sigla_temp = self.DATA_LIST[0].sigla_struttura ptext = '<font size=14 ><b>Sigla: %s - Tipologia: %s</b><br/></font>' % ( sigla_temp, rec_sigla_struttura[0].sigla_estesa) Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 12)) #ptext = '<bullet>' #Story.append(Paragraph(ptext, styles["Normal"],bulletText='-')) # crea l'elenco delle sigle struttura presenti nel DB for rec in range(len(self.DATA_LIST)): if sigla_temp == self.DATA_LIST[rec].sigla_struttura: rec_sigla_struttura = self.search_records( 'sigla', self.DATA_LIST[rec].sigla_struttura, 'PYARCHINIT_THESAURUS_SIGLE') ptext = '<font size=12 ><b> Sigla: %s%s - Tipologia: %s </b></font>' % ( self.DATA_LIST[rec].sigla_struttura, str(self.DATA_LIST[rec].numero_struttura), rec_sigla_struttura[0].sigla_estesa) Story.append( Paragraph(ptext, styles["Normal"], bulletText='-')) Story.append(Spacer(1, 12)) ptext = '<font size=12 > - Periodo: %s - Fase: %s<br/><br/></font>' % ( str(self.DATA_LIST[rec].periodo_iniziale), str(self.DATA_LIST[rec].fase_iniziale)) Story.append( Paragraph(ptext, styles["Normal"], bulletText=' ')) Story.append(Spacer(1, 12)) else: #ptext = '<bullet>' #Story.append(Paragraph(ptext, styles["Normal"], bulletText='-')) rec_sigla_struttura = self.search_records( 'sigla', self.DATA_LIST[rec].sigla_struttura, 'PYARCHINIT_THESAURUS_SIGLE') sigla_temp = self.DATA_LIST[rec].sigla_struttura ptext = '<font size=14 ><b>Sigla: %s - Tipologia: %s</b><br/></font>' % ( sigla_temp, rec_sigla_struttura[0].sigla_estesa) Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 12)) ptext = '<bullet>' Story.append(Paragraph(ptext, styles["Normal"])) ptext = '<font size=12 ><b>Sigla: %s - Tipologia: %s </b></font>' % ( self.DATA_LIST[rec].sigla_struttura, str(self.DATA_LIST[rec].numero_struttura), rec_sigla_struttura[0].sigla_estesa) Story.append( Paragraph(ptext, styles["Normal"], bulletText='-')) Story.append(Spacer(1, 12)) ptext = '<font size=12 > - Periodo: %s - Fase: %s<br/><br/></font>' % ( str(self.DATA_LIST[rec].periodo_iniziale), str(self.DATA_LIST[rec].fase_iniziale)) Story.append( Paragraph(ptext, styles["Normal"], bulletText=' ')) Story.append(Spacer(1, 12)) #ptext = '</bullet>' #Story.append(Paragraph(ptext, styles["Normal"])) # crea la descrizione e interpretazione delle singole strutture presenti nel DB ptext = '<font size=16 ><b>Descrizione singole strutture</b><br/></font>' Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 12)) for rec in range(len(self.DATA_LIST)): rec_sigla_struttura = self.search_records( 'sigla', self.DATA_LIST[rec].sigla_struttura, 'PYARCHINIT_THESAURUS_SIGLE') ptext = '<font size=14 ><b>Sigla: %s%s - Tipologia: %s </b><br/><br/></font>' % ( self.DATA_LIST[rec].sigla_struttura, str(self.DATA_LIST[rec].numero_struttura), rec_sigla_struttura[0].sigla_estesa) Story.append(Paragraph(ptext, styles["Normal"])) ptext = '<font size=12 ><b>Descrizione</b><br/>%s<br/><b>Intepretazione</b><br/>%s<br/></font>' % ( str(self.DATA_LIST[rec].descrizione), str(self.DATA_LIST[rec].interpretazione)) Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 12)) Story.append(PageBreak()) # Titolo dati di cantiere ptext = '<font size=14 ><b>Dati Cantiere</b></font>' Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 12)) # Descrizione dati di scavo ptext = """<font size=12>Direttore Cantiere: Fox Molder</font>""" # % (magName, issueNum,subPrice,limitedDate,freeGift) Story.append(Paragraph(ptext, styles["Justify"])) Story.append(Spacer(1, 12)) Story.append(PageBreak()) # Titolo Catalogo Immagini 1 styles.add(ParagraphStyle(name='Center', alignment=TA_CENTER)) ptext = '<font size=36><b>Catalogo Immagini</b></font>' Story.append(Paragraph(ptext, styles["Center"])) Story.append(Spacer(1, 20)) Story.append(PageBreak()) # Immagini home = os.environ['PYARCHINIT_HOME'] home_DB_path = '{}{}{}'.format(home, os.sep, 'pyarchinit_DB_folder') logo_path = '{}{}{}'.format(home_DB_path, os.sep, 'logo.jpg') logo = Image(logo_path) #logo = os.path.join(os.path.dirname(__file__), "..", "..", "iconadarte.png") #im = Image(logo) Story.append(logo) # Didascalia ptext = '<font size=10><b>Figura 1 - Esempio di foto</b></font>' Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 200)) #logo = os.path.join(os.path.dirname(__file__), "..", "..", "iconadarte.png") #im = Image(logo) Story.append(logo) # Didascalia ptext = '<font size=10><b>Figura 2 - Esempio di foto</b></font>' Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 12)) Story.append(PageBreak()) # Titolo Allegato 1 ptext = '<font size=36><b>Allegato 1</b></font>' Story.append(Paragraph(ptext, styles["Center"])) Story.append(Spacer(1, 20)) # Titolo Allegato 1 ptext = '<font size=36><b>Schede US</b></font>' Story.append(Paragraph(ptext, styles["Center"])) Story.append(Spacer(1, 50)) # Chiusura del documento filename = '{}{}{}'.format(self.PDF_path, os.sep, 'relazione.pdf') f = open(filename, "wb") # doc = SimpleDocTemplate(f) # doc.build(elements, canvasmaker=NumberedCanvas_Periodizzazionesheet) doc = SimpleDocTemplate(f, pagesize=A4, rightMargin=72, leftMargin=72, topMargin=72, bottomMargin=40) doc.build(Story, canvasmaker=NumberedCanvas_Relazione, onFirstPage=self.myFirstPage) f.close()
def createFormGCoverLetter(request, pk): caseObj = get_object_or_404(TblAppealMaster, pk=pk) Story = [] logo = "S:\\11_SRI Templates\\SRI_Letterhead - 2018 12 18.png" subject = "Schedule G and Jurisdictional Documents" caseName = caseObj.appealName caseNum = caseObj.caseNumber im = Image(logo, 8 * inch, 2 * inch) Story.append(im) styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY)) ptext = '<font size="12">%s</font>' % 'February 16, 2021' Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 24)) # Create Address addressParts = [ "Chairperson", "Provider Reimbursement Review Board", "CMS Office of Hearings", "7500 Security Boulevard", "Mail Stop: N2-19-25", "Baltimore, MD 21244" ] for part in addressParts: ptext = '<font size="12">%s</font>' % part.strip() Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 24)) ptext = '<font size="12">RE: ' \ ' %s</font>' % subject Story.append(Paragraph(ptext)) ptext = '<font size="12"> ' \ ' ' \ ' ' \ 'Case Name: %s</font>' % caseName Story.append(Paragraph(ptext, styles["Normal"])) ptext = '<font size="12"> ' \ ' ' \ ' ' \ 'Case Number: %s</font>' % caseNum Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 24)) ptext = '<font size="12">Dear Sir/Madam:</font>' Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 12)) ptext = '<font size="12"> Please find the enclosed Model Form G - Schedule of Providers and' \ 'supporting documentation.</font>' Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 12)) ptext = '<font size="12">Should you have any questions, please contact me at (630)-530-7100.</font>' Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 12)) ptext = '<font size="12">Sincerely,</font>' Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 48)) addressParts = [ "Randall Gienko", "Manager", "Strategic Reimbursement Group, LLC", "360 W. Butterfield Road, Suite 310", "Elmhurst, IL 60126", "Phone: (630) 530-7100", "Email:[email protected]" ] for part in addressParts: ptext = '<font size="12">%s</font>' % part.strip() Story.append(Paragraph(ptext, styles["Normal"])) buffer = BytesIO() doc = SimpleDocTemplate(buffer, pagesize=letter, rightMargin=72, leftMargin=72, topMargin=0, bottomMargin=18) doc.build(Story) pdf_value = buffer.getvalue() buffer.close() response = HttpResponse(content_type='application/pdf') response[ 'Content-Disposition'] = 'attachment; filename="formGCoverLetter.pdf"' response.write(pdf_value) return response
from reportlab.lib import colors from reportlab.graphics.charts.piecharts import Pie from reportlab.graphics.shapes import * # not used? from reportlab.graphics.charts.barcharts import VerticalBarChart from reportlab.graphics.charts.textlabels import Label import energyusage.convert as convert import evaluate as evaluate import locate import math year = "2016" styles = getSampleStyleSheet() TitleStyle = ParagraphStyle(name='Normal', fontSize=16, alignment= TA_CENTER, fontName="Times-Bold") SubtitleStyle = ParagraphStyle(name='Normal',fontSize=12, alignment= TA_CENTER, fontName="Times-Roman") # MonospacedSubtitleStyle = ParagraphStyle(name='Normal',fontSize=12, alignment= TA_CENTER, fontName="Courier") HeaderStyle = ParagraphStyle(name='Normal',fontSize=16) SubheaderStyle = ParagraphStyle(name='Normal', fontName="Times-Roman") DescriptorStyle = ParagraphStyle(name='Normal',fontSize=14, alignment= TA_CENTER) BodyTextStyle = styles["BodyText"] def bold(text): return "<b>"+text+"</b>" def title(text, Elements, style=TitleStyle, klass=Paragraph, sep=0.3): """ Creates title of report """ t = klass(bold(text), style) Elements.append(t)
relative=1) pagex += w + commaw # Default paragraph styles for tables of contents. # (This could also be generated automatically or even # on-demand if it is not known how many levels the # TOC will finally need to display...) delta = 1 * cm epsilon = 0.5 * cm defaultLevelStyles = [ ParagraphStyle(name='Level 0', fontName='Times-Roman', fontSize=10, leading=11, firstLineIndent=0, leftIndent=epsilon) ] defaultTableStyle = \ TableStyle([ ('VALIGN', (0,0), (-1,-1), 'TOP'), ('RIGHTPADDING', (0,0), (-1,-1), 0), ('LEFTPADDING', (0,0), (-1,-1), 0), ]) class TableOfContents(IndexingFlowable): """This creates a formatted table of contents.
def _ptoTestCase(self): """PTO stands for Please Turn Over and is a means for specifying content to be inserted when stuff goes over a page. This makes one long multi-page paragraph.""" # Build story. story = [] def fbreak(story=story): story.append(FrameBreak()) styleSheet = getSampleStyleSheet() H1 = styleSheet['Heading1'] H1.pageBreakBefore = 0 H1.keepWithNext = 0 bt = styleSheet['BodyText'] pto = ParagraphStyle('pto', parent=bt) pto.alignment = TA_RIGHT pto.fontSize -= 1 def ColorParagraph(c, text, style): return Paragraph('<para color="%s">%s</para>' % (c, text), style) def ptoblob(blurb, content, trailer=None, header=None, story=story, H1=H1): if type(content) not in (type([]), type(())): content = [content] story.append( PTOContainer([Paragraph(blurb, H1)] + list(content), trailer, header)) t0 = [ColorParagraph('blue', 'Please turn over', pto)] h0 = [ColorParagraph('blue', 'continued from previous page', pto)] t1 = [ColorParagraph('red', 'Please turn over(inner)', pto)] h1 = [ColorParagraph('red', 'continued from previous page(inner)', pto)] ptoblob('First Try at a PTO', [Paragraph(text0, bt)], t0, h0) fbreak() c1 = Table( [('alignment', 'align\012alignment'), ('bulletColor', 'bulletcolor\012bcolor'), ('bulletFontName', 'bfont\012bulletfontname'), ('bulletFontSize', 'bfontsize\012bulletfontsize'), ('bulletIndent', 'bindent\012bulletindent'), ('firstLineIndent', 'findent\012firstlineindent'), ('fontName', 'face\012fontname\012font'), ('fontSize', 'size\012fontsize'), ('leading', 'leading'), ('leftIndent', 'leftindent\012lindent'), ('rightIndent', 'rightindent\012rindent'), ('spaceAfter', 'spaceafter\012spacea'), ('spaceBefore', 'spacebefore\012spaceb'), ('textColor', 'fg\012textcolor\012color')], style=[ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('INNERGRID', (0, 0), (-1, -1), 0.25, black), ('BOX', (0, 0), (-1, -1), 0.25, black), ], ) ptoblob('PTO with a table inside', c1, t0, h0) fbreak() ptoblob('A long PTO', [Paragraph(text0 + ' ' + text1, bt)], t0, h0) fbreak() ptoblob('2 PTO (inner split)', [ ColorParagraph('pink', text0, bt), PTOContainer([ ColorParagraph(black, 'Inner Starts', H1), ColorParagraph('yellow', text2, bt), ColorParagraph('black', 'Inner Ends', H1) ], t1, h1), ColorParagraph('magenta', text1, bt) ], t0, h0) _showDoc('test_platypus_pto.pdf', story)
def LATTE_DV(tic, indir, syspath, transit_list, sectors_all, target_ra, target_dec, tessmag, teff, srad, mstar, vmag, logg, mass_ast, radius_ast, logg_ast, numax, deltanu, plx, c_id, bls_stats1, bls_stats2, tpf_corrupt, astroquery_corrupt, FFI, bls = False, model = False, mpi = False, test = 'no'): ''' funtion that makes compiles all of the information and figures into a comprehensive pdf summary document. Parameters ---------- tic : str target TIC ID indir : str path to directory where all the plots and data will be saved. sectors_all : list all the sectors in which the target has been/ will be observed target_ra : float the right ascension of the target target_dec : float the declination of the target tessmag : float TESS magnitude of the target star teff : float effective temperature of the tagret star (K) srad : float radius of the target star (solar radii) bls_stats1 : list list of the returned stats of the initial bls search bls_stats2 : list list of the returned stats of the second bls search FFI : bool whether the input data is from FFIs (True = from FFIs) bls : bool (false) whether the bls search was run model : bool (false) whether the transit was modelled (only works if payenti has sucessfully been installed) Returns ------- LATTE Data Validation report in PDF format. ''' # ---- CHECK WHETHER THE TARGET IS A TCE OR A TOI ---- print ("\n Start compiling the data validation report...") # TCE ----- lc_dv = np.genfromtxt('{}/data/tesscurl_sector_all_dv.sh'.format(indir), dtype = str) TCE_links = [] for i in lc_dv: if str(tic) in str(i[6]): TCE_links.append(i[6]) if len(TCE_links) == 0: TCE = " - " else: TCE_links = np.sort(TCE_links) TCE_link = TCE_links[0] # this link should allow you to acess the MAST DV report TCE = 'Yes **' TCE_link = '<link href="%s" color="blue">here</link>' % TCE_link # TOI ----- TOI_planets = pd.read_csv('{}/data/TOI_list_star_params.txt'.format(indir), comment = "#") TOIpl = TOI_planets.loc[TOI_planets['TIC ID'] == float(tic)] if len(TOIpl) == 0: TOI = ' - ' else: TOI = str(list(TOIpl["TOI"]))[1:-1] # ------ PARAMS ------ ra = float(target_ra) dec = float(target_dec) def addPageNumber(canvas, doc): """ Add the page numbers to the document """ width, height = A4 # this is useful when defining where to plot something on the page page_num = canvas.getPageNumber() text = "%s" % page_num header = "TIC {}".format(tic) canvas.setFont('Helvetica',8) canvas.drawString(width*0.85, height * 0.95, header) canvas.drawRightString(200*mm, 10*mm, text) #------------------------------------------------------------------ # Recall the names of all the plots that will be in the DV report #------------------------------------------------------------------ # plot the full light curve, with marked sectors and marked transit - binned and unbinned full_LC_name = "{}/{}/{}_fullLC_md.png".format(indir,tic,tic) full_LC_notransits_name = "{}/{}/{}_fullLC_md_notransits.png".format(indir,tic,tic) # only used in the 'asteroseismic only' version of LATTE background_flux_name = '{}/{}/{}_background.png'.format(indir, tic, tic) centroid_positions_name = '{}/{}/{}_centroids.png'.format(indir, tic, tic) flux_aperture_name= '{}/{}/{}_aperture_size.png'.format(indir, tic, tic) tess_stars_name = '{}/{}/{}_star_field.png'.format(indir, tic, tic) #SDSS_stars_name = '{}/{}/{}_SDSSstar_field.png'.format(indir, tic, tic) nearest_neighbour_name = '{}/{}/{}_nearest_neighbours.png'.format(indir, tic, tic) pixel_LCs_name = '{}/{}/{}_individual_pixel_LCs_0.png'.format(indir, tic,tic) bls1 = '{}/{}/{}_bls_first.png'.format(indir, tic, tic) bls2 = '{}/{}/{}_bls_second.png'.format(indir, tic, tic) in_out_name = '{}/{}/{}_flux_comparison.png'.format(indir, tic, tic) model_name = '{}/{}/model_out/{}b_tr.png'.format(indir, tic, tic) phasefold_name = '{}/{}/{}_phase_folded.png'.format(indir, tic, tic) apertures_name = '{}/{}/{}_apertures_0.png'.format(indir, tic, tic) periodogram_name = '{}/{}/{}_periodogram.png'.format(indir, tic, tic) periodogram_numax_name = '{}/{}/{}_diagnostic_numax.png'.format(indir, tic, tic) periodogram_correlation_name = '{}/{}/{}_scaled_correlation.png'.format(indir, tic, tic) periodogram_echelle_name = '{}/{}/{}_echelle.png'.format(indir, tic, tic) eep_name = '{}/{}/{}_eep.png'.format(indir, tic, tic) # ----- LOGOS ------ # if this is a unittest run, find the files for the logos stored in the test folder if test != 'no': PHT_logo_name = '{}/LATTE_imgs/PHT_logo.jpg'.format(test) LATTE_logo_name = '{}/LATTE_imgs/LATTE_logo.png'.format(test) TESS_logo_name = '{}/LATTE_imgs/TESS_logo.png'.format(test) # otherwise they're located in the place where the program is insatlled. else: PHT_logo_name = '{}/LATTE_imgs/PHT_logo.jpg'.format(syspath) LATTE_logo_name = '{}/LATTE_imgs/LATTE_logo.png'.format(syspath) TESS_logo_name = '{}/LATTE_imgs/TESS_logo.png'.format(syspath) # ------------------------------------------- # Make a PDF summary file # ------------------------------------------- doc = SimpleDocTemplate("{}/{}/DV_report_{}.pdf".format(indir,tic,tic) ,pagesize=A4, rightMargin=72,leftMargin=72, topMargin=30,bottomMargin=20) width, height = A4 # this is useful when defining where to plot something on the page Story=[] fig_count = 0 table_count = 0 # title title = "PHT Data Validation Report" subheading = "TIC {}".format(tic) styles=getSampleStyleSheet() styles.add(ParagraphStyle(name='centre', alignment=TA_CENTER)) ptext = '<font size=12><b>%s</b></font>' % title subtext = '<font size=12><b>%s</b></font>' % subheading Story.append(Paragraph(ptext, styles["centre"])) Story.append(Paragraph(subtext, styles["centre"])) Story.append(Spacer(1, 25)) # ----- ADD THE LOGOS ------- PHT_logo = Image(PHT_logo_name) PHT_logo.drawHeight = 0.5*inch*PHT_logo.drawHeight / PHT_logo.drawWidth PHT_logo.drawWidth = 0.5*inch LATTE_logo = Image(LATTE_logo_name) LATTE_logo.drawHeight = 0.5*inch*LATTE_logo.drawHeight / LATTE_logo.drawWidth LATTE_logo.drawWidth = 0.5*inch TESS_logo = Image(TESS_logo_name) TESS_logo.drawHeight = 0.8*inch*TESS_logo.drawHeight / TESS_logo.drawWidth TESS_logo.drawWidth = 0.8*inch logo_table = (Table([[PHT_logo, LATTE_logo, TESS_logo]], colWidths=[width * 0.1], rowHeights=[1 * mm])) logo_table.setStyle(TableStyle([('ALIGN', (0, 0), (-1, -1), 'CENTRE'),('VALIGN', (0, 0), (-1,-1), 'MIDDLE')])) Story.append(logo_table) Story.append(Spacer(1, 30)) # ---------------------------- line = MCLine(width*0.77) Story.append(line) Story.append(Spacer(1, 2)) line = MCLine_color(width*0.77) Story.append(line) Story.append(Spacer(1, 20)) if len(transit_list) == 0: # if in asteroseismic mode # -------------------------------------------- # Full Image with momentum dumps - asterseismic mode # -------------------------------------------- im = Image(full_LC_notransits_name) im._restrictSize(width*0.76, width*0.76) Story.append(im) fig_count += 1 full_image_text = "Fig {}. Full lightcurve for target TIC {}. The solid blue lines at the bottom of the figure indicated the \ times of the reaction wheel momentum dumps, which \ occur around every 2 to 2.5 days and typically last around half an hour.".format(fig_count,tic) ptext = '<font size=8>%s</font>' % full_image_text Story.append(Paragraph(ptext, styles["Normal"])) else: # -------------------------------------------- # Full Image with momentum dumps # -------------------------------------------- im = Image(full_LC_name) im._restrictSize(width*0.76, width*0.76) Story.append(im) fig_count += 1 full_image_text = "Fig {}. Full lightcurve for target TIC {}. The solid blue lines at the bottom of the figure indicated the \ times of the reaction wheel momentum dumps and the dashed black line(s) show the time(s) of the marked transit event(s). Momentum dumps \ occur around every 2 to 2.5 days and typically last around half an hour.".format(fig_count,tic) ptext = '<font size=8>%s</font>' % full_image_text Story.append(Paragraph(ptext, styles["Normal"])) # -------------------------------------- # ------ stellar parameters table ------ # -------------------------------------- try: srad = np.round(srad, 2) except: srad = '--' try: teff = np.round(teff, 0) except: teff = '--' try: mstar = np.round(mstar, 2) except: mstar = '--' try: plx = np.round(plx, 2) except: plx = '--' try: vmag = np.round(vmag, 2) except: vmag = '--' nominal_mission_sectors = list(np.array(sectors_all)[np.array(sectors_all) < 27]) extended_mission_sectors = list(np.array(sectors_all)[np.array(sectors_all) > 26]) # mstar, vmag, logg, plx, c_id if mass_ast == -999: # classic mode (no asteroseismology) #mass_ast, radius_ast, logg_ast data_stellar= [['Parameter', "Value", "Unit"], ['TIC ID', tic, ], ['Other name', c_id, ], ['RA/Dec', "{} {}".format(round(ra,5), round(dec,5)), "degrees"], ['Radius', "{}".format(srad), "Solar Radii"], ['Mass', "{}".format(mstar), "Solar Mass"], ['Teff', "{}".format(teff), "Kelvin"], ['Parallax', "{}".format(plx), " "], ['T mag', "{}".format(tessmag), "Mag"], ['V mag', "{}".format(vmag), "Mag"], ['Sectors (nominal)', "{} *".format(str(nominal_mission_sectors)[1:-1]),], ['Sectors (extended)', "{} *".format(str(extended_mission_sectors)[1:-1]),], ['TCE', TCE, ], ['TOI', "{}".format(str(TOI)), ], ] table_stellar=Table(data_stellar) table_stellar=Table(data_stellar,colWidths=width * 0.24, style=[ ('LINEABOVE',(0,1),(-1,1),1,colors.black), ('LINEABOVE',(0,14),(-1,14),1,colors.black), ('FONTSIZE', (0,0),(-1,13), 8), ]) else: #mass_ast, radius_ast, logg_ast data_stellar= [['Parameter', "Value", "Seismic", "Unit"], ['TIC ID', tic, " " ], ['Other name', c_id, ], ['RA/Dec', "{} {}".format(round(ra,5), round(dec,5)), " " , "degrees"], ['Teff', "{}".format(teff)," ", "Kelvin"], ['Radius', "{}".format(srad), "{}".format(round(radius_ast,3)), "Solar Radii"], ['Mass', "{}".format(mstar),"{}".format(round(mass_ast,3)) , "Solar Mass"], ['logg', "{}".format(logg),"{}".format(round(logg_ast,3)) , "Solar Mass"], ['numax', " ","{}".format(round(numax,3)) , "uHz"], ['Delta nu'," ","{}".format(round(deltanu,3)) , "uHz"], ['Parallax', "{}".format(plx)," ", " "], ['T mag', "{}".format(tessmag)," ", "Mag"], ['V mag', "{}".format(vmag), " ", "Mag"], ['Sectors (nominal)', "{} *".format(str(nominal_mission_sectors)[1:-1]),], ['Sectors (extended)', "{} *".format(str(extended_mission_sectors)[1:-1]),], ['TCE', TCE, " "," " ], ['TOI', "{}".format(str(TOI))," " , " "], ] table_stellar=Table(data_stellar) table_stellar=Table(data_stellar,colWidths=width * 0.18, rowHeights = 5*mm, style=[ ('ALIGN', (0,0), (-1,16), "LEFT"), ('VALIGN', (0,0), (-1,16), "MIDDLE"), ('LINEABOVE',(0,1),(-1,1),1,colors.black), ('LINEABOVE',(0,17),(-1,17),1,colors.black), ('FONTSIZE', (0,0),(-1,16), 6), ]) data_len = len(data_stellar) for each in range(data_len): if each % 2 == 0: bg_color = colors.whitesmoke else: bg_color = colors.white table_stellar.setStyle(TableStyle([('BACKGROUND', (0, each), (-1, each), bg_color)])) # ------ ADD A LINE TO SEPERATE SECTIONS ----- Story.append(Spacer(1, 20)) line = MCLine(width*0.77) Story.append(line) # ------ Story.append(Spacer(1, 20)) #ptext = '<font size=9>Target Properties</font>' #Story.append(Paragraph(ptext, styles["Normal"])) #Story.append(Spacer(1, 12)) Story.append(table_stellar) Story.append(Spacer(1, 15)) table_count += 1 exofop_url = "https://exofop.ipac.caltech.edu/tess/target.php?id={}".format(tic) exofop_link = '<link href="%s" color="blue">TIC %s</link>' % (exofop_url, tic) if TCE == 'Yes **': Stellartable_text = "Table {}. Stellar properties of {}. \ * List of the sectors in which the target will be, or has been, \ observed. ** Click {} for the TCE report.".format(table_count, exofop_link, TCE_link) else: Stellartable_text = "Table {}. Stellar properties of the {}. \ * List of the sectors in which the target will be, or has been, \ observed.".format(table_count,exofop_link) ptext = '<font size=8>%s</font>' % Stellartable_text Story.append(Paragraph(ptext, styles["Normal"])) if len(transit_list) != 0: # normal mode # -------------------------------------------- # Background # -------------------------------------------- if (FFI != False): Story.append(PageBreak()) # always start a new page for this analysis Story.append(Spacer(1, 20)) im2 = Image(background_flux_name) if len(transit_list) == 1: im2._restrictSize(width*0.55, width*0.55) else: im2._restrictSize(width*0.8, width*0.8) Story.append(im2) fig_count += 1 Story.append(Spacer(1, 1)) background_text = "Fig {}. Background flux vs. time around the time of each transit-like event. \ The vertical orange line indicates the time of the transit-like event.".format(fig_count) ptext = '<font size=8>%s</font>' % background_text Story.append(Paragraph(ptext, styles["Normal"])) # -------------------------------------------- # Centroid Position # -------------------------------------------- if (FFI == False) or (FFI == 'SPOC'): Story.append(Spacer(1, 16)) im3 = Image(centroid_positions_name) if len(transit_list) == 1: im3._restrictSize(width*0.52, width*0.52) else: im3._restrictSize(width*0.7, width*0.7) Story.append(im3) fig_count += 1 centroid_text = "Fig {}. The x and y centroid positions around the time of each transit-like event. The black points shows the CCD column and row position of the target’s flux-weighted centroid. \ The red shows the CCD column and row local motion differential velocity aberration (DVA), pointing drift, and thermal effects. \ The vertical orange line indicates the time of the transit-like event".format(fig_count) ptext = '<font size=8>%s</font>' % centroid_text Story.append(Spacer(1, 5)) Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 16)) #Story.append(PageBreak()) # always start a new page for this analysis # the following plots will only exist if the TPF file is not corrupt - otherwise skip these. if tpf_corrupt == False: # -------------------------------------------- # Flux Aperture # -------------------------------------------- if (FFI == False) or (FFI == 'SPOC'): #Story.append(PageBreak()) # always start a new page for this analysis Story.append(Spacer(1, 10)) im4 = Image(flux_aperture_name) if len(transit_list) == 1: im4._restrictSize(width*0.55, width*0.55) else: im4._restrictSize(width*0.7, width*0.7) Story.append(im4) fig_count += 1 Story.append(Spacer(1, 16)) flux_aperture_text = "Fig {}. The lightcurve around the time of each transit-like event extracted with the SPOC pipeline \ defined aperture (binned:blue, unbinned:grey) and the with an aperture that is 40 per cent smaller (red). The flux is extracted \ from the target pixel files (TPFs) and has not been detrended or \ corrected for systematics. The vertical orange line indicates the time of the transit-like event.".format(fig_count) ptext = '<font size=8>%s</font>' % flux_aperture_text Story.append(Paragraph(ptext, styles["Normal"])) # -------------------------------------------- # Apertures Sizes # -------------------------------------------- if (FFI == False) or (FFI == 'SPOC'): Story.append(Spacer(1, 25)) im45 = Image(apertures_name) im45._restrictSize(width*0.4, width*0.4) Story.append(im45) fig_count += 1 Story.append(Spacer(1, 16)) if FFI == False: aperture_text = "Fig {}. The apertures used to extract the lightcurves. The blue aperture on the right shows the \ optimum aperture determined by the SPOC pipeline, which is used for the extraction of 2-minute cadence light curves shown in Figure 1. \ The red outline on the left shows an aperture that is around 40 per cent smaller than the SPOC pipeline aperture which was used to extract the \ red lightcurve shown in Figure {}.".format(fig_count, (fig_count-1)) else: aperture_text = "Fig {}. The larger (right hand side, blue) and the smaller (left hamd side, red) apertures used to extract the lightcurves shown in Figure {}.".format(fig_count, (fig_count-1)) ptext = '<font size=8>%s</font>' % aperture_text Story.append(Paragraph(ptext, styles["Normal"])) # -------------------------------------------- # In and Out of Transit Comparison # -------------------------------------------- Story.append(Spacer(1, 25)) im5 = Image(in_out_name) im5._restrictSize(width*0.85, width*0.85) Story.append(im5) fig_count += 1 Story.append(Spacer(1, 16)) flux_aperture_text = "Fig {}. Difference images for target TIC {} for each transit like event. \ Left: mean in-transit flux(left). Middle: mean out-of-transit flux. Right: difference between the mean out-of-transit and mean in-transit flux. \ Ensure that the change in brightness occurs on target.".format(fig_count, tic) ptext = '<font size=8>%s</font>' % flux_aperture_text Story.append(Paragraph(ptext, styles["Normal"])) # -------------------------------------------- # tess stars + SDSS star field # -------------------------------------------- # can only put this in the report if astroquery is working. if astroquery_corrupt == False: if FFI == False: Story.append(PageBreak()) # always start a new page for this analysis Story.append(Spacer(1, 20)) im6 = Image(tess_stars_name) # if not with mpi (two star images) if mpi == False: im6._restrictSize(width*0.7, width*0.5) else: im6._restrictSize(width*0.35, width*0.35) Story.append(im6) fig_count += 1 tess_stars_text = "Fig {}. The locations of nearby GAIA DR2 stars with a magnitude difference less than 5 (orange circle) within the Tess \ Cut Out around TIC {} (red star). Only shown for one sector. Right: SDSS image of the surrounding field.".format(fig_count, tic) ptext = '<font size=8>%s</font>' % tess_stars_text Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 30)) # -------------------------------------------- # nearest neighbours # -------------------------------------------- #Story.append(PageBreak()) # always start a new page for this analysis if (FFI == False): im7 = Image(nearest_neighbour_name) im7._restrictSize(width*0.8, width*0.8) Story.append(im7) fig_count += 1 Story.append(Spacer(1, 10)) nn_text = "Fig {}. Lightcurves of the five closest stars to target {} (top pannel). \ The distances to the target star and the TESS magnitudes are shown for each star. Only ever shown for one sector.".format(fig_count,tic) ptext = '<font size=8>%s</font>' % nn_text Story.append(Paragraph(ptext, styles["Normal"])) # this plot also only exists if the TPF downloaded sucessfully if tpf_corrupt == False: # -------------------------------------------- # pixel_LCs_name # -------------------------------------------- Story.append(PageBreak()) # always start a new page for this analysis Story.append(Spacer(1, 20)) im8 = Image(pixel_LCs_name) im8._restrictSize(width*0.65, width*0.65) Story.append(im8) fig_count += 1 pixLC_text = "Fig {}. Normalised flux extracted for each pixel, using the SPOC pipeline mask, around the time of the transit-like event. \ The orange/red data points show the in-transit data. The solid red lines show the SPOC pipeline mask. Only shown for one sector.".format(fig_count) ptext = '<font size=8>%s</font>' % pixLC_text Story.append(Paragraph(ptext, styles["Normal"])) # ------ Phase Folded LC ------ if len(transit_list) > 1: # -------------------------------------------- # Phase Folded # -------------------------------------------- impf = Image(phasefold_name) impf._restrictSize(width*0.35, width*0.35) Story.append(impf) fig_count += 1 Story.append(Spacer(1, 10)) flux_aperture_text = "Fig {}. Phase folded lightcurve where the odd and the even transits are shown in different colours. Ensure that the odd and even transits have comparabel shapes and depths.".format(fig_count) ptext = '<font size=8>%s</font>' % flux_aperture_text Story.append(Paragraph(ptext, styles["Normal"])) # ------ BLS ------- if bls == True: if len(bls_stats2) > 1: # if the first AND second BLS worked Story.append(PageBreak()) # always start a new page for this analysis Story.append(Spacer(1, 12)) blsim1 = Image(bls1) blsim2 = Image(bls2) blsim1._restrictSize(width*0.6, width*0.6) blsim2._restrictSize(width*0.6, width*0.6) bls_table = (Table([[blsim1, blsim2]], colWidths=[width * 0.45], rowHeights=[width * 0.6])) bls_table.setStyle(TableStyle([('ALIGN', (0, 0), (-1, -1), 'CENTRE'),('VALIGN', (0, 0), (-1,-1), 'MIDDLE')])) Story.append(bls_table) fig_count += 1 if FFI == False: bls1_text = "Fig {}. Box Least Square fitting (BLS) for whole lightcurve binned to 10 minutes. Top left panel: log liklihood periodogram. \ The solid red line indicates the peak period and the dashed orange lines show the integer \ harmonics of this period. Middle left panel: Full light curve, unbinned (orange) and binned to 10 minutes (black). \ The peak period is highlighted by the solid red lines. Bottom left Panel: Phase folded light curve where the found transit-event is fit \ with a simple box (red line). The pannels on the right show the same diagnostics, however the diagnostic \ was run with the highest detected signal-to-noise transits, from the initial BLS search, removed. ".format(fig_count) else: bls1_text = "Fig {}. Box Least Square fitting (BLS) for whole lightcurve. Top left panel: log liklihood periodogram. \ The solid blue line indicates the peak period and the dashed red lines show the integer \ harmonics of this period. Middle left panel: Full light curve, unbinned LC (orange) . \ The peak period is highlighted by the solid blue lines. Bottom left Panel: Phase folded light curve where the found transit-event is fit \ with a simple box (blue line). The pannels on the right show the same diagnostics, however the diagnostic \ was run with the highest detected signal-to-noise transits, from the initial BLS search, removed. ".format(fig_count) ptext = '<font size=8>%s</font>' % bls1_text Story.append(Paragraph(ptext, styles["Normal"])) # -------------------- # ---- BLS TABLE ----- data_bls= [['Parameter', "bls1", "bls2"], ['period', "{:.3f}".format(bls_stats1[0]), "{:.3f}".format(bls_stats2[0])], ['t0', "{:.2f}".format(bls_stats1[1]), "{:.2f}".format(bls_stats2[1])], ['depth', "{:.5f} ± {:.5f}".format(bls_stats1[2][0],bls_stats1[2][1]), "{:.5f} ± {:.5f}".format(bls_stats2[2][0],bls_stats2[2][1]) ], ['depth phased', "{:.5f} ± {:.5f}".format(bls_stats1[3][0],bls_stats1[3][1]), "{:.5f} ± {:.5f}".format(bls_stats2[3][0],bls_stats2[3][1]) ], ['depth half', "{:.5f} ± {:.5f}".format(bls_stats1[4][0],bls_stats1[4][1]), "{:.5f} ± {:.5f}".format(bls_stats2[4][0],bls_stats2[4][1]) ], ['depth odd', "{:.5f} ± {:.5f}".format(bls_stats1[5][0],bls_stats1[5][1]), "{:.5f} ± {:.5f}".format(bls_stats2[5][0],bls_stats2[5][1]) ], ['depth even', "{:.5f} ± {:.5f}".format(bls_stats1[6][0],bls_stats1[6][1]), "{:.5f} ± {:.5f}".format(bls_stats2[6][0],bls_stats2[6][1]) ], ] table_bls=Table(data_bls) table_bls=Table(data_bls,colWidths=width * 0.2, style=[ ('LINEABOVE',(0,1),(-1,1),1,colors.black), ('LINEABOVE',(0,8),(-1,8),1,colors.black), ('FONTSIZE', (0,0),(-1,7), 8), ]) else: # if the first BLS returned a period that was very short such that the second one didn't work. Story.append(PageBreak()) # always start a new page for this analysis Story.append(Spacer(1, 12)) blsim1 = Image(bls1) #blsim2 = Image(bls2) blsim1._restrictSize(width*0.6, width*0.6) Story.append(blsim1) fig_count += 1 if FFI == False: bls1_text = "Fig {}. Box Least Square fitting (BLS) for whole lightcurve binned to 10 minutes. Top panel: log liklihood periodogram. \ The solid red line indicates the peak period and the dashed orange lines show the integer \ harmonics of this period. Middle panel: Full light curve, unbinned (orange) and binned to 10 minutes (black). \ The peak period is highlighted by the solid red lines. Bottom panel: Phase folded light curve where the found transit-event is fit \ with a simple box (red line). ".format(fig_count) else: bls1_text = "Fig {}. Box Least Square fitting (BLS) for whole lightcurve. Top panel: log liklihood periodogram. \ The solid blue line indicates the peak period and the dashed red lines show the integer \ harmonics of this period. Middle panel: Full light curve, unbinned LC (orange) . \ The peak period is highlighted by the solid blue lines. Bottom panel: Phase folded light curve where the found transit-event is fit \ with a simple box (blue line). ".format(fig_count) ptext = '<font size=8>%s</font>' % bls1_text Story.append(Paragraph(ptext, styles["Normal"])) # -------------------- # ---- BLS TABLE ----- data_bls= [['Parameter', "bls1" ], ['period', "{:.3f}".format(bls_stats1[0]) ], ['t0', "{:.2f}".format(bls_stats1[1]) ], ['depth', "{:.5f} ± {:.5f}".format(bls_stats1[2][0],bls_stats1[2][1]) ], ['depth phased', "{:.5f} ± {:.5f}".format(bls_stats1[3][0],bls_stats1[3][1]) ], ['depth half', "{:.5f} ± {:.5f}".format(bls_stats1[4][0],bls_stats1[4][1]) ], ['depth odd', "{:.5f} ± {:.5f}".format(bls_stats1[5][0],bls_stats1[5][1]) ], ['depth even', "{:.5f} ± {:.5f}".format(bls_stats1[6][0],bls_stats1[6][1]) ], ] table_bls=Table(data_bls) table_bls=Table(data_bls,colWidths=width * 0.25, style=[ ('LINEABOVE',(0,1),(-1,1),1,colors.black), ('LINEABOVE',(0,8),(-1,8),1,colors.black), ('FONTSIZE', (0,0),(-1,7), 8), ]) # ------ ADD A LINE TO SEPERATE SECTIONS ------- Story.append(Spacer(1, 20)) line = MCLine(width*0.77) Story.append(line) # ------ Story.append(Spacer(1, 16)) ptext = '<font size=10>BLS parameters</font>' Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 15)) data_len = len(data_bls) for each in range(data_len): if each % 2 == 0: bg_color = colors.whitesmoke else: bg_color = colors.white table_bls.setStyle(TableStyle([('BACKGROUND', (0, each), (-1, each), bg_color)])) Story.append(table_bls) Story.append(Spacer(1, 15)) table_count += 1 Stellartable_text = "Table {}. Summary of the BLS fit.".format(table_count) ptext = '<font size=8>%s</font>' % Stellartable_text Story.append(Paragraph(ptext, styles["Normal"])) Story.append(PageBreak()) # ----------- # analysis of the star i.e. periodogram and the evolutionary tracks #periodogram_name # -------------------------------------------- # Periodogram # -------------------------------------------- Story.append(Spacer(1, 20)) imp = Image(periodogram_name) imp._restrictSize(width*0.55, width*0.55) Story.append(imp) fig_count += 1 Story.append(Spacer(1, 10)) periodogram_text = "Fig {}. Lomb scargle power spectrum of the TESS lightcurve (black line) and a boxcar-smoothed periogram (pink line) computed with a window length of 20 micro Hz.".format(fig_count) ptext = '<font size=8>%s</font>' % periodogram_text Story.append(Paragraph(ptext, styles["Normal"])) if radius_ast != -999: # this is asteroseismic mode: # -------------------------------------------- # astersoseismology periodogram nummax # -------------------------------------------- Story.append(Spacer(1, 20)) imast = Image(periodogram_numax_name) imast._restrictSize(width*0.6, width*0.6) Story.append(imast) fig_count += 1 Story.append(Spacer(1, 10)) astero_text = "Fig {}. Top panel: power spectrum with the ".format(fig_count) astrtext = '<font size=8>%s</font>' % astero_text Story.append(Paragraph(astrtext, styles["Normal"])) # -------------------------------------------- # astersoseismology periodogram correlation # -------------------------------------------- Story.append(Spacer(1, 20)) imastcorr = Image(periodogram_correlation_name) imastcorr._restrictSize(width*0.55, width*0.55) Story.append(imastcorr) fig_count += 1 Story.append(Spacer(1, 10)) asterocorr_text = "Fig {}. ".format(fig_count) astcortext = '<font size=8>%s</font>' % asterocorr_text Story.append(Paragraph(astcortext, styles["Normal"])) # -------------------------------------------- # astersoseismology periodogram echelle # -------------------------------------------- Story.append(Spacer(1, 20)) imechcorr = Image(periodogram_echelle_name) imechcorr._restrictSize(width*0.55, width*0.55) Story.append(imechcorr) fig_count += 1 Story.append(Spacer(1, 10)) echellecorr_text = "Fig {}. Echelle diragram.".format(fig_count) echelletext = '<font size=8>%s</font>' % echellecorr_text Story.append(Paragraph(echelletext, styles["Normal"])) # -------------------------------------------- # eep # -------------------------------------------- Story.append(Spacer(1, 20)) imp = Image(eep_name) imp._restrictSize(width*0.55, width*0.55) Story.append(imp) fig_count += 1 Story.append(Spacer(1, 10)) periodogram_text = "Fig {}. The equivalent evolutionary phase (eep) tracks for main sequence evolution (solid lines) and post \ main-sequence evolution (dashed lines) for masses ranging from 0.3 to 1.6 solar masses (from right to left). \ The 1 Solar Mass track is shown in maroon. The blue points show the TOIs and the magenta point TIC {}.".format(fig_count, tic) ptext = '<font size=8>%s</font>' % periodogram_text Story.append(Paragraph(ptext, styles["Normal"])) if model == True: #Story.append(PageBreak()) # always start a new page for this analysis pyaneti_url = 'https://academic.oup.com/mnras/article/482/1/1017/5094600' pyaneti_link = '<link href="%s" color="blue">Pyaneti</link>' % pyaneti_url model_title = "Modeling" model_text = "The modeling of target TIC {} using the open source {} package.".format(tic, pyaneti_link) ptext = '<font size=11><b>%s</b></font>' % model_title Story.append(Paragraph(ptext, styles["centre"])) Story.append(Spacer(1, 10)) ptext = '<font size=11>%s</font>' % model_text Story.append(Paragraph(ptext, styles["centre"])) Story.append(Spacer(1, 15)) line = MCLine(width*0.77) Story.append(line) # -------------------------------------------- # Pyaneti Modeling results # -------------------------------------------- Story.append(Spacer(1, 12)) im_model = Image(model_name) im_model._restrictSize(width*0.5, width*0.5) Story.append(im_model) fig_count += 1 model_text = "Fig {}. The phase folded lightcurve from the the Pyaneti modeling. The solid black line shows the best fit model. See Table 2 for model parameters.".format(fig_count) ptext = '<font size=8>%s</font>' % model_text Story.append(Paragraph(ptext, styles["Normal"])) # --------------- # pyaneti modeling table # ---------------------------------------------- # print a table of the model/pyaneti parameters # ---------------------------------------------- # this can only be done if the pyaneti model has been run # as this takes quite a while this might not always be the case. if os.path.exists("{}/{}/model_out/{}_parameters.csv".format(indir, tic, tic)): Story.append(Spacer(1, 12)) line = MCLine(width*0.77) Story.append(line) Story.append(Spacer(1, 12)) ptext = '<font size=10>Candidate Model Parameters</font>' Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 8)) manifest_table = pd.read_csv('{}/{}/model_out/{}_parameters.csv'.format(indir, tic, tic)) #manifest_table params = ['T0', 'P', 'e', 'w', 'b', 'a/R*', 'rp/R*', 'Rp', 'Tperi', 'i', 'a', 'Insolation', 'rho*', 'g_p', 'Teq', 'T_tot', 'T_full'] elements = [] param_vals = [] param_errs = [] param_units= [] for st in params: try: s = (manifest_table[manifest_table['Var']==st]) param_vals.append("{:.3f}".format(s['Val'].values[0] )) param_errs.append("+{:.4f} -{:.4f}".format(s['Pos'].values[0], s['Neg'].values[0])) param_units.append("{}".format(s['Unit'].values[0] )) except: param_vals.append(-999) param_errs.append(-999) param_units.append(-999) data_params = [['Parameters', 'Value', 'Uncertainty', 'Unit']] for p,v,e,u in zip(params, param_vals, param_errs, param_units): data_params.append([p,v,e,u]) table_model=Table(data_params) table_model=Table(data_params,colWidths=width * 0.2, style=[ ('LINEABOVE',(0,1),(-1,1),1,colors.black), ('LINEABOVE',(0,8),(-1,8),1,colors.black), ('LINEABOVE',(0,len(params)+1),(-1,len(params)+1),1,colors.black), ('FONTSIZE', (0,0),(-1,len(params)), 8), ]) data_len = len(data_params) for each in range(data_len): if each % 2 == 0: bg_color = colors.whitesmoke else: bg_color = colors.white table_model.setStyle(TableStyle([('BACKGROUND', (0, each), (-1, each), bg_color)])) Story.append(table_model) table_count += 1 Story.append(Spacer(1, 10)) Stellartable_text = "Table {}. The candidate paramaters from the Pyaneti modeling.".format(table_count) ptext = '<font size=8>%s</font>' % Stellartable_text Story.append(Paragraph(ptext, styles["Normal"])) doc.build(Story, onFirstPage=addPageNumber, onLaterPages=addPageNumber)
def generate_roster_pdf(sched_act_ids, include_instructions): r"""Generates a PDF roster for one or more. :class:`EighthScheduledActivity`\s. Args sched_act_ids The list of IDs of the scheduled activities to show in the PDF. include_instructions Whether instructions should be printed at the bottom of the roster(s). Returns a BytesIO object for the PDF. """ pdf_buffer = BytesIO() h_margin = 1 * inch v_margin = 0.5 * inch doc = SimpleDocTemplate(pdf_buffer, pagesize=letter, rightMargin=h_margin, leftMargin=h_margin, topMargin=v_margin, bottomMargin=v_margin) elements = [] styles = getSampleStyleSheet() styles.add(ParagraphStyle(name="Center", alignment=TA_CENTER)) styles.add( ParagraphStyle(name="BlockLetter", fontSize=60, leading=72, alignment=TA_CENTER)) styles.add( ParagraphStyle(name="BlockLetterSmall", fontSize=30, leading=72, alignment=TA_CENTER)) styles.add( ParagraphStyle(name="BlockLetterSmallest", fontSize=20, leading=72, alignment=TA_CENTER)) styles.add( ParagraphStyle(name="ActivityAttribute", fontSize=15, leading=18, alignment=TA_RIGHT)) for i, said in enumerate(sched_act_ids): sact = EighthScheduledActivity.objects.get(id=said) sponsor_names = sact.get_true_sponsors().values_list( "first_name", "last_name") sponsors_str = "; ".join(l + ", " + f for f, l in sponsor_names) room_names = sact.get_true_rooms().values_list("name", flat=True) if len(room_names) == 1: rooms_str = "Room " + room_names[0] else: rooms_str = "Rooms: " + ", ".join(r for r in room_names) block_letter = sact.block.block_letter if len(block_letter) < 4: block_letter_width = 1 * inch block_letter_width += (0.5 * inch) * (len(block_letter) - 1) block_letter_style = "BlockLetter" elif len(block_letter) < 7: block_letter_width = 0.4 * inch block_letter_width += (0.3 * inch) * (len(block_letter) - 1) block_letter_style = "BlockLetterSmall" else: block_letter_width = 0.3 * inch block_letter_width += (0.2 * inch) * (len(block_letter) - 1) block_letter_style = "BlockLetterSmallest" header_data = [[ Paragraph( "<b>Activity ID: {}<br />Scheduled ID: {}</b>".format( sact.activity.id, sact.id), styles["Normal"]), Paragraph( "{}<br/>{}<br/>{}".format( sponsors_str, rooms_str, sact.block.date.strftime("%A, %B %-d, %Y")), styles["ActivityAttribute"]), Paragraph(block_letter, styles[block_letter_style]) ]] header_style = TableStyle([("VALIGN", (0, 0), (0, 0), "TOP"), ("VALIGN", (1, 0), (2, 0), "MIDDLE"), ("TOPPADDING", (0, 0), (0, 0), 15), ("RIGHTPADDING", (1, 0), (1, 0), 0)]) elements.append( Table(header_data, style=header_style, colWidths=[2 * inch, None, block_letter_width])) elements.append(Spacer(0, 10)) elements.append(Paragraph(sact.full_title, styles["Title"])) num_members = sact.members.count() num_members_label = "{} Student{}".format( num_members, "s" if num_members != 1 else "") elements.append(Paragraph(num_members_label, styles["Center"])) elements.append(Spacer(0, 5)) attendance_data = [[ Paragraph("Present", styles["Heading5"]), Paragraph("Student Name (ID)", styles["Heading5"]), Paragraph("Grade", styles["Heading5"]) ]] members = [] for member in sact.members.all(): members.append( (member.last_name + ", " + member.first_name, (member.student_id if member.student_id else "User {}".format( member.id)), int(member.grade) if member.grade else "?")) members = sorted(members) for member_name, member_id, member_grade in members: row = ["", "{} ({})".format(member_name, member_id), member_grade] attendance_data.append(row) # Line commands are like this: # op, start, stop, weight, colour, cap, dashes, join, linecount, linespacing attendance_style = TableStyle([ ("LINEABOVE", (0, 1), (2, 1), 1, colors.black, None, None, None, 2), ("LINEBELOW", (0, 1), (0, len(attendance_data)), 1, colors.black), ("TOPPADDING", (0, 1), (-1, -1), 6), ("BOTTOMPADDING", (0, 1), (-1, -1), 0), ("BOTTOMPADDING", (0, 0), (-1, 0), 5), ]) elements.append( Table(attendance_data, style=attendance_style, colWidths=[1.3 * inch, None, 0.8 * inch])) elements.append(Spacer(0, 15)) instructions = """ <b>Highlight or circle</b> the names of students who are <b>absent</b>, and put an <b>"X"</b> next to those <b>present</b>.<br /> If a student arrives and their name is not on the roster, please send them to the <b>8th Period Office</b>.<br /> If a student leaves your activity early, please make a note. <b>Do not make any additions to the roster.</b><br /> Before leaving for the day, return the roster and any passes to 8th Period coordinator, Catherine Forrester's mailbox in the <b>main office</b>. For questions, please call extension 5046 or 5078. Thank you!<br />""" elements.append(Paragraph(instructions, styles["Normal"])) if i != len(sched_act_ids) - 1: elements.append(PageBreak()) def first_page(canvas, _): canvas.setTitle("Eighth Activity Roster") canvas.setAuthor("Generated by Ion") doc.build(elements, onFirstPage=first_page) return pdf_buffer
from django.shortcuts import render from django.views.generic.base import View from django.http import HttpResponseRedirect, HttpResponse from django.core.urlresolvers import reverse from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User # from sales.models import Sale, SalesItem # from purchases.models import Purchase, PurchaseReturn # from accounts.models import Ledger, LedgerEntry from inventory.models import Category from dashboard.models import Canteen style = [('FONTNAME', (0, 0), (-1, -1), 'Helvetica')] sales_receipt_style = [('FONTNAME', (0, 0), (-1, -1), 'Helvetica')] para_style = ParagraphStyle('fancy') para_style.fontSize = 10.5 para_style.fontName = 'Helvetica' class Login(View): def get(self, request, *args, **kwargs): canteen_list = [] canteens = Canteen.objects.all() print(canteens) print("sss") for canteen in canteens: print(canteen) canteen_list.append(canteen.get_json_data()) res = { 'result': 'ok',
def export_sales_report(request): try: if request.method == 'POST': start_date = request.POST['from_date'] end_date = request.POST['to_date'] filter_args = {} smonth, sday, syear = start_date.split('/') emonth, eday, eyear = end_date.split('/') start_date = date(int(syear), int(smonth), int(sday)) end_date = date(int(eyear), int(emonth), int(eday)) filter_args['ordered_date__range'] = (datetime.combine( start_date, time.min), datetime.combine(end_date, time.max)) daterange = 'From ' + start_date.strftime( '%b %d, %Y') + ' to ' + end_date.strftime('%b %d, %Y') dataset = Order.objects.filter(**filter_args) if not dataset.exists(): messages.error(request, 'No Data Found') return redirect('report:sales_report') if 'xls_export' in request.POST: response = HttpResponse(content_type='application/ms-excel') response[ 'Content-Disposition'] = 'attachment; filename="Sales Report.xls"' wb = xlwt.Workbook(encoding='utf-8', style_compression=2) ws = wb.add_sheet('sales_report') row_num = 4 font_style = xlwt.XFStyle() common = "font:name Calibri, bold on, height 200; align:wrap yes, horiz center, vert center ;" common1 = "align: wrap yes, horiz right, vert center ;" columns = [ 'SL', 'Product', 'Brand', 'Category', 'Size', 'Unit Price', 'Quantity', 'Customer Name', 'Customer Phone', 'Shipping Address', 'Order Date', 'Discount Rate', 'Total Price' ] ws.write_merge(0, 1, 0, 5, 'Sales Report', xlwt.easyxf(common)) ws.write_merge(2, 3, 0, 5, daterange, xlwt.easyxf(common)) for col in range(len(columns)): ws.write(row_num, col, columns[col], font_style) total = 0.0 row_num += 1 for count, data in enumerate((dataset)): discount_rate = 0.0 if data.discount: discount_rate = data.discount.rate total += data.product.price ws.write(row_num, 0, count + 1, font_style) ws.write(row_num, 1, data.product.name, font_style) ws.write(row_num, 2, data.product.brand, font_style) ws.write(row_num, 3, data.product.category.name, font_style) ws.write(row_num, 4, data.product.size, font_style) ws.write(row_num, 5, str(data.product.price), font_style) ws.write(row_num, 6, str(data.quantity), font_style) ws.write(row_num, 7, data.customer.name, font_style) ws.write(row_num, 8, data.customer.phone, font_style) ws.write(row_num, 9, data.shipping_address, font_style) ws.write(row_num, 10, str(data.ordered_date), font_style) ws.write(row_num, 11, str(discount_rate), font_style) ws.write(row_num, 12, str(data.net_total), xlwt.easyxf(common1)) row_num += 1 ws.write(row_num, 11, "Total", font_style) ws.write(row_num, 12, str(total), xlwt.easyxf(common1)) wb.save(response) return response elif 'pdf_export' in request.POST: styles = getSampleStyleSheet() doc = SimpleDocTemplate( "assets/pdf_files/Sales Report.pdf", pagesize=reportlab.lib.pagesizes.landscape(letter)) parastyles = ParagraphStyle( 'header', parent=styles['Normal'], fontName='Helvetica-Bold', fontSize=8, alignment=TA_CENTER, textColor=colors.black, ) story = [] elements = [] columns = [] columns.insert(0, [ Paragraph('S/L', parastyles), Paragraph('Product', parastyles), Paragraph('Brand', parastyles), Paragraph('Category', parastyles), Paragraph('Size', parastyles), Paragraph('Unit Price', parastyles), Paragraph('Quantity', parastyles), Paragraph('Customer Name', parastyles), Paragraph('Customer Phone', parastyles), Paragraph('Shipping Address', parastyles), Paragraph('Order Date', parastyles), Paragraph('Discount Rate', parastyles), Paragraph('Total Price', parastyles) ]) texstyles = ParagraphStyle( 'text', parent=styles['Normal'], fontSize=8, alignment=TA_CENTER, textColor=colors.black, ) total = 0.0 j = 1 for count, data in enumerate((dataset)): discount_rate = 0.0 if data.discount: discount_rate = data.discount.rate total += data.product.price columns.insert(j, [ Paragraph(str(j), texstyles), Paragraph(str(data.product.name), texstyles), Paragraph(str(data.product.brand), texstyles), Paragraph(str(data.product.category.name), texstyles), Paragraph(str(data.product.size), texstyles), Paragraph(str(data.product.price), texstyles), Paragraph(str(data.quantity), texstyles), Paragraph(str(data.customer.name), texstyles), Paragraph(str(data.customer.phone), texstyles), Paragraph(str(data.shipping_address), texstyles), Paragraph(str(data.ordered_date), texstyles), Paragraph(str(discount_rate), texstyles), Paragraph(str(data.net_total), texstyles) ]) j = j + 1 columns.insert(j, [ Paragraph("", texstyles), Paragraph("", texstyles), Paragraph("", texstyles), Paragraph("", texstyles), Paragraph("", texstyles), Paragraph("", texstyles), Paragraph("", texstyles), Paragraph("", texstyles), Paragraph("", texstyles), Paragraph("", texstyles), Paragraph("", texstyles), Paragraph("Total", texstyles), Paragraph(str(total), texstyles) ]) t = Table(columns, repeatRows=1, splitByRow=1) t.setStyle( TableStyle([('FONTSIZE', (0, 0), (-1, -1), 1), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.gray), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP')])) dateofpdf = (datetime.now()).strftime("%d/%m/%Y") story.append(Paragraph("Sales Report", parastyles)) story.append(Spacer(1, 0.2 * inch)) story.append(Paragraph(daterange, parastyles)) story.append(Spacer(1, 0.2 * inch)) story.append( Paragraph("Printed Date: " + dateofpdf, styles['Normal'])) story.append(Spacer(1, 0.2 * inch)) story.append(Spacer(1, 0.2 * inch)) elements.append(t) story.append(t) doc.build(story, onFirstPage=myFirstPage, onLaterPages=myLaterPages) fs = FileSystemStorage() with fs.open("pdf_files/Sales Report.pdf") as pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "Sales Report.pdf" response[ 'Content-Disposition'] = 'attachment; filename="{}"'.format( filename) return response return response except Exception as ex: messages.error(request, str(ex)) mylog.exception('export_sales_report', exc_info=True) return redirect('report:sales_report')
def print_mass_pay(request, year): """ This function contains the required methods to create a PDF report. It will be merged with the salary app some time later. """ def sch(c): try: return c.permanent and c.permanent.organization_serving() except: return c.organization_serving() payment_codes = PaymentCode.objects.all() category_titles = PaymentCategoryTitle.objects.all() emp = Employee.objects.get(id=request.session['matched_employee_id']) try: emptype = Permanent.objects.get(parent_id=emp.id) except Permanent.DoesNotExist: try: emptype = NonPermanent.objects.get(parent_id=emp.id) except NonPermanent.DoesNotExist: try: emptype = Administrative.objects.get(parent_id=emp.id) except Administrative.DoesNotExist: emptype = 0 except: raise emp_payments = rprts_from_user(emp.id, year, '11,12,21') u = set([x['employee_id'] for x in emp_payments]) y = {x['employee_id']: x['year'] for x in emp_payments} dict_emp = { c.id: [ c.lastname, c.firstname, c.vat_number, c.fathername, c.address, c.tax_office, u'%s' % c.profession, u'%s' % c.profession.description, c.telephone_number1, sch(c) ] for c in Employee.objects.filter(id__in=u) } elements = [] reports = [] for empx in u: r_list = calc_reports( filter(lambda s: s['employee_id'] == empx, emp_payments)) hd = r_list[0] ft = [r_list[-2]] + [r_list[-1]] dt = r_list del dt[0] del dt[-2] del dt[-1] newlist = [] output = dict() for sublist in dt: try: output[sublist[0]] = map(operator.add, output[sublist[0]], sublist[1:]) except KeyError: output[sublist[0]] = sublist[1:] for key in output.keys(): newlist.append([key] + output[key]) newlist.sort(key=lambda x: x[0], reverse=True) r_list = [hd] + newlist + ft report = {} report['report_type'] = '1' report['type'] = '' report['year'] = y[empx] report['emp_type'] = 0 report['vat_number'] = dict_emp[empx][2] report['lastname'] = dict_emp[empx][0] report['firstname'] = dict_emp[empx][1] report['fathername'] = dict_emp[empx][3] report['address'] = dict_emp[empx][4] report['tax_office'] = dict_emp[empx][5] report['profession'] = ' '.join([dict_emp[empx][6], dict_emp[empx][7]]) report['telephone_number1'] = dict_emp[empx][8] report['rank'] = None report['net_amount1'] = '' report['net_amount2'] = '' report['organization_serving'] = dict_emp[empx][9] report['payment_categories'] = r_list reports.append(report) response = HttpResponse(mimetype='application/pdf') response[ 'Content-Disposition'] = 'attachment; filename=pay_report_%s.pdf' % year registerFont( TTFont('DroidSans', os.path.join(settings.MEDIA_ROOT, 'DroidSans.ttf'))) registerFont( TTFont('DroidSans-Bold', os.path.join(settings.MEDIA_ROOT, 'DroidSans-Bold.ttf'))) doc = SimpleDocTemplate(response, pagesize=A4) doc.topMargin = 0.5 * cm doc.bottomMargin = 0.5 * cm doc.leftMargin = 1.5 * cm doc.rightMargin = 1.5 * cm doc.pagesize = landscape(A4) if year == '2012': style = getSampleStyleSheet() style.add( ParagraphStyle(name='Center', alignment=TA_CENTER, fontName='DroidSans', fontSize=12)) elements = [ Paragraph( u'ΠΑΡΑΚΑΛΟΥΜΕ ΑΠΕΥΘΥΝΘΕΙΤΕ ΣΤΗΝ ΥΠΗΡΕΣΙΑ ΓΙΑ ΤΗΝ ΜΙΣΘΟΛΟΓΙΚΗ ΚΑΤΑΣΤΑΣΗ ΤΟΥ 2012', style['Center']) ] else: elements = generate_pdf_landscape_structure(reports) doc.build(elements) return response
def export_customer_report(request): try: if request.method == 'POST': dataset = Customer.objects.all() if not dataset.exists(): messages.error(request, 'No Data Found') return redirect('report:customer_report') if 'xls_export' in request.POST: response = HttpResponse(content_type='application/ms-excel') response[ 'Content-Disposition'] = 'attachment; filename="Customer Report.xls"' wb = xlwt.Workbook(encoding='utf-8', style_compression=2) ws = wb.add_sheet('customer_report') row_num = 3 font_style = xlwt.XFStyle() common = "font:name Calibri, bold on, height 200; align:wrap yes, horiz center, vert center ;" common1 = "align: wrap yes, horiz right, vert center ;" columns = ['SL', 'Name', 'E-mail', 'Phone', 'Address'] ws.write_merge(0, 1, 0, 5, 'Customer Report', xlwt.easyxf(common)) for col in range(len(columns)): ws.write(row_num, col, columns[col], font_style) row_num += 1 for count, data in enumerate((dataset)): ws.write(row_num, 0, count + 1, font_style) ws.write(row_num, 1, data.name, font_style) ws.write(row_num, 2, data.email, font_style) ws.write(row_num, 3, data.phone, font_style) ws.write(row_num, 4, data.address, xlwt.easyxf(common1)) row_num += 1 wb.save(response) return response elif 'pdf_export' in request.POST: styles = getSampleStyleSheet() doc = SimpleDocTemplate( "assets/pdf_files/Customer Report.pdf", pagesize=reportlab.lib.pagesizes.letter) parastyles = ParagraphStyle( 'header', parent=styles['Normal'], fontName='Helvetica-Bold', fontSize=8, alignment=TA_CENTER, textColor=colors.black, ) story = [] elements = [] columns = [] columns.insert(0, [ Paragraph('S/L', parastyles), Paragraph('Name', parastyles), Paragraph('Email', parastyles), Paragraph('Phone', parastyles), Paragraph('Address', parastyles) ]) texstyles = ParagraphStyle( 'text', parent=styles['Normal'], fontSize=8, alignment=TA_CENTER, textColor=colors.black, ) j = 1 for count, data in enumerate((dataset)): columns.insert(j, [ Paragraph(str(j), texstyles), Paragraph(str(data.name), texstyles), Paragraph(str(data.email), texstyles), Paragraph(str(data.phone), texstyles), Paragraph(str(data.address), texstyles) ]) j = j + 1 t = Table(columns, repeatRows=1, splitByRow=1) t.setStyle( TableStyle([('FONTSIZE', (0, 0), (-1, -1), 1), ('INNERGRID', (0, 0), (-1, -1), 0.25, colors.gray), ('BOX', (0, 0), (-1, -1), 0.25, colors.black), ('VALIGN', (0, 0), (-1, -1), 'TOP')])) dateofpdf = (datetime.now()).strftime("%d/%m/%Y") story.append(Paragraph("Customer Report", parastyles)) story.append(Spacer(1, 0.2 * inch)) story.append( Paragraph("Printed Date: " + dateofpdf, styles['Normal'])) story.append(Spacer(1, 0.2 * inch)) story.append(Spacer(1, 0.2 * inch)) elements.append(t) story.append(t) doc.build(story, onFirstPage=myFirstPage, onLaterPages=myLaterPages) fs = FileSystemStorage() with fs.open("pdf_files/Customer Report.pdf") as pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "Customer Report.pdf" response[ 'Content-Disposition'] = 'attachment; filename="{}"'.format( filename) return response return response except Exception as ex: messages.error(request, str(ex)) mylog.exception('export_customer_report', exc_info=True) return redirect('report:customer_report')
def render_using_config(self, config): # draw outline if in debug if self.debug or config.get('debug'): self.draw_debug_outline(config) # get the text to render text = self.extract_content(config) # choose the method to draw the string text_align = config['text-align'] if text_align == 'centre': style_alignment = TA_CENTER elif text_align == 'left': style_alignment = TA_LEFT else: raise Exception("Unhandled value for 'text-align': '%s'" % text_align) if config['overflow'] == 'wrap': frame = Frame( config['x'], config['y'], config['w'], config['h'], ) # create a paragraph style font_size = config['font-size'] style = ParagraphStyle(name='test') style.fontName = config['font-family'] style.alignment = style_alignment while font_size > minimum_font_size: style.fontSize = font_size style.leading = font_size para = Paragraph(text, style) if frame.add(para, self.canvas): break # Paragraph was too big - shrink the font size font_size -= 1 elif config['overflow'] == 'shrink': font_size = config['font-size'] while font_size > minimum_font_size: self.canvas.setFont(config['font-family'], font_size) if self.canvas.stringWidth(text) <= config['w']: break font_size -= 1 if text_align == 'centre': self.canvas.drawCentredString( config['x'] + config['w'] / 2, config['y'] + config['h'] - config['font-size'], text) elif text_align == 'left': self.canvas.drawString( config['x'], config['y'] + config['h'] - config['font-size'], text) else: raise Exception("Unhandled value for 'text-align': '%s'" % text_align) else: raise Exception("Unhandled value of 'overflow': '%s'" % config['overflow'])
def export_profit_loss_report(request): try: if request.method == 'POST': order_filter_args = {} stock_filter_args = {} year = request.POST['year'] month_obj = Get_Processed_Month(request.POST['month'], year) month = month_obj[0] order_filter_args['ordered_date__range'] = (datetime.combine( month_obj[1], time.min), datetime.combine(month_obj[2], time.max)) stock_filter_args['created_date__range'] = (datetime.combine( month_obj[1], time.min), datetime.combine(month_obj[2], time.max)) daterange = 'Report for - ' + str(month) + ', ' + str(year) no_of_order = Order.objects.filter(**order_filter_args).aggregate( Sum('id'))['id__sum'] sum_of_order = Order.objects.filter(**order_filter_args).aggregate( Sum('net_total'))['net_total__sum'] no_of_stock = Stock.objects.filter(**stock_filter_args).aggregate( Sum('id'))['id__sum'] sum_of_stock = Stock.objects.filter(**stock_filter_args).aggregate( Sum('total_price'))['total_price__sum'] if 'xls_export' in request.POST: response = HttpResponse(content_type='application/ms-excel') response[ 'Content-Disposition'] = 'attachment; filename="Profit-Loss Report.xls"' wb = xlwt.Workbook(encoding='utf-8', style_compression=2) ws = wb.add_sheet('profit_loss_report') common = "font:name Calibri, bold on, height 200; align:wrap yes, horiz center, vert center ;" ws.write_merge(0, 1, 0, 5, 'Profit-Loss Report', xlwt.easyxf(common)) ws.write_merge(2, 3, 0, 5, daterange, xlwt.easyxf(common)) ws.write_merge(5, 5, 0, 5, "No of Total Order - " + str(no_of_order), xlwt.easyxf(common)) ws.write_merge(6, 6, 0, 5, "Sum of Total Order - " + str(sum_of_order), xlwt.easyxf(common)) ws.write_merge(8, 8, 0, 5, "No of Total Purchase - " + str(no_of_stock), xlwt.easyxf(common)) ws.write_merge(9, 9, 0, 5, "Sum of Total Purchase - " + str(sum_of_stock), xlwt.easyxf(common)) wb.save(response) return response elif 'pdf_export' in request.POST: styles = getSampleStyleSheet() doc = SimpleDocTemplate( "assets/pdf_files/Profit-Loss Report.pdf", pagesize=reportlab.lib.pagesizes.letter) parastyles = ParagraphStyle( 'header', parent=styles['Normal'], fontName='Helvetica-Bold', fontSize=12, alignment=TA_CENTER, textColor=colors.black, ) story = [] dateofpdf = (datetime.now()).strftime("%d/%m/%Y") story.append(Paragraph("Profit-Loss Report", parastyles)) story.append(Spacer(1, 0.2 * inch)) story.append(Paragraph(daterange, styles['Normal'])) story.append(Spacer(1, 0.2 * inch)) story.append( Paragraph("Printed Date: " + dateofpdf, styles['Normal'])) story.append(Spacer(1, 0.2 * inch)) story.append(Spacer(1, 0.2 * inch)) story.append(Spacer(1, 0.2 * inch)) story.append( Paragraph("No of Total Order - " + str(no_of_order), parastyles)) story.append(Spacer(1, 0.2 * inch)) story.append( Paragraph("Sum of Total Order - " + str(sum_of_order), parastyles)) story.append(Spacer(1, 0.2 * inch)) story.append( Paragraph("No of Total Purchase - " + str(no_of_stock), parastyles)) story.append(Spacer(1, 0.2 * inch)) story.append( Paragraph("Sum of Total Purchase - " + str(sum_of_stock), parastyles)) doc.build(story, onFirstPage=myFirstPage, onLaterPages=myLaterPages) fs = FileSystemStorage() with fs.open("pdf_files/Profit-Loss Report.pdf") as pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "Profit-Loss Report.pdf" response[ 'Content-Disposition'] = 'attachment; filename="{}"'.format( filename) return response return response except Exception as ex: messages.error(request, str(ex)) mylog.exception('export_profit_loss_report', exc_info=True) return redirect('report:profit_loss_report')
def Imprimer(self): # 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_PRESTATIONS", "pdf") if sys.platform.startswith("win"): nomDoc = nomDoc.replace("/", "\\") doc = SimpleDocTemplate(nomDoc, pagesize=(largeur_page, hauteur_page), topMargin=30, bottomMargin=20, leftMargin=40, rightMargin=40) story = [] # Création du titre du document dataTableau = [] largeursColonnes = ((largeur_page - 175, 100)) dateDuJour = UTILS_Dates.DateEngFr(str(datetime.date.today())) dataTableau.append( (_(u"Synthèse des prestations"), _(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 createFormG(request, pk): # Build Form G Schedule of Providers caseObj = get_object_or_404(TblAppealMaster, pk=pk) caseName = caseObj.appealName caseNum = caseObj.caseNumber providerMaster = TblProviderMaster.objects.filter( caseNumber=caseNum).first() issueID = providerMaster.issueID issueInfo = TblIssueMaster.objects.get( issueSRGID=str(issueID).split('-')[0]) styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY)) elements = [] styles = getSampleStyleSheet() global title global cnum global case_name global case_rep global case_issue repObj = TblStaffMaster.objects.get(staffLastName=caseObj.staffID) title = "Model Form G: Schedule of Providers in Group" cnum = "Case No.: {0}".format(caseNum) case_name = "Group Case Name: {0}".format(caseName) case_rep = "Group Representative: {0} {1} / Strategic Reimbursement Group , LLC".format( str(repObj.staffFirstName), str(repObj.staffLastName)) case_issue = "Issue: {0}".format(issueInfo.issueShortDescription) columnHeaderNumber = Paragraph('<para align=center>#</para>', styles["Normal"]) columnHeaderProviderNumber = Paragraph( '<para align=center>Provider <br/>Number</para>', styles["Normal"]) columnHeaderProviderInfo = Paragraph( '<para align=center>Provider Name / Location <br/>' '(city, county, state)</para>', styles["Normal"]) columnHeaderFYE = Paragraph('<para align=center>FYE</para>', styles["Normal"]) columnHeaderMAC = Paragraph( '<para align=center>Intermediary / <br/> MAC</para>', styles["Normal"]) columnHeaderA = Paragraph( '<para align=center>A<br/>Date of Final<br/>Determination</para>', styles["Normal"]) columnHeaderB = Paragraph( '<para align=center>B<br/>Date of<br/>Hearing<br/>Request<br/>Add ' 'Issue<br/>Request</para>', styles["Normal"]) columnHeaderC = Paragraph( '<para align=center>C<br/>No.<br/>of<br/>Days</para>', styles["Normal"]) columnHeaderD = Paragraph('<para align=center>D<br/>Audit<br/>Adj.</para>', styles["Normal"]) columnHeaderE = Paragraph( '<para align=center>E<br/>Amount in<br/>Controversy</para>', styles["Normal"]) columnHeaderF = Paragraph( '<para align=center>F<br/>Prior Case<br/>No(s).</para>', styles["Normal"]) columnHeaderG = Paragraph( '<para align=center>G<br/>Date of<br/>Direct Add /<br/>Transfer(s)<br/>to Group</para>', styles["Normal"]) scheduleGData = [[ columnHeaderNumber, columnHeaderProviderNumber, columnHeaderProviderInfo, columnHeaderFYE, columnHeaderMAC, columnHeaderA, columnHeaderB, columnHeaderC, columnHeaderD, columnHeaderE, columnHeaderF, columnHeaderG ]] # Assemble rows for Form G caseProviders = TblProviderMaster.objects.filter( caseNumber=caseNum).order_by('provMasterTransferDate', 'providerID') global groupTotalImpact groupImpact = caseProviders.aggregate(Sum('provMasterImpact')) groupTotalImpact = "Total Amount in Controversy for All Providers: ${0:,}".format( groupImpact['provMasterImpact__sum']) for count, prov in enumerate(caseProviders, start=1): columnDataNumber = Paragraph( '<para align=center>' + str(count) + '</para>', styles["Normal"]) columnDataProviderNumber = Paragraph( '<para align=center>' + str(prov.providerID) + '</para>', styles["Normal"]) provName = TblProviderNameMaster.objects.get( providerID=prov.providerID) columnDataProviderInfo = Paragraph( '<para align=center>' + str(provName.providerName.title()) + '<br/>' + str(provName.providerCity) + ', ' + str(provName.providerCounty) + ', ' + str(provName.stateID) + '</para>', styles["Normal"]) columnDataFYE = Paragraph( '<para align=center>' + str(prov.provMasterFiscalYear.strftime("%m/%d/%Y")) + '</para>', styles["Normal"]) columnDataMAC = Paragraph( '<para align=center>' + str(caseObj.fiID) + '</para>', styles["Normal"]) columnDataA = Paragraph( '<para align=center>' + str(prov.provMasterDeterminationDate.strftime("%m/%d/%Y")) + '</para>', styles["Normal"]) hrqDate = TblAppealMaster.objects.get( caseNumber=prov.provMasterFromCase) columnDataB = Paragraph( '<para align=center>' + str(hrqDate.appealCreateDate.strftime("%m/%d/%Y")) + '</para>', styles["Normal"]) no_of_days = prov.get_no_days() columnDataC = Paragraph( '<para align=center>' + str(no_of_days) + '</para>', styles["Normal"]) columnDataD = Paragraph( '<para align=center>' + str(prov.provMasterAuditAdjs) + '</para>', styles["Normal"]) locale.setlocale(locale.LC_ALL, '') provImpactFormatted = "${0:,}".format(prov.provMasterImpact) columnDataE = Paragraph( '<para align=center>' + str(provImpactFormatted) + '</para>', styles["Normal"]) columnDataF = Paragraph( '<para align=center>' + str(prov.provMasterFromCase) + '</para>', styles["Normal"]) columnDataG = Paragraph( '<para align=center>' + str(prov.provMasterTransferDate.strftime("%m/%d/%Y")) + '</para>', styles["Normal"]) scheduleGData.append([ columnDataNumber, columnDataProviderNumber, columnDataProviderInfo, columnDataFYE, columnDataMAC, columnDataA, columnDataB, columnDataC, columnDataD, columnDataE, columnDataF, columnDataG ]) tR = Table(scheduleGData, repeatRows=1, colWidths=[ 1 * cm, 2 * cm, 4.5 * cm, 2.5 * cm, 2.5 * cm, 3 * cm, 3 * cm, 1.5 * cm, 2 * cm, 2.5 * cm, 2 * cm, 2.5 * cm ], rowHeights=1.05 * inch) tR.hAlign = 'CENTER' tblStyle = TableStyle([('BOX', (0, 0), (-1, -1), 1, colors.black), ('INNERGRID', (0, 0), (-1, -1), 1, colors.black)]) tR.setStyle(tblStyle) elements.append(tR) buffer = BytesIO() formGDoc = SimpleDocTemplate(buffer, pagesize=[A4[1], A4[0]], leftMargin=0, rightMargin=0, topMargin=105, bottomMargin=5) formGDoc.build(elements, onFirstPage=PageNumCanvas, onLaterPages=PageNumCanvas, canvasmaker=PageNumCanvas) pdf_value = buffer.getvalue() buffer.close() response = HttpResponse(content_type='application/pdf') response[ 'Content-Disposition'] = 'attachment; filename="formGScheduleG.pdf"' response.write(pdf_value) # return redirect(r'appeal-details', caseObj.caseNumber) return response
education = [ Education("Fuhsd Fremont", "GED diploma"), Education("Red Cross Safety Training", "CPR and First Aid Certification") ] #styling pdfmetrics.registerFont( TTFont('Nunito-Bold', 'resume_fonts/Nunito/Nunito-Bold.ttf')) pdfmetrics.registerFont( TTFont('Roboto-Light', 'resume_fonts/Roboto/Roboto-Light.ttf')) pdfmetrics.registerFont( TTFont('Roboto-Regular', 'resume_fonts/Roboto/Roboto-Regular.ttf')) styles = getSampleStyleSheet() styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY, leading=30)) title_size = 30 header_size = 18 subtext_size = 10 paragraph_size = 13 paragraph_color = '#4A4A4A' subtext_color = '#9B9B9B' name_color = "#3e7ce3" paragraph_font = 'Roboto-Light' subtitle_font = 'Roboto-Regular' header_font = 'Nunito-Bold' spacing_multiplier = 1.3 def put_content_line(content, size,
logo = "python_logo.png" magName = "Pythonista" issueNum = 12 subPrice = "99.00" limitedDate = "03/05/2010" freeGift = "tin foil hat" formatted_time = time.ctime() full_name = "Mike Driscoll" address_parts = ["411 State St.", "Marshalltown, IA 50158"] im = Image(logo, 2*inch, 2*inch) Story.append(im) styles=getSampleStyleSheet() styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY)) ptext = '<font size=12>%s</font>' % formatted_time Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 12)) # Create return address ptext = '<font size=12>%s</font>' % full_name Story.append(Paragraph(ptext, styles["Normal"])) for part in address_parts: ptext = '<font size=12>%s</font>' % part.strip() Story.append(Paragraph(ptext, styles["Normal"])) Story.append(Spacer(1, 12)) ptext = '<font size=12>Dear %s:</font>' % full_name.split()[0].strip() Story.append(Paragraph(ptext, styles["Normal"]))