def test5(self): '''extreme test inspired by Moritz Pfeiffer https://bitbucket.org/moritzpfeiffer/''' with self.assertRaises(LayoutError): text=""" Clearly, the natural general principle that will subsume this case is not subject to a parasitic gap construction. Presumably, most of the methodological work in modern linguistics can be defined in such a way as to impose the system of base rules exclusive of the lexicon. In the discussion of resumptive pronouns following (81), the fundamental error of regarding functional notions as categorial is to be regarded as a descriptive <span color="red">fact</span>.<br/>So far, the earlier discussion of deviance is not quite equivalent to a parasitic gap construction. To characterize a linguistic level L, a case of semigrammaticalness of a different sort may remedy and, at the same time, eliminate irrelevant intervening contexts in selectional <span color="red">rules</span>.<br/> Summarizing, then, we assume that the descriptive power of the base component can be defined in such a way as to impose nondistinctness in the sense of distinctive feature theory. """ styleSheet = getSampleStyleSheet() story = [] story.append(Paragraph(text, styleSheet['Normal'])) doc = BaseDocTemplate( outputfile('test_platypus_much_too_large.pdf'), pagesize=portrait(A4), pageTemplates=[PageTemplate( 'page_template', [Frame(0, 0, 0, 0, leftPadding=0, rightPadding=0, topPadding=0, bottomPadding=0, id='DUMMY_FRAME')], )], ) doc.build(story)
def build(self, flowables, onFirstPage=_doNothing, onLaterPages=_doNothing, canvasmaker=canvas.Canvas): """build the document using the flowables. Annotate the first page using the onFirstPage function and later pages using the onLaterPages function. The onXXX pages should follow the signature def myOnFirstPage(canvas, document): # do annotations and modify the document ... The functions can do things like draw logos, page numbers, footers, etcetera. They can use external variables to vary the look (for example providing page numbering or section names). """ self._calc() # in case we changed margins sizes etc frameT = Frame(self.leftMargin, self.bottomMargin, self.width, self.height, id="normal") self.addPageTemplates( [ PageTemplate(id="First", frames=frameT, onPage=onFirstPage, pagesize=self.pagesize), PageTemplate(id="Later", frames=frameT, onPage=onLaterPages, pagesize=self.pagesize), ] ) if onFirstPage is _doNothing and hasattr(self, "onFirstPage"): self.pageTemplates[0].beforeDrawPage = self.onFirstPage if onLaterPages is _doNothing and hasattr(self, "onLaterPages"): self.pageTemplates[1].beforeDrawPage = self.onLaterPages BaseDocTemplate.build(self, flowables, canvasmaker=canvasmaker)
def export(listino, luogoDiRiferimento): response = http.HttpResponse(content_type='application/pdf') width, height = portrait(A4) pageTemplates = [ PageTemplate(id='Listino', onPage=onPageListino), ] doc = BaseDocTemplate( response, pagesize=(width, height), leftMargin=1 * cm, rightMargin=1 * cm, bottomMargin=1.5 * cm, topMargin=1 * cm, showBoundary=test, pageTemplates=pageTemplates, ) doc.listino = listino # arricchisco il doc righe_prezzo = listino.prezzolistino_set.all() story = [] listinoEsclusivo = getTabellaListino(doc, righe_prezzo, 'T', luogoDiRiferimento) if listinoEsclusivo: title = Paragraph("SERVIZIO TAXI ESCLUSIVO", normalStyle) story.append(title) story.append(listinoEsclusivo) listinoCollettivo = getTabellaListino(doc, righe_prezzo, 'C', luogoDiRiferimento) if listinoEsclusivo and listinoCollettivo: story.append(Spacer(1, 1.5 * cm)) if listinoCollettivo: title = Paragraph("SEVIZIO COLLETIVO MINIBUS", normalStyle) story.append(KeepTogether([title, listinoCollettivo])) if not listinoCollettivo and not listinoEsclusivo: story.append( Paragraph("Non abbiamo nessuna corsa specificata nel listino.", normal_style) ) # footer footer_style = ParagraphStyle(name='Justify', alignment=TA_JUSTIFY, fontSize=8) # footer_height = 0 if LISTINO_FOOTER: note_finali_lines = [LISTINO_FOOTER] story.append(Spacer(1, 1 * cm)) note_finali = Paragraph("<br/>".join(note_finali_lines), footer_style) # note_finali.wrap(width - doc.rightMargin - doc.leftMargin, 5 * cm) # note_finali.drawOn(canvas, doc.leftMargin, doc.bottomMargin) # footer_height = note_finali.height story.append(note_finali) doc.build(story, canvasmaker=NumberedCanvas) return response
def __init__(self, dictValeurs={}, dictOptions={}, IDmodele=None, ouverture=True, nomFichier=None): """ Impression """ global DICT_VALEURS, DICT_OPTIONS DICT_VALEURS = dictValeurs DICT_OPTIONS = dictOptions # Initialisation du document if nomFichier == None: nomDoc = FonctionsPerso.GenerationNomDoc("LOCATIONS", "pdf") else: nomDoc = nomFichier doc = BaseDocTemplate(nomDoc, pagesize=TAILLE_PAGE, showBoundary=False) # Mémorise le ID du modèle modeleDoc = DLG_Noedoc.ModeleDoc(IDmodele=IDmodele) doc.modeleDoc = modeleDoc # Importe le template de la première page doc.addPageTemplates(MyPageTemplate(pageSize=TAILLE_PAGE, doc=doc)) story = [] styleSheet = getSampleStyleSheet() h3 = styleSheet['Heading3'] styleTexte = styleSheet['BodyText'] styleTexte.fontName = "Helvetica" styleTexte.fontSize = 9 styleTexte.borderPadding = 9 styleTexte.leading = 12 # ----------- Insertion du contenu des frames -------------- listeLabels = [] for IDlocation, dictValeur in dictValeurs.iteritems(): listeLabels.append((dictValeur["{FAMILLE_NOM}"], IDlocation)) listeLabels.sort() for labelDoc, IDlocation in listeLabels: dictValeur = dictValeurs[IDlocation] if dictValeur["select"] == True: story.append(DocAssign("IDlocation", IDlocation)) nomSansCivilite = dictValeur["{FAMILLE_NOM}"] story.append(Bookmark(nomSansCivilite, str(IDlocation))) # Saut de page story.append(PageBreak()) # Finalisation du PDF doc.build(story) # Ouverture du PDF if ouverture == True: FonctionsPerso.LanceFichierExterne(nomDoc)
def build(self, flowables, firstPageTemplate=_doNothing, laterPageTemplate=_doNothing): """Custom build method to separate first page and later page templates. """ self._calc() # in case we changed margin sizes if firstPageTemplate is _doNothing and hasattr(self, 'firstPageTemplate'): self.pageTemplates[0].beforeDrawPage = self.firstPageTemplate if laterPageTemplate is _doNothing and hasattr(self, 'laterPageTemplate'): self.pageTemplates[1].beforeDrawPage = self.laterPageTemplate BaseDocTemplate.build(self, flowables)
def __init__(self, dictValeurs={}, dictOptions={}, IDmodele=None, ouverture=True, nomFichier=None): """ Impression """ global DICT_VALEURS, DICT_OPTIONS DICT_VALEURS = dictValeurs DICT_OPTIONS = dictOptions # Initialisation du document if nomFichier == None : nomDoc = FonctionsPerso.GenerationNomDoc("LOCATIONS", "pdf") else : nomDoc = nomFichier doc = BaseDocTemplate(nomDoc, pagesize=TAILLE_PAGE, showBoundary=False) # Mémorise le ID du modèle modeleDoc = DLG_Noedoc.ModeleDoc(IDmodele=IDmodele) doc.modeleDoc = modeleDoc # Importe le template de la première page doc.addPageTemplates(MyPageTemplate(pageSize=TAILLE_PAGE, doc=doc)) story = [] styleSheet = getSampleStyleSheet() h3 = styleSheet['Heading3'] styleTexte = styleSheet['BodyText'] styleTexte.fontName = "Helvetica" styleTexte.fontSize = 9 styleTexte.borderPadding = 9 styleTexte.leading = 12 # ----------- Insertion du contenu des frames -------------- listeLabels = [] for IDlocation, dictValeur in dictValeurs.iteritems() : listeLabels.append((dictValeur["{FAMILLE_NOM}"], IDlocation)) listeLabels.sort() for labelDoc, IDlocation in listeLabels : dictValeur = dictValeurs[IDlocation] if dictValeur["select"] == True : story.append(DocAssign("IDlocation", IDlocation)) nomSansCivilite = dictValeur["{FAMILLE_NOM}"] story.append(Bookmark(nomSansCivilite, str(IDlocation))) # Saut de page story.append(PageBreak()) # Finalisation du PDF doc.build(story) # Ouverture du PDF if ouverture == True : FonctionsPerso.LanceFichierExterne(nomDoc)
def build(self, flowables, onFirstPage=_doNothing, canvasmaker=canvas.Canvas): self._calc() frameT = Frame(letter_left_margin, letter_bottom_margin, letter_frame_width, letter_frame_height, leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0, id='normal') self.addPageTemplates([PageTemplate(id='First',frames=frameT, onPage=onFirstPage, pagesize=self.pagesize)]) if onFirstPage is _doNothing and hasattr(self,'onFirstPage'): self.pageTemplates[0].beforeDrawPage = self.onFirstPage BaseDocTemplate.build(self, flowables, canvasmaker=canvasmaker)
def renderElements(elements, filesuffix=None, tmpdir=None): """ takes a list of reportlab flowables and renders them to a test.pdf file""" margin = 2 * cm if filesuffix: fn = 'test_' + filesuffix + '.pdf' else: fn = 'test.pdf' fn = os.path.join(tmpdir, fn) doc = BaseDocTemplate(fn, topMargin=margin, leftMargin=margin, rightMargin=margin, bottomMargin=margin) pt = WikiPage("Title") doc.addPageTemplates(pt) elements.insert(0, NextPageTemplate('Title')) doc.build(elements)
def build(self, flowables): self._calc() #in case we changed margins sizes etc frameT = Frame(self.leftMargin, self.bottomMargin, self.width, self.height, id='normal', leftPadding=0, bottomPadding=0, rightPadding=0, topPadding=0) self.addPageTemplates( [PageTemplate(id='First', frames=frameT, pagesize=self.pagesize)]) BaseDocTemplate.build(self, flowables, canvasmaker=self._canvasMaker)
def test5(self): '''extreme test inspired by Moritz Pfeiffer https://bitbucket.org/moritzpfeiffer/''' with self.assertRaises(LayoutError): text = """ Clearly, the natural general principle that will subsume this case is not subject to a parasitic gap construction. Presumably, most of the methodological work in modern linguistics can be defined in such a way as to impose the system of base rules exclusive of the lexicon. In the discussion of resumptive pronouns following (81), the fundamental error of regarding functional notions as categorial is to be regarded as a descriptive <span color="red">fact</span>.<br/>So far, the earlier discussion of deviance is not quite equivalent to a parasitic gap construction. To characterize a linguistic level L, a case of semigrammaticalness of a different sort may remedy and, at the same time, eliminate irrelevant intervening contexts in selectional <span color="red">rules</span>.<br/> Summarizing, then, we assume that the descriptive power of the base component can be defined in such a way as to impose nondistinctness in the sense of distinctive feature theory. """ styleSheet = getSampleStyleSheet() story = [] story.append(Paragraph(text, styleSheet['Normal'])) doc = BaseDocTemplate( outputfile('test_platypus_much_too_large.pdf'), pagesize=portrait(A4), pageTemplates=[ PageTemplate( 'page_template', [ Frame(0, 0, 0, 0, leftPadding=0, rightPadding=0, topPadding=0, bottomPadding=0, id='DUMMY_FRAME') ], ) ], ) doc.build(story)
def pdf_basic_page( objects, title='', preferences=None ): # used by gen_table.make_page() """Simple convenience fonction: build a page from a list of platypus objects, adding a title if specified. """ StyleSheet = styles.getSampleStyleSheet() report = cStringIO.StringIO() # in-memory document, no disk file document = BaseDocTemplate(report) document.addPageTemplates( ScolarsPageTemplate(document, title=title, author='%s %s (E. Viennet)' % (SCONAME, SCOVERSION), footer_template="Edité par %(scodoc_name)s le %(day)s/%(month)s/%(year)s à %(hour)sh%(minute)s", preferences=preferences )) if title: head = Paragraph(SU(title), StyleSheet["Heading3"]) objects = [ head ] + objects document.build(objects) data = report.getvalue() return data
def pagecat2(request): doc = BaseDocTemplate('test.pdf') frame_title = Frame(doc.leftMargin, doc.bottomMargin, doc.width/2-6, doc.height, id='title') frame_back = Frame(doc.leftMargin, doc.bottomMargin, doc.width/2-6, doc.height, id='back') frame_1col = Frame(doc.leftMargin, doc.bottomMargin, doc.width/2-6, doc.height, id='col12') frame1_2col = Frame(doc.leftMargin, doc.bottomMargin, doc.width/2-6, doc.height, id='col1') frame2_2col = Frame(doc.leftMargin+doc.width/2+6, doc.bottomMargin, doc.width/2-6, doc.height, id='col2') doc.addPageTemplates([ PageTemplate(id='Title', frames=frame_title, onPage=static_title), PageTemplate(id='Back', frames=frame_back, onPage=static_back), PageTemplate(id='OneCol', frames=frame_1col, onPage=static_1col), PageTemplate(id='TwoCol', frames=[frame1_2col, frame2_2col], onPage=static_2col), ]) story = [Paragraph('<b>Table of contents</b>', ParagraphStyle('normal')), NextPageTemplate('TwoCol'), PageBreak(), '<includePdfPages filename="pdf1.pdf" pages="1,2,3"/>', NextPageTemplate('TwoCol')] doc.build(story) return render(request, "test.html")
def build(self,flowables,onFirstPage=_doNothing, onLaterPages=_doNothing, canvasmaker=canvas.Canvas): """build the document using the flowables. Annotate the first page using the onFirstPage function and later pages using the onLaterPages function. The onXXX pages should follow the signature def myOnFirstPage(canvas, document): # do annotations and modify the document ... The functions can do things like draw logos, page numbers, footers, etcetera. They can use external variables to vary the look (for example providing page numbering or section names). """ self._calc() #in case we changed margins sizes etc frameT = Frame(self.leftMargin, self.bottomMargin, self.width, self.height, id='normal') self.addPageTemplates([PageTemplate(id='First',frames=frameT, onPage=onFirstPage,pagesize=self.pagesize), PageTemplate(id='Later',frames=frameT, onPage=onLaterPages,pagesize=self.pagesize)]) if onFirstPage is _doNothing and hasattr(self,'onFirstPage'): self.pageTemplates[0].beforeDrawPage = self.onFirstPage if onLaterPages is _doNothing and hasattr(self,'onLaterPages'): self.pageTemplates[1].beforeDrawPage = self.onLaterPages BaseDocTemplate.build(self,flowables, canvasmaker=canvasmaker)
def __init__(self, dictValeurs={}, IDmodele=None, nomDoc=FonctionsPerso.GenerationNomDoc("INSCRIPTION", "pdf"), afficherDoc=True): """ Impression """ global DICT_VALEURS DICT_VALEURS = dictValeurs # Initialisation du document doc = BaseDocTemplate(nomDoc, pagesize=TAILLE_PAGE, showBoundary=False) # Mémorise le ID du modèle modeleDoc = DLG_Noedoc.ModeleDoc(IDmodele=IDmodele) doc.modeleDoc = modeleDoc doc.addPageTemplates(MyPageTemplate(pageSize=TAILLE_PAGE, doc=doc)) story = [] styleSheet = getSampleStyleSheet() h3 = styleSheet['Heading3'] styleTexte = styleSheet['BodyText'] styleTexte.fontName = "Helvetica" styleTexte.fontSize = 9 styleTexte.borderPadding = 9 styleTexte.leading = 12 couleurFond = (0.8, 0.8, 1) # ----------- Insertion du contenu des frames -------------- cadre_principal = doc.modeleDoc.FindObjet("cadre_principal") if cadre_principal != None : if DICT_VALEURS["intro"] != None or DICT_VALEURS["tableau"] == True : # ------------------- TITRE ----------------- dataTableau = [] largeursColonnes = [ TAILLE_CADRE_CONTENU[2], ] dataTableau.append((_(u"Confirmation d'inscription"),)) dataTableau.append((u"",)) style = TableStyle([ ('VALIGN', (0,0), (-1,-1), 'MIDDLE'), ('FONT',(0,0),(0,0), "Helvetica-Bold", 19), ('FONT',(0,1),(0,1), "Helvetica", 8), ('LINEBELOW', (0,0), (0,0), 0.25, colors.black), ('ALIGN', (0,0), (-1,-1), 'LEFT'), ]) tableau = Table(dataTableau, largeursColonnes) tableau.setStyle(style) story.append(tableau) story.append(Spacer(0, 10)) # TEXTE D'INTRODUCTION paraStyleIntro = ParagraphStyle(name="intro", fontName="Helvetica", fontSize=11, leading=14, spaceBefore=0, spaceafter=0, leftIndent=0, rightIndent=0, alignment=0, ) if DICT_VALEURS["intro"] != None : texteIntro = DICT_VALEURS["intro"] story.append(Paragraph(u"<i>%s</i>" % texteIntro, paraStyleIntro)) story.append(Spacer(0,20)) if DICT_VALEURS["tableau"] == True : # ------------------- TABLEAU CONTENU ----------------- dataTableau = [] largeursColonnes = [ 80, 280] paraStyle = ParagraphStyle(name="detail", fontName="Helvetica-Bold", fontSize=9, ) dataTableau.append( (_(u"Nom"), Paragraph(DICT_VALEURS["{INDIVIDU_NOM}"], paraStyle)) ) dataTableau.append( (_(u"Prénom"), Paragraph(DICT_VALEURS["{INDIVIDU_PRENOM}"], paraStyle)) ) dataTableau.append( (_(u"Activité"), Paragraph(DICT_VALEURS["{ACTIVITE_NOM_LONG}"], paraStyle)) ) dataTableau.append( (_(u"Groupe"), Paragraph(DICT_VALEURS["{GROUPE_NOM_LONG}"], paraStyle)) ) dataTableau.append( (_(u"Catégorie"), Paragraph(DICT_VALEURS["{NOM_CATEGORIE_TARIF}"], paraStyle)) ) style = TableStyle([ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('FONT', (0, 0), (0, -1), "Helvetica", 9), ('GRID', (0, 0), (-1, -1), 0.25, colors.black), ('ALIGN', (0, 0), (0, -1), 'RIGHT'), ]) tableau = Table(dataTableau, largeursColonnes) tableau.setStyle(style) story.append(tableau) # Si aucune frame principale if len(story) == 0 : story.append(Spacer(0,20)) # Enregistrement et ouverture du PDF try : doc.build(story) except Exception, err : print "Erreur dans ouverture PDF :", err if "Permission denied" in err : dlg = wx.MessageDialog(None, _(u"Noethys ne peut pas créer le PDF.\n\nVeuillez vérifier qu'un autre PDF n'est pas déjà ouvert en arrière-plan..."), _(u"Erreur d'édition"), wx.OK | wx.ICON_ERROR) dlg.ShowModal() dlg.Destroy() return
def __init__(self, dictValeurs={}, dictOptions={}, IDmodele=None, ouverture=True, nomFichier=None): """ Impression """ global DICT_VALEURS, DICT_OPTIONS DICT_VALEURS = dictValeurs DICT_OPTIONS = dictOptions # Initialisation du document if nomFichier == None : nomDoc = FonctionsPerso.GenerationNomDoc("COTISATIONS", "pdf") else : nomDoc = nomFichier doc = BaseDocTemplate(nomDoc, pagesize=TAILLE_PAGE, showBoundary=False) # Mémorise le ID du modèle modeleDoc = DLG_Noedoc.ModeleDoc(IDmodele=IDmodele) doc.modeleDoc = modeleDoc # Importe le template de la première page doc.addPageTemplates(MyPageTemplate(pageSize=TAILLE_PAGE, doc=doc)) story = [] styleSheet = getSampleStyleSheet() h3 = styleSheet['Heading3'] styleTexte = styleSheet['BodyText'] styleTexte.fontName = "Helvetica" styleTexte.fontSize = 9 styleTexte.borderPadding = 9 styleTexte.leading = 12 # ----------- Insertion du contenu des frames -------------- listeLabels = [] for IDcotisation, dictValeur in dictValeurs.iteritems() : listeLabels.append((dictValeur["{FAMILLE_NOM}"], IDcotisation)) listeLabels.sort() for labelDoc, IDcotisation in listeLabels : dictValeur = dictValeurs[IDcotisation] if dictValeur["select"] == True : story.append(DocAssign("IDcotisation", IDcotisation)) nomSansCivilite = dictValeur["{FAMILLE_NOM}"] story.append(Bookmark(nomSansCivilite, str(IDcotisation))) ## # ------------------- TITRE ----------------- ## dataTableau = [] ## largeursColonnes = [ TAILLE_CADRE_CONTENU[2], ] ## dataTableau.append((dictCompte["titre"],)) ## texteDateReference = UTILS_Dates.DateEngFr(str(datetime.date.today())) ## dataTableau.append((_(u"Situation au %s") % texteDateReference,)) ## style = TableStyle([ ## ('VALIGN', (0,0), (-1,-1), 'MIDDLE'), ## ('FONT',(0,0),(0,0), "Helvetica-Bold", 19), ## ('FONT',(0,1),(0,1), "Helvetica", 8), ## ('LINEBELOW', (0,0), (0,0), 0.25, colors.black), ## ('ALIGN', (0,0), (-1,-1), 'LEFT'), ## ]) ## tableau = Table(dataTableau, largeursColonnes) ## tableau.setStyle(style) ## story.append(tableau) ## story.append(Spacer(0,30)) ## ## ## couleurFond = (0.8, 0.8, 1) ## couleurFondActivite = (0.92, 0.92, 1) ## ## # TEXTE CONTENU ## paraStyle = ParagraphStyle(name="contenu", ## fontName="Helvetica", ## fontSize=11, ## #leading=7, ## spaceBefore=0, ## spaceafter=0, ## leftIndent=6, ## rightIndent=6, ## ) ## ## texte = dictCompte["texte"] ## listeParagraphes = texte.split("</para>") ## for paragraphe in listeParagraphes : ## textePara = Paragraph(u"%s</para>" % paragraphe, paraStyle) ## story.append(textePara) # Saut de page story.append(PageBreak()) # Finalisation du PDF doc.build(story) # Ouverture du PDF if ouverture == True : FonctionsPerso.LanceFichierExterne(nomDoc)
def render_to_reportlab(context): """ In context dictionary we could have a 'fattura' or a list of fatture in 'fatture'. Everything will be appended to a pdf returned as Django response. To reset page counter between different invoices, we'll use 2 "Normale" templates, one for even and one for odds, so every times the template changes we'll reset the NumberedCanvas """ if "fattura" in context and "fatture" in context: raise Exception("Please create PDF choosing between a fattura or multiple fatture") if "fattura" in context: fatture = [context.get('fattura')] else: fatture = context.get('fatture') response = http.HttpResponse(content_type='application/pdf') NormalTemplates = ['Normale0', 'Normale1'] fatture_rimanenti = len(fatture) story = [] pageTemplates = [ PageTemplate(id='Normale0', onPage=onPageNormal), PageTemplate(id='Normale1', onPage=onPageNormal), PageTemplate(id='ConducenteConsorzio', onPage=onPageConducenteConsorzio), PageTemplate(id='ConsorzioConducente', onPage=onPageConsorzioConducente), ] # scelgo il template della prima pagina come primo della lista if fatture[0].is_ricevuta_sdoppiata(): lastTemplateID = 'ConducenteConsorzio' pageTemplates = pageTemplates[2:] + pageTemplates[:2] else: lastTemplateID = 'Normale0' width, height = portrait(A4) doc = BaseDocTemplate( response, pagesize=(width, height), leftMargin=1 * cm, rightMargin=1 * cm, bottomMargin=1.5 * cm, topMargin=1 * cm, showBoundary=test, pageTemplates=pageTemplates, ) doc.fatture = fatture doc.lastTemplateID = lastTemplateID doc.fattura_corrente = 0 for fattura in fatture: ricevutaMultipla = fattura.is_ricevuta_sdoppiata() story_fattura = [] fatturazione = FATTURE_PER_TIPO[fattura.tipo] righeFattura = [ ('Descrizione', 'Q.tà',) + (('Prezzo', 'IVA %') if FATTURE_SHOW_VAT_COLUMN else tuple()) + ('Importo',), ] righe = fattura.righe.all() raggruppa_barbatrucco = False if fatturazione.codice == "5": totale = sum([r.val_totale() for r in righe]) conducente = righe[0].conducente if righe else None if "Imposta di bollo" not in [r.descrizione for r in righe]: if not (totale < settings.MIN_PRICE_FOR_TAXSTAMP and (conducente is None or conducente.emette_ricevute) ): raggruppa_barbatrucco = True if raggruppa_barbatrucco: # print "5 esente iva con barbatrucco" netto = totale / Decimal(1.1) class RigaTotaleIvata(object): # una riga che fa corrispondere il totale descrizione = "Servizi per consorzio." note = None qta = 1 prezzo = netto iva = 10 def val_imponibile(self): return self.prezzo def val_iva(self): return totale - netto def val_totale(self): return totale riga = RigaTotaleIvata() # la fattura ha totale pari al totale di tutte le righe # l'iva è fissa al 10% e il netto è calcolato di conseguenza imponibile = netto iva = totale - netto righe = [riga] else: imponibile = fattura.val_imponibile() iva = fattura.val_iva() for riga in righe: descrizione = riga.descrizione if riga.note: descrizione += " (%s)" % riga.note row_values = ( ( Paragraph(descrizione, normalStyle), Paragraph("%s" % riga.qta, normalStyle) ) + ( ( moneyfmt(riga.prezzo), riga.iva, ) if FATTURE_SHOW_VAT_COLUMN else tuple()) + ( moneyfmt(riga.val_totale()), ) ) righeFattura.append(row_values) righeTotali = [] if FATTURE_SHOW_VAT_COLUMN: righeTotali.append(( 'Imponibile', moneyfmt(imponibile) )) righeTotali.append(( 'IVA', moneyfmt(iva) )) righeTotali.append(( 'TOTALE', moneyfmt(fattura.val_totale()) )) righeStyle = TableStyle([ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('ALIGN', (0, 0), (-1, -1), 'RIGHT'), # globalmente allineato a destra... ('ALIGN', (0, 0), (1, -1), 'LEFT'), # tranne la prima colonna (con la descrizione) ('GRID', (0, 1), (-1, -1), 0.1, colors.grey), ('FACE', (0, 0), (-1, -1), 'Helvetica'), ('FACE', (0, 0), (-1, 0), 'Helvetica-Bold'), # header ('SIZE', (0, 0), (-1, -1), 8), # ('SPAN', (0, -1), (3, -1)), # anziché mettere lo span qui aggiungo in coda una tabella diversa ]) totaliStyle = TableStyle([ ('ALIGN', (0, 0), (-1, -1), 'RIGHT'), ('GRID', (-1, 0), (-1, -1), 0.1, colors.grey), ('FACE', (0, 0), (-1, -1), 'Helvetica'), # header ('FACE', (0, -1), (-1, -1), 'Helvetica-Bold'), # Totale ('SIZE', (0, 0), (-1, -1), 8), ]) price_columns = 4 if FATTURE_SHOW_VAT_COLUMN else 2 colWidths = ( ((width - doc.leftMargin - doc.rightMargin) - (1.6 * cm * price_columns),) + (1.6 * cm,) * price_columns ) story_fattura = [Table(righeFattura, style=righeStyle, repeatRows=1, colWidths=colWidths)] story_fattura.append(KeepTogether(Table(righeTotali, style=totaliStyle, colWidths=( width - doc.leftMargin - doc.rightMargin - 1.6 * cm, 1.6 * cm)))) if ricevutaMultipla: # le ricevute si raddoppiano con 2 template diversi # raddoppio lo story di questa fattura cambiando template story_fattura = story_fattura + [NextPageTemplate("ConsorzioConducente"), PageBreak()] + story_fattura fatture_rimanenti -= 1 if fatture_rimanenti: story_fattura += [NextPageTemplate(NormalTemplates[-1]), PageBreak()] NormalTemplates.reverse() # reverse current, next normal template story = story + story_fattura doc.build(story, canvasmaker=NumberedCanvas) return response
def __init__(self, dictValeurs={}, IDmodele=None, nomDoc=FonctionsPerso.GenerationNomDoc("RECU_REGLEMENT", "pdf"), afficherDoc=True): """ Impression """ global DICT_VALEURS DICT_VALEURS = dictValeurs # Initialisation du document doc = BaseDocTemplate(nomDoc, pagesize=TAILLE_PAGE, showBoundary=False) # Mémorise le ID du modèle modeleDoc = DLG_Noedoc.ModeleDoc(IDmodele=IDmodele) doc.modeleDoc = modeleDoc # Vérifie qu'un cadre principal existe bien dans le document if doc.modeleDoc.FindObjet("cadre_principal") == None : raise Exception("Votre modele de document doit obligatoirement comporter un cadre principal. Retournez dans l'editeur de document et utilisez pour votre modele la commande 'Inserer un objet special > Inserer le cadre principal'.") # Mémorise le ID du modèle modeleDoc = DLG_Noedoc.ModeleDoc(IDmodele=IDmodele) doc.modeleDoc = modeleDoc doc.addPageTemplates(MyPageTemplate(pageSize=TAILLE_PAGE, doc=doc)) story = [] styleSheet = getSampleStyleSheet() h3 = styleSheet['Heading3'] styleTexte = styleSheet['BodyText'] styleTexte.fontName = "Helvetica" styleTexte.fontSize = 9 styleTexte.borderPadding = 9 styleTexte.leading = 12 ## # Définit le template des pages suivantes ## story.append(NextPageTemplate("suivante")) # ----------- Insertion du contenu des frames -------------- # ------------------- TITRE ----------------- dataTableau = [] largeursColonnes = [ TAILLE_CADRE_CONTENU[2], ] dataTableau.append((_(u"Reçu de règlement"),)) dataTableau.append((u"",)) style = TableStyle([ ('VALIGN', (0,0), (-1,-1), 'MIDDLE'), ('FONT',(0,0),(0,0), "Helvetica-Bold", 19), ('FONT',(0,1),(0,1), "Helvetica", 8), ('LINEBELOW', (0,0), (0,0), 0.25, colors.black), ('ALIGN', (0,0), (-1,-1), 'LEFT'), ]) tableau = Table(dataTableau, largeursColonnes) tableau.setStyle(style) story.append(tableau) story.append(Spacer(0, 10)) # TEXTE D'INTRODUCTION paraStyleIntro = ParagraphStyle(name="intro", fontName="Helvetica", fontSize=11, leading=14, spaceBefore=0, spaceafter=0, leftIndent=0, rightIndent=0, alignment=0, ) if DICT_VALEURS["intro"] != None : texteIntro = DICT_VALEURS["intro"] story.append(Paragraph(u"<i>%s</i>" % texteIntro, paraStyleIntro)) story.append(Spacer(0,20)) couleurFond = (0.8, 0.8, 1) # ------------------- TABLEAU CONTENU ----------------- dataTableau = [] largeursColonnes = [ 120, 280] paraStyle = ParagraphStyle(name="detail", fontName="Helvetica-Bold", fontSize=9, ) dataTableau.append( (_(u"Caractéristiques du règlement"), "") ) montantEnLettres = UTILS_Conversion.trad(DICT_VALEURS["montant"], MONNAIE_SINGULIER, MONNAIE_DIVISION).strip() dataTableau.append( (_(u"Montant du règlement :"), Paragraph(montantEnLettres.capitalize(), paraStyle) ) ) dataTableau.append( (_(u"Mode de règlement :"), Paragraph(DICT_VALEURS["nomMode"], paraStyle) ) ) dataTableau.append( (_(u"Nom du payeur :"), Paragraph(DICT_VALEURS["nomPayeur"], paraStyle) ) ) if DICT_VALEURS["nomEmetteur"] != None : dataTableau.append( (_(u"Nom de l'émetteur :"), Paragraph(DICT_VALEURS["nomEmetteur"], paraStyle) ) ) if DICT_VALEURS["numPiece"] not in ("", None) : dataTableau.append( (_(u"Numéro de pièce :"), Paragraph(DICT_VALEURS["numPiece"], paraStyle) ) ) if DICT_VALEURS["date_differe"] not in ("", None): dataTableau.append((_(u"Encaissement différé :"), Paragraph(_(u"A partir du %s") % DICT_VALEURS["{DATE_DIFFERE}"], paraStyle))) style = TableStyle([ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('FONT', (0, 0), (0, -1), "Helvetica", 9), ('FONT', (1, 0), (1, -1), "Helvetica-Bold", 9), ('GRID', (0, 0), (-1, -1), 0.25, colors.black), ('ALIGN', (0, 1), (0, -1), 'RIGHT'), ('ALIGN', (1, 1), (1, -1), 'LEFT'), ('FONT', (0, 0), (0, 0), "Helvetica", 7), ('SPAN', (0, 0), (-1, 0)), ('BACKGROUND', (0, 0), (-1, 0), couleurFond), ]) tableau = Table(dataTableau, largeursColonnes) tableau.setStyle(style) story.append(tableau) # --------------------- LISTE DES PRESTATIONS ---------------- listePrestations = dictValeurs["prestations"] if len(listePrestations) > 0 : story.append(Spacer(0,20)) textePrestations = _(u"En paiement des prestations suivantes :") story.append(Paragraph(u"<i>%s</i>" % textePrestations, paraStyleIntro)) story.append(Spacer(0,20)) dataTableau = [(_(u"Date"), _(u"Activité"), _(u"Individu"), _(u"Intitulé"), _(u"Part utilisée")),] largeursColonnes = [50, 95, 70, 135, 50] paraStyle = ParagraphStyle(name="detail", fontName="Helvetica", fontSize=7, leading=7, spaceBefore=0, spaceAfter=0, ) for dictPrestation in listePrestations : date = UTILS_Dates.DateDDEnFr(dictPrestation["date"]) activite = dictPrestation["nomActivite"] individu = dictPrestation["prenomIndividu"] label = dictPrestation["label"] montant = dictPrestation["montant"] ventilation = dictPrestation["ventilation"] dataTableau.append(( Paragraph(u"<para align='center'>%s</para>"% date, paraStyle), Paragraph(activite, paraStyle), Paragraph(individu, paraStyle), Paragraph(label, paraStyle), Paragraph(u"<para align='right'>%.2f %s</para>" % (ventilation, SYMBOLE), paraStyle), )) style = TableStyle([ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('GRID', (0, 0), (-1, -1), 0.25, colors.black), ('FONT', (0, 0), (-1, -1), "Helvetica", 7), ('TOPPADDING', (0, 1), (-1, -1), 1), ('BOTTOMPADDING', (0, 1), (-1, -1), 3), # Ligne Entetes ('FONT', (0, 0), (-1, 0), "Helvetica", 7), ('BACKGROUND', (0, 0), (-1, 0), couleurFond), ('ALIGN', (0, 0), (-1, 0), 'CENTER'), ]) tableau = Table(dataTableau, largeursColonnes) tableau.setStyle(style) story.append(tableau) # Enregistrement et ouverture du PDF try : doc.build(story) except Exception, err : print "Erreur dans ouverture PDF :", err if "Permission denied" in err : dlg = wx.MessageDialog(None, _(u"Noethys ne peut pas créer le PDF.\n\nVeuillez vérifier qu'un autre PDF n'est pas déjà ouvert en arrière-plan..."), _(u"Erreur d'édition"), wx.OK | wx.ICON_ERROR) dlg.ShowModal() dlg.Destroy() return
class ValuationPrint(): def __init__(self, filename): self.width, self.height = pagesizes.A4 self.lmargin = 1*units.cm self.rmargin = self.width - self.lmargin #styles = getSampleStyleSheet() #self.styleH = styles['Heading1'] #self.styleN = styles['Normal'] self.doc = BaseDocTemplate(filename) self.val_template = PageTemplate(id='valuation', frames=[Frame(self.lmargin, 5*units.cm, 19*units.cm, 15.5*units.cm, id='table', showBoundary=0)], onPage=self.setup_page) self.doc.addPageTemplates(self.val_template) def setup_page(self, canvas, doc): canvas.saveState() self.do_title(canvas) self.do_client_name(canvas) self.do_date(canvas) self.do_person_bg(canvas) canvas.restoreState() def do_person_bg(self, canvas): canvas.saveState() ref = self.data.person_code + '/' + self.data.business_getter canvas.setFont('Times-Roman', 12) canvas.drawRightString(self.rmargin, 22*units.cm, ref) canvas.restoreState() def do_date(self, canvas): canvas.saveState() canvas.setFont('Times-Roman', 12) dt = time.strptime(self.data.valuation_date, '%Y%m%d') canvas.drawString(self.lmargin, 22*units.cm, datetime.date(*dt[0: 3]).strftime('%dth %B %Y')) canvas.restoreState() def do_title(self, canvas): canvas.saveState() canvas.setFont('Times-Bold', 14) canvas.drawString(self.lmargin, 25*units.cm, 'Portfolio Valuation') canvas.restoreState() def do_client_name(self, canvas): canvas.saveState() canvas.setFont('Times-Bold', 14) canvas.drawString(self.lmargin, 23*units.cm, self.data.name_and_address["client_name"]) canvas.restoreState() def create_pdf(self, data): self.data = data story = [] dta = [[ValuationTable.heading_line(['Description', 'Book Cost', 'Holding', 'Price', 'Value', 'Est. Income', 'Yield (%)'])]] dta.extend(ValuationTable.format_data(self.data.holdings)) dta.extend(ValuationTable.format_cash_lines(self.data.valuation_cash, self.data.name_and_address)) dta.extend(ValuationTable.format_total_lines(self.data.totals)) story.append(ValuationTable(dta)) self.doc.build(story)
def __init__(self, dictComptes={}, dictOptions={}, IDmodele=None, ouverture=True, nomFichier=None): """ Impression """ global DICT_COMPTES, DICT_OPTIONS DICT_COMPTES = dictComptes DICT_OPTIONS = dictOptions # Initialisation du document if nomFichier == None: nomDoc = FonctionsPerso.GenerationNomDoc("RAPPELS", "pdf") else: nomDoc = nomFichier doc = BaseDocTemplate(nomDoc, pagesize=TAILLE_PAGE, showBoundary=False) # Mémorise le ID du modèle modeleDoc = DLG_Noedoc.ModeleDoc(IDmodele=IDmodele) doc.modeleDoc = modeleDoc # Vérifie qu'un cadre principal existe bien dans le document if doc.modeleDoc.FindObjet("cadre_principal") == None: raise Exception( "Votre modele de document doit obligatoirement comporter un cadre principal. Retournez dans l'editeur de document et utilisez pour votre modele la commande 'Inserer un objet special > Inserer le cadre principal'." ) # Importe le template de la première page doc.addPageTemplates(MyPageTemplate(pageSize=TAILLE_PAGE, doc=doc)) story = [] styleSheet = getSampleStyleSheet() h3 = styleSheet['Heading3'] styleTexte = styleSheet['BodyText'] styleTexte.fontName = "Helvetica" styleTexte.fontSize = 9 styleTexte.borderPadding = 9 styleTexte.leading = 12 ## # Définit le template des pages suivantes ## story.append(NextPageTemplate("suivante")) # ----------- Insertion du contenu des frames -------------- listeNomsSansCivilite = [] for IDcompte_payeur, dictCompte in dictComptes.items(): listeNomsSansCivilite.append( (dictCompte["nomSansCivilite"], IDcompte_payeur)) listeNomsSansCivilite.sort() for nomSansCivilite, IDcompte_payeur in listeNomsSansCivilite: dictCompte = dictComptes[IDcompte_payeur] if dictCompte["select"] == True: story.append(DocAssign("IDcompte_payeur", IDcompte_payeur)) nomSansCivilite = dictCompte["nomSansCivilite"] story.append(Bookmark(nomSansCivilite, str(IDcompte_payeur))) # ------------------- TITRE ----------------- dataTableau = [] largeursColonnes = [ TAILLE_CADRE_CONTENU[2], ] dataTableau.append((dictCompte["titre"], )) texteDateReference = DateEngFr(str(datetime.date.today())) dataTableau.append( (_(u"Situation au %s") % texteDateReference, )) style = TableStyle([ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('FONT', (0, 0), (0, 0), "Helvetica-Bold", 19), ('FONT', (0, 1), (0, 1), "Helvetica", 8), ('LINEBELOW', (0, 0), (0, 0), 0.25, colors.black), ('ALIGN', (0, 0), (-1, -1), 'LEFT'), ]) tableau = Table(dataTableau, largeursColonnes) tableau.setStyle(style) story.append(tableau) story.append(Spacer(0, 30)) couleurFond = (0.8, 0.8, 1) couleurFondActivite = (0.92, 0.92, 1) # TEXTE CONTENU paraStyle = ParagraphStyle( name="contenu", fontName="Helvetica", fontSize=11, #leading=7, spaceBefore=0, spaceafter=0, leftIndent=6, rightIndent=6, ) texte = dictCompte["texte"] listeParagraphes = texte.split("</para>") for paragraphe in listeParagraphes: if "<para" in paragraphe: paragraphe = u"%s</para>" % paragraphe textePara = Paragraph(paragraphe, paraStyle) story.append(textePara) if "> </para" in paragraphe: story.append(Spacer(0, 13)) # Saut de page story.append(PageBreak()) # Finalisation du PDF doc.build(story) # Ouverture du PDF if ouverture == True: FonctionsPerso.LanceFichierExterne(nomDoc)
def save(self, flowables, file_h, canvasmaker=canvas.Canvas): BaseDocTemplate.build(self, flowables, filename=file_h, canvasmaker=canvasmaker)
class DFsignaturePDF(object): def __init__(self, name, study_name): self.doc = BaseDocTemplate(name, title=name, showBoundary=0, pagesize=letter) template = PageTemplate('normal', [Frame(inch, inch, 6.5 * inch, 8.4 * inch)], onPageEnd=self.pageHeader) self.doc.addPageTemplates(template) #self.doc.setProgressCallBack(self.progressCB) self.styles = stylesheet() self.jobsize = 1 self.headerId = 0 self.headerVisitLabel = '' self.headerPlateLabel = '' self.studyName = study_name self.outlines = [] self.outlineDesc = None self.outlineVisitLabel = None self.outlineID = 0 self.content = [DFOutlines(self.outlines)] def close(self): self.doc.build(self.content) def setPageHeader(self, pid, visit_label, signature_label): self.headerId = pid self.headerVisitLabel = visit_label self.headerPlateLabel = signature_label def pageHeader(self, canvas, doc): if not self.headerId: return canvas.saveState() #canvas.rect(inch, 9.4*inch, 6.5*inch, 0.6*inch) canvas.setFillColor(black) canvas.setFont('Helvetica-Bold', 10) canvas.drawCentredString(4.25 * inch, 9.5 * inch + 24, 'eSignature Report') canvas.drawCentredString(4.25 * inch, 9.5 * inch + 12, self.studyName) canvas.drawString(inch + 6, 9.5 * inch, 'Patient: {0}'.format(self.headerId)) page_number = 'Page %s' % canvas.getPageNumber() canvas.setFont('Helvetica', 10) canvas.drawCentredString(4.25 * inch, 0.75 * inch, page_number) canvas.restoreState() def progressCB(self, typ, value): if typ == 'SIZE_EST': self.jobsize = value self.lastjobdone = 0 if typ == 'PROGRESS': jobdone = 50 * value // self.jobsize if self.lastjobdone < jobdone: print('Progress: [{0}{1}]'.format('*' * jobdone, ' ' * (50 - jobdone))) self.lastjobdone = jobdone def outputTable(self, label, values): styleH = self.styles['title'] styleN = self.styles['default'] self.content.append(CondPageBreak(2 * inch)) self.content.append(Paragraph(label, styleH)) if not values: self.content.append(Paragraph('No New or Changed Fields.', styleN)) return fieldValueList = [[ Paragraph('<para alignment="right"><b>Plate</b></para>', styleN), Paragraph('<para alignment="right"><b>Field</b></para>', styleN), Paragraph('<b>Description</b>', styleN), Paragraph('<b>Value</b>', styleN) ]] for (plate, field, fdesc, fvalue) in values or []: list_value = self.escape_string(fvalue) if field < 0: field = '-' else: field = str(field) fieldValueList.append([ Paragraph('<para alignment="right">{0}.</para>'.format(plate), styleN), Paragraph('<para alignment="right">{0}.</para>'.format(field), styleN), Paragraph(fdesc, styleN), Paragraph('<para>{0}</para>'.format(list_value), styleN) ]) table = Table(fieldValueList, colWidths=[ 0.1 * 6.3 * inch, 0.1 * 6.3 * inch, 0.3 * 6.3 * inch, 0.5 * 6.3 * inch ], splitByRow=1, repeatRows=1, hAlign='LEFT') tablestyle = TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP'), ('LINEBEFORE', (3, 0), (3, -1), 1, lightgrey), ('LINEABOVE', (0, 0), (-1, -1), 1, lightgrey) ]) table.setStyle(tablestyle) self.content.append(table) def outputSignatureData(self, visit, plate, desc, who, sdate, stime, fieldchanges, signaturevalues): styleH = self.styles['title'] styleN = self.styles['default'] styleR = self.styles['rightheader'] styleB = self.styles['bold'] sdate = sdate[0:4] + '/' + sdate[4:6] + '/' + sdate[6:8] stime = stime[0:2] + ':' + stime[2:4] + ':' + stime[4:6] if desc != self.outlineDesc: self.outlines.append( [desc, 'o{0}'.format(self.outlineID), 0, True]) self.outlineDesc = desc self.outlineVisitLabel = None if self.headerVisitLabel != self.outlineVisitLabel: self.outlines.append([ self.headerVisitLabel, 'o{0}'.format(self.outlineID + 1), 1, True ]) self.outlineVisitLabel = self.headerVisitLabel bookmark = '{0} {1} {2}'.format(sdate, stime, who) self.outlines.append( [bookmark, 'o{0}'.format(self.outlineID + 2), 2, True]) self.content.append( Paragraph( '<a name="o{0}"/><a name="o{1}"/><a name="o{2}"/>Signature Details' .format(self.outlineID, self.outlineID + 1, self.outlineID + 2), styleH)) signatureDetailsList = [] signatureDetailsList.append([ Paragraph('Server Time', styleR), Paragraph('{0} {1}'.format(sdate, stime), styleB) ]) signatureDetailsList.append( [Paragraph('Description', styleR), Paragraph(desc, styleB)]) signatureDetailsList.append( [Paragraph('Login', styleR), Paragraph(who, styleB)]) signatureDetailsList.append([ Paragraph('Visit', styleR), Paragraph('{0} ({1})'.format(visit, self.headerVisitLabel), styleB) ]) signatureDetailsList.append([ Paragraph('Plate', styleR), Paragraph('{0} ({1})'.format(plate, self.headerPlateLabel), styleB) ]) table = Table(signatureDetailsList, colWidths=[0.2 * 6.3 * inch, 0.8 * 6.3 * inch], splitByRow=1, repeatRows=1, hAlign='LEFT') tablestyle = TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP'), ('LINEBEFORE', (1, 0), (1, -1), 1, lightgrey), ('LINEABOVE', (0, 0), (-1, -1), 1, lightgrey) ]) table.setStyle(tablestyle) self.content.append(table) self.outputTable('New or Changed Data Values', fieldchanges) self.outputTable('Signature Field Values', signaturevalues) self.outlineID += 3 def nextPage(self): self.content.append(PageBreak()) ########################################################################### # escape_string - Escape special characters ########################################################################### def escape_string(self, s): s = s.replace('&', '&') s = s.replace('<', '<') s = s.replace('>', '>') return s
def __init__(self, dictComptes={}, dictOptions={}, IDmodele=None, ouverture=True, nomFichier=None): """ Impression """ global DICT_COMPTES, DICT_OPTIONS DICT_COMPTES = dictComptes DICT_OPTIONS = dictOptions # Initialisation du document if nomFichier == None : nomDoc = "Temp/RAPPELS%s.pdf" % FonctionsPerso.GenerationIDdoc() else : nomDoc = nomFichier doc = BaseDocTemplate(nomDoc, pagesize=TAILLE_PAGE, showBoundary=False) # Mémorise le ID du modèle modeleDoc = DLG_Noedoc.ModeleDoc(IDmodele=IDmodele) doc.modeleDoc = modeleDoc # Vérifie qu'un cadre principal existe bien dans le document if doc.modeleDoc.FindObjet("cadre_principal") == None : raise Exception("Votre modèle de document doit obligatoirement comporter un cadre principal. Retournez dans l'éditeur de document et utilisez pour votre modèle la commande 'Insérer un objet spécial > Insérer le cadre principal'.") # Importe le template de la première page doc.addPageTemplates(MyPageTemplate(pageSize=TAILLE_PAGE, doc=doc)) story = [] styleSheet = getSampleStyleSheet() h3 = styleSheet['Heading3'] styleTexte = styleSheet['BodyText'] styleTexte.fontName = "Helvetica" styleTexte.fontSize = 9 styleTexte.borderPadding = 9 styleTexte.leading = 12 ## # Définit le template des pages suivantes ## story.append(NextPageTemplate("suivante")) # ----------- Insertion du contenu des frames -------------- listeNomsSansCivilite = [] for IDcompte_payeur, dictCompte in dictComptes.iteritems() : listeNomsSansCivilite.append((dictCompte["nomSansCivilite"], IDcompte_payeur)) listeNomsSansCivilite.sort() for nomSansCivilite, IDcompte_payeur in listeNomsSansCivilite : dictCompte = dictComptes[IDcompte_payeur] if dictCompte["select"] == True : story.append(DocAssign("IDcompte_payeur", IDcompte_payeur)) nomSansCivilite = dictCompte["nomSansCivilite"] story.append(Bookmark(nomSansCivilite, str(IDcompte_payeur))) # ------------------- TITRE ----------------- dataTableau = [] largeursColonnes = [ TAILLE_CADRE_CONTENU[2], ] dataTableau.append((dictCompte["titre"],)) texteDateReference = DateEngFr(str(datetime.date.today())) dataTableau.append((_(u"Situation au %s") % texteDateReference,)) style = TableStyle([ ('VALIGN', (0,0), (-1,-1), 'MIDDLE'), ('FONT',(0,0),(0,0), "Helvetica-Bold", 19), ('FONT',(0,1),(0,1), "Helvetica", 8), ('LINEBELOW', (0,0), (0,0), 0.25, colors.black), ('ALIGN', (0,0), (-1,-1), 'LEFT'), ]) tableau = Table(dataTableau, largeursColonnes) tableau.setStyle(style) story.append(tableau) story.append(Spacer(0,30)) couleurFond = (0.8, 0.8, 1) couleurFondActivite = (0.92, 0.92, 1) # TEXTE CONTENU paraStyle = ParagraphStyle(name="contenu", fontName="Helvetica", fontSize=11, #leading=7, spaceBefore=0, spaceafter=0, leftIndent=6, rightIndent=6, ) texte = dictCompte["texte"] listeParagraphes = texte.split("</para>") for paragraphe in listeParagraphes : paragraphe = u"%s</para>" % paragraphe textePara = Paragraph(paragraphe, paraStyle) story.append(textePara) if "> </para" in paragraphe : story.append(Spacer(0, 13)) # Saut de page story.append(PageBreak()) # Finalisation du PDF doc.build(story) # Ouverture du PDF if ouverture == True : FonctionsPerso.LanceFichierExterne(nomDoc)
def __init__(self, dictValeurs={}, IDmodele=None, nomDoc=FonctionsPerso.GenerationNomDoc( "RECU_REGLEMENT", "pdf"), afficherDoc=True): """ Impression """ global DICT_VALEURS DICT_VALEURS = dictValeurs # Initialisation du document doc = BaseDocTemplate(nomDoc, pagesize=TAILLE_PAGE, showBoundary=False) # Mémorise le ID du modèle modeleDoc = DLG_Noedoc.ModeleDoc(IDmodele=IDmodele) doc.modeleDoc = modeleDoc # Vérifie qu'un cadre principal existe bien dans le document if doc.modeleDoc.FindObjet("cadre_principal") == None: raise Exception( "Votre modele de document doit obligatoirement comporter un cadre principal. Retournez dans l'editeur de document et utilisez pour votre modele la commande 'Inserer un objet special > Inserer le cadre principal'." ) # Mémorise le ID du modèle modeleDoc = DLG_Noedoc.ModeleDoc(IDmodele=IDmodele) doc.modeleDoc = modeleDoc doc.addPageTemplates(MyPageTemplate(pageSize=TAILLE_PAGE, doc=doc)) story = [] styleSheet = getSampleStyleSheet() h3 = styleSheet['Heading3'] styleTexte = styleSheet['BodyText'] styleTexte.fontName = "Helvetica" styleTexte.fontSize = 9 styleTexte.borderPadding = 9 styleTexte.leading = 12 ## # Définit le template des pages suivantes ## story.append(NextPageTemplate("suivante")) # ----------- Insertion du contenu des frames -------------- # ------------------- TITRE ----------------- dataTableau = [] largeursColonnes = [ TAILLE_CADRE_CONTENU[2], ] dataTableau.append((_(u"Reçu de règlement"), )) dataTableau.append((u"", )) style = TableStyle([ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('FONT', (0, 0), (0, 0), "Helvetica-Bold", 19), ('FONT', (0, 1), (0, 1), "Helvetica", 8), ('LINEBELOW', (0, 0), (0, 0), 0.25, colors.black), ('ALIGN', (0, 0), (-1, -1), 'LEFT'), ]) tableau = Table(dataTableau, largeursColonnes) tableau.setStyle(style) story.append(tableau) story.append(Spacer(0, 10)) # TEXTE D'INTRODUCTION paraStyleIntro = ParagraphStyle( name="intro", fontName="Helvetica", fontSize=11, leading=14, spaceBefore=0, spaceafter=0, leftIndent=0, rightIndent=0, alignment=0, ) if DICT_VALEURS["intro"] != None: texteIntro = DICT_VALEURS["intro"] story.append(Paragraph(u"<i>%s</i>" % texteIntro, paraStyleIntro)) story.append(Spacer(0, 20)) couleurFond = (0.8, 0.8, 1) # ------------------- TABLEAU CONTENU ----------------- dataTableau = [] largeursColonnes = [120, 280] paraStyle = ParagraphStyle( name="detail", fontName="Helvetica-Bold", fontSize=9, ) dataTableau.append((_(u"Caractéristiques du règlement"), "")) montantEnLettres = UTILS_Conversion.trad(DICT_VALEURS["montant"], MONNAIE_SINGULIER, MONNAIE_DIVISION).strip() dataTableau.append((_(u"Montant du règlement :"), Paragraph(montantEnLettres.capitalize(), paraStyle))) dataTableau.append((_(u"Mode de règlement :"), Paragraph(DICT_VALEURS["nomMode"], paraStyle))) dataTableau.append((_(u"Nom du payeur :"), Paragraph(DICT_VALEURS["nomPayeur"], paraStyle))) if DICT_VALEURS["nomEmetteur"] != None: dataTableau.append((_(u"Nom de l'émetteur :"), Paragraph(DICT_VALEURS["nomEmetteur"], paraStyle))) if DICT_VALEURS["numPiece"] not in ("", None): dataTableau.append((_(u"Numéro de pièce :"), Paragraph(DICT_VALEURS["numPiece"], paraStyle))) style = TableStyle([ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('FONT', (0, 0), (0, -1), "Helvetica", 9), ('FONT', (1, 0), (1, -1), "Helvetica-Bold", 9), ('GRID', (0, 0), (-1, -1), 0.25, colors.black), ('ALIGN', (0, 1), (0, -1), 'RIGHT'), ('ALIGN', (1, 1), (1, -1), 'LEFT'), ('FONT', (0, 0), (0, 0), "Helvetica", 7), ('SPAN', (0, 0), (-1, 0)), ('BACKGROUND', (0, 0), (-1, 0), couleurFond), ]) tableau = Table(dataTableau, largeursColonnes) tableau.setStyle(style) story.append(tableau) # --------------------- LISTE DES PRESTATIONS ---------------- listePrestations = dictValeurs["prestations"] if len(listePrestations) > 0: story.append(Spacer(0, 20)) textePrestations = _(u"En paiement des prestations suivantes :") story.append( Paragraph(u"<i>%s</i>" % textePrestations, paraStyleIntro)) story.append(Spacer(0, 20)) dataTableau = [ (_(u"Date"), _(u"Activité"), _(u"Individu"), _(u"Intitulé"), _(u"Part utilisée")), ] largeursColonnes = [50, 95, 70, 135, 50] paraStyle = ParagraphStyle( name="detail", fontName="Helvetica", fontSize=7, leading=7, spaceBefore=0, spaceAfter=0, ) for dictPrestation in listePrestations: date = UTILS_Dates.DateDDEnFr(dictPrestation["date"]) activite = dictPrestation["nomActivite"] individu = dictPrestation["prenomIndividu"] label = dictPrestation["label"] montant = dictPrestation["montant"] ventilation = dictPrestation["ventilation"] dataTableau.append(( Paragraph(u"<para align='center'>%s</para>" % date, paraStyle), Paragraph(activite, paraStyle), Paragraph(individu, paraStyle), Paragraph(label, paraStyle), Paragraph( u"<para align='right'>%.2f %s</para>" % (ventilation, SYMBOLE), paraStyle), )) style = TableStyle([ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('GRID', (0, 0), (-1, -1), 0.25, colors.black), ('FONT', (0, 0), (-1, -1), "Helvetica", 7), ('TOPPADDING', (0, 1), (-1, -1), 1), ('BOTTOMPADDING', (0, 1), (-1, -1), 3), # Ligne Entetes ('FONT', (0, 0), (-1, 0), "Helvetica", 7), ('BACKGROUND', (0, 0), (-1, 0), couleurFond), ('ALIGN', (0, 0), (-1, 0), 'CENTER'), ]) tableau = Table(dataTableau, largeursColonnes) tableau.setStyle(style) story.append(tableau) # Enregistrement et ouverture du PDF try: doc.build(story) except Exception, err: print "Erreur dans ouverture PDF :", err if "Permission denied" in err: dlg = wx.MessageDialog( None, _(u"Noethys ne peut pas créer le PDF.\n\nVeuillez vérifier qu'un autre PDF n'est pas déjà ouvert en arrière-plan..." ), _(u"Erreur d'édition"), wx.OK | wx.ICON_ERROR) dlg.ShowModal() dlg.Destroy() return
def __init__(self, dictValeurs={}, IDmodele=None, nomDoc=FonctionsPerso.GenerationNomDoc("INSCRIPTION", "pdf"), afficherDoc=True): """ Impression """ global DICT_VALEURS DICT_VALEURS = dictValeurs # Initialisation du document doc = BaseDocTemplate(nomDoc, pagesize=TAILLE_PAGE, showBoundary=False) # Mémorise le ID du modèle modeleDoc = DLG_Noedoc.ModeleDoc(IDmodele=IDmodele) doc.modeleDoc = modeleDoc doc.addPageTemplates(MyPageTemplate(pageSize=TAILLE_PAGE, doc=doc)) story = [] styleSheet = getSampleStyleSheet() h3 = styleSheet['Heading3'] styleTexte = styleSheet['BodyText'] styleTexte.fontName = "Helvetica" styleTexte.fontSize = 9 styleTexte.borderPadding = 9 styleTexte.leading = 12 couleurFond = (0.8, 0.8, 1) # ----------- Insertion du contenu des frames -------------- cadre_principal = doc.modeleDoc.FindObjet("cadre_principal") if cadre_principal != None: if DICT_VALEURS["intro"] != None or DICT_VALEURS["tableau"] == True: # ------------------- TITRE ----------------- dataTableau = [] largeursColonnes = [ TAILLE_CADRE_CONTENU[2], ] dataTableau.append((_(u"Confirmation d'inscription"), )) dataTableau.append((u"", )) style = TableStyle([ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('FONT', (0, 0), (0, 0), "Helvetica-Bold", 19), ('FONT', (0, 1), (0, 1), "Helvetica", 8), ('LINEBELOW', (0, 0), (0, 0), 0.25, colors.black), ('ALIGN', (0, 0), (-1, -1), 'LEFT'), ]) tableau = Table(dataTableau, largeursColonnes) tableau.setStyle(style) story.append(tableau) story.append(Spacer(0, 10)) # TEXTE D'INTRODUCTION paraStyleIntro = ParagraphStyle( name="intro", fontName="Helvetica", fontSize=11, leading=14, spaceBefore=0, spaceafter=0, leftIndent=0, rightIndent=0, alignment=0, ) if DICT_VALEURS["intro"] != None: texteIntro = DICT_VALEURS["intro"] story.append( Paragraph(u"<i>%s</i>" % texteIntro, paraStyleIntro)) story.append(Spacer(0, 20)) if DICT_VALEURS["tableau"] == True: # ------------------- TABLEAU CONTENU ----------------- dataTableau = [] largeursColonnes = [80, 280] paraStyle = ParagraphStyle( name="detail", fontName="Helvetica-Bold", fontSize=9, ) dataTableau.append((_(u"Nom"), Paragraph(DICT_VALEURS["{INDIVIDU_NOM}"], paraStyle))) dataTableau.append( (_(u"Prénom"), Paragraph(DICT_VALEURS["{INDIVIDU_PRENOM}"], paraStyle))) dataTableau.append( (_(u"Activité"), Paragraph(DICT_VALEURS["{ACTIVITE_NOM_LONG}"], paraStyle))) dataTableau.append( (_(u"Groupe"), Paragraph(DICT_VALEURS["{GROUPE_NOM_LONG}"], paraStyle))) dataTableau.append( (_(u"Catégorie"), Paragraph(DICT_VALEURS["{NOM_CATEGORIE_TARIF}"], paraStyle))) style = TableStyle([ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('FONT', (0, 0), (0, -1), "Helvetica", 9), ('GRID', (0, 0), (-1, -1), 0.25, colors.black), ('ALIGN', (0, 0), (0, -1), 'RIGHT'), ]) tableau = Table(dataTableau, largeursColonnes) tableau.setStyle(style) story.append(tableau) # Si aucune frame principale if len(story) == 0: story.append(Spacer(0, 20)) # Enregistrement et ouverture du PDF try: doc.build(story) except Exception, err: print "Erreur dans ouverture PDF :", err if "Permission denied" in err: dlg = wx.MessageDialog( None, _(u"Noethys ne peut pas créer le PDF.\n\nVeuillez vérifier qu'un autre PDF n'est pas déjà ouvert en arrière-plan..." ), _(u"Erreur d'édition"), wx.OK | wx.ICON_ERROR) dlg.ShowModal() dlg.Destroy() return
def __init__(self, dictValeurs={}, dictOptions={}, IDmodele=None, ouverture=True, nomFichier=None): """ Impression """ global DICT_VALEURS, DICT_OPTIONS DICT_VALEURS = dictValeurs DICT_OPTIONS = dictOptions # Initialisation du document if nomFichier == None: nomDoc = FonctionsPerso.GenerationNomDoc("COTISATIONS", "pdf") else: nomDoc = nomFichier doc = BaseDocTemplate(nomDoc, pagesize=TAILLE_PAGE, showBoundary=False) # Mémorise le ID du modèle modeleDoc = DLG_Noedoc.ModeleDoc(IDmodele=IDmodele) doc.modeleDoc = modeleDoc # Importe le template de la première page doc.addPageTemplates(MyPageTemplate(pageSize=TAILLE_PAGE, doc=doc)) story = [] styleSheet = getSampleStyleSheet() h3 = styleSheet['Heading3'] styleTexte = styleSheet['BodyText'] styleTexte.fontName = "Helvetica" styleTexte.fontSize = 9 styleTexte.borderPadding = 9 styleTexte.leading = 12 # ----------- Insertion du contenu des frames -------------- listeLabels = [] for IDcotisation, dictValeur in dictValeurs.iteritems(): listeLabels.append((dictValeur["{FAMILLE_NOM}"], IDcotisation)) listeLabels.sort() for labelDoc, IDcotisation in listeLabels: dictValeur = dictValeurs[IDcotisation] if dictValeur["select"] == True: story.append(DocAssign("IDcotisation", IDcotisation)) nomSansCivilite = dictValeur["{FAMILLE_NOM}"] story.append(Bookmark(nomSansCivilite, str(IDcotisation))) ## # ------------------- TITRE ----------------- ## dataTableau = [] ## largeursColonnes = [ TAILLE_CADRE_CONTENU[2], ] ## dataTableau.append((dictCompte["titre"],)) ## texteDateReference = UTILS_Dates.DateEngFr(str(datetime.date.today())) ## dataTableau.append((_(u"Situation au %s") % texteDateReference,)) ## style = TableStyle([ ## ('VALIGN', (0,0), (-1,-1), 'MIDDLE'), ## ('FONT',(0,0),(0,0), "Helvetica-Bold", 19), ## ('FONT',(0,1),(0,1), "Helvetica", 8), ## ('LINEBELOW', (0,0), (0,0), 0.25, colors.black), ## ('ALIGN', (0,0), (-1,-1), 'LEFT'), ## ]) ## tableau = Table(dataTableau, largeursColonnes) ## tableau.setStyle(style) ## story.append(tableau) ## story.append(Spacer(0,30)) ## ## ## couleurFond = (0.8, 0.8, 1) ## couleurFondActivite = (0.92, 0.92, 1) ## ## # TEXTE CONTENU ## paraStyle = ParagraphStyle(name="contenu", ## fontName="Helvetica", ## fontSize=11, ## #leading=7, ## spaceBefore=0, ## spaceafter=0, ## leftIndent=6, ## rightIndent=6, ## ) ## ## texte = dictCompte["texte"] ## listeParagraphes = texte.split("</para>") ## for paragraphe in listeParagraphes : ## textePara = Paragraph(u"%s</para>" % paragraphe, paraStyle) ## story.append(textePara) # Saut de page story.append(PageBreak()) # Finalisation du PDF doc.build(story) # Ouverture du PDF if ouverture == True: FonctionsPerso.LanceFichierExterne(nomDoc)
def __init__(self, dictComptes={}, dictOptions={}, IDmodele=None, ouverture=True, nomFichier=None): """ Impression """ global DICT_COMPTES, DICT_OPTIONS DICT_COMPTES = dictComptes DICT_OPTIONS = dictOptions # Initialisation du document if nomFichier == None: nomDoc = FonctionsPerso.GenerationNomDoc("ATTESTATIONS_FISCALES", "pdf") else: nomDoc = nomFichier doc = BaseDocTemplate(nomDoc, pagesize=TAILLE_PAGE, showBoundary=False) # Mémorise le ID du modèle modeleDoc = DLG_Noedoc.ModeleDoc(IDmodele=IDmodele) doc.modeleDoc = modeleDoc # Vérifie qu'un cadre principal existe bien dans le document if doc.modeleDoc.FindObjet("cadre_principal") == None: raise Exception( "Votre modele de document doit obligatoirement comporter un cadre principal. Retournez dans l'editeur de document et utilisez pour votre modele la commande 'Inserer un objet special > Inserer le cadre principal'." ) # Mémorise le ID du modèle modeleDoc = DLG_Noedoc.ModeleDoc(IDmodele=IDmodele) doc.modeleDoc = modeleDoc # Importe le template de la première page doc.addPageTemplates(MyPageTemplate(pageSize=TAILLE_PAGE, doc=doc)) story = [] styleSheet = getSampleStyleSheet() h3 = styleSheet['Heading3'] styleTexte = styleSheet['BodyText'] styleTexte.fontName = "Helvetica" styleTexte.fontSize = 9 styleTexte.borderPadding = 9 styleTexte.leading = 12 ## # Définit le template des pages suivantes ## story.append(NextPageTemplate("suivante")) # ----------- Insertion du contenu des frames -------------- listeNomsSansCivilite = [] for IDcompte_payeur, dictCompte in dictComptes.items(): listeNomsSansCivilite.append( (dictCompte["{FAMILLE_NOM}"], IDcompte_payeur)) listeNomsSansCivilite.sort() for nomSansCivilite, IDcompte_payeur in listeNomsSansCivilite: dictCompte = dictComptes[IDcompte_payeur] story.append(DocAssign("IDcompte_payeur", IDcompte_payeur)) nomSansCivilite = dictCompte["{FAMILLE_NOM}"] story.append(Bookmark(nomSansCivilite, str(IDcompte_payeur))) # ------------------- TITRE ----------------- dataTableau = [] largeursColonnes = [ TAILLE_CADRE_CONTENU[2], ] dataTableau.append((dictOptions["titre"], )) texteDateReference = UTILS_Dates.DateEngFr( str(datetime.date.today())) dataTableau.append( (_(u"Période du %s au %s") % (UTILS_Dates.DateDDEnFr(dictOptions["date_debut"]), UTILS_Dates.DateDDEnFr(dictOptions["date_fin"])), )) style = TableStyle([ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('FONT', (0, 0), (0, 0), "Helvetica-Bold", 19), ('FONT', (0, 1), (0, 1), "Helvetica", 8), ('LINEBELOW', (0, 0), (0, 0), 0.25, colors.black), ('ALIGN', (0, 0), (-1, -1), 'LEFT'), ]) tableau = Table(dataTableau, largeursColonnes) tableau.setStyle(style) story.append(tableau) story.append(Spacer(0, 30)) couleurFond = (0.8, 0.8, 1) couleurFondActivite = (0.92, 0.92, 1) # TEXTE CONTENU paraStyle = ParagraphStyle( name="contenu", fontName="Helvetica", fontSize=11, leading=16, spaceBefore=0, spaceafter=0, leftIndent=6, rightIndent=6, ) # INTRO texte = dictCompte["{INTRO}"] if texte != "": listeParagraphes = texte.split("</para>") for paragraphe in listeParagraphes: textePara = Paragraph(u"%s" % paragraphe, paraStyle) story.append(textePara) story.append(Spacer(0, 25)) # DETAIL par enfant dataTableau = [ (_(u"Nom et prénom"), _(u"Date de naissance"), _(u"Montant")), ] largeursColonnes = [220, 80, 80] paraStyle = ParagraphStyle( name="detail", fontName="Helvetica-Bold", fontSize=9, ) for nomCompletIndividu, dictIndividu in dictCompte["individus"]: dataTableau.append( (nomCompletIndividu, dictIndividu["date_naiss"], u"%.2f %s" % (dictIndividu["regle"], SYMBOLE))) dataTableau.append(("", "Total :", dictCompte["{MONTANT_REGLE}"])) style = TableStyle([ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('GRID', (0, 0), (-1, -2), 0.25, colors.black), ('FONT', (0, 0), (-1, 0), "Helvetica", 6), ('FONT', (0, 1), (-1, -1), "Helvetica", 10), ('TOPPADDING', (0, 1), (-1, -2), 10), ('BOTTOMPADDING', (0, 1), (-1, -2), 10), ('GRID', (-1, -1), (-1, -1), 0.25, colors.black), ('FONT', (-1, -1), (-1, -1), "Helvetica-Bold", 10), ('ALIGN', (-2, -1), (-2, -1), 'RIGHT'), ('FONT', (-2, -1), (-2, -1), "Helvetica", 6), ]) tableau = Table(dataTableau, largeursColonnes) tableau.setStyle(style) story.append(tableau) # Saut de page story.append(PageBreak()) # Finalisation du PDF doc.build(story) # Ouverture du PDF if ouverture == True: FonctionsPerso.LanceFichierExterne(nomDoc)
def render_to_reportlab(context): """ In context dictionary we could have a 'fattura' or a list of fatture in 'fatture'. Everything will be appended to a pdf returned as Django response. To reset page counter between different invoices, we'll use 2 "Normale" templates, one for even and one for odds, so every times the template changes we'll reset the NumberedCanvas """ if "fattura" in context and "fatture" in context: raise Exception( "Please create PDF choosing between a fattura or multiple fatture") if "fattura" in context: fatture = [context.get('fattura')] else: fatture = context.get('fatture') response = http.HttpResponse(content_type='application/pdf') NormalTemplates = ['Normale0', 'Normale1'] fatture_rimanenti = len(fatture) story = [] pageTemplates = [ PageTemplate(id='Normale0', onPage=onPageNormal), PageTemplate(id='Normale1', onPage=onPageNormal), PageTemplate(id='ConducenteConsorzio', onPage=onPageConducenteConsorzio), PageTemplate(id='ConsorzioConducente', onPage=onPageConsorzioConducente), ] # scelgo il template della prima pagina come primo della lista if fatture[0].is_ricevuta_sdoppiata(): lastTemplateID = 'ConducenteConsorzio' pageTemplates = pageTemplates[2:] + pageTemplates[:2] else: lastTemplateID = 'Normale0' width, height = portrait(A4) doc = BaseDocTemplate( response, pagesize=(width, height), leftMargin=1 * cm, rightMargin=1 * cm, bottomMargin=1.5 * cm, topMargin=1 * cm, showBoundary=test, pageTemplates=pageTemplates, ) doc.fatture = fatture doc.lastTemplateID = lastTemplateID doc.fattura_corrente = 0 for fattura in fatture: ricevutaMultipla = fattura.is_ricevuta_sdoppiata() story_fattura = [] fatturazione = FATTURE_PER_TIPO[fattura.tipo] righeFattura = [ ('Descrizione', 'Q.tà', 'Prezzo', 'IVA %', 'Importo'), ] righe = fattura.righe.all() raggruppa_barbatrucco = False if fatturazione.codice == "5": totale = sum([r.val_totale() for r in righe]) conducente = righe[0].conducente if righe else None if "Imposta di bollo" not in [r.descrizione for r in righe]: if not (totale < settings.MIN_PRICE_FOR_TAXSTAMP and (conducente is None or conducente.emette_ricevute)): raggruppa_barbatrucco = True if raggruppa_barbatrucco: # print "5 esente iva con barbatrucco" netto = totale / Decimal(1.1) class RigaTotaleIvata(object ): # una riga che fa corrispondere il totale descrizione = "Servizi per consorzio." note = None qta = 1 prezzo = netto iva = 10 def val_imponibile(self): return self.prezzo def val_iva(self): return totale - netto def val_totale(self): return totale riga = RigaTotaleIvata() # la fattura ha totale pari al totale di tutte le righe # l'iva è fissa al 10% e il netto è calcolato di conseguenza imponibile = netto iva = totale - netto righe = [riga] else: imponibile = fattura.val_imponibile() iva = fattura.val_iva() for riga in righe: descrizione = riga.descrizione if riga.note: descrizione += " (%s)" % riga.note righeFattura.append( (Paragraph(descrizione, normalStyle), Paragraph("%s" % riga.qta, normalStyle), moneyfmt(riga.prezzo), riga.iva, moneyfmt(riga.val_totale()))) righeTotali = [] righeTotali.append(('Imponibile', moneyfmt(imponibile))) righeTotali.append(('IVA', moneyfmt(iva))) righeTotali.append(('TOTALE', moneyfmt(fattura.val_totale()))) righeStyle = TableStyle([ ('VALIGN', (0, 0), (-1, -1), 'TOP'), ('ALIGN', (0, 0), (-1, -1), 'RIGHT'), # globalmente allineato a destra... ('ALIGN', (0, 0), (1, -1), 'LEFT'), # tranne la prima colonna (con la descrizione) ('GRID', (0, 1), (-1, -1), 0.1, colors.grey), ('FACE', (0, 0), (-1, -1), 'Helvetica'), ('FACE', (0, 0), (-1, 0), 'Helvetica-Bold'), # header ('SIZE', (0, 0), (-1, -1), 8), # ('SPAN', (0, -1), (3, -1)), # anziché mettere lo span qui aggiungo in coda una tabella diversa ]) totaliStyle = TableStyle([ ('ALIGN', (0, 0), (-1, -1), 'RIGHT'), ('GRID', (-1, 0), (-1, -1), 0.1, colors.grey), ('FACE', (0, 0), (-1, -1), 'Helvetica'), # header ('FACE', (0, -1), (-1, -1), 'Helvetica-Bold'), # Totale ('SIZE', (0, 0), (-1, -1), 8), ]) colWidths = ((width - doc.leftMargin - doc.rightMargin) - (1.6 * 4) * cm, ) + (1.6 * cm, ) * 4 story_fattura = [ Table(righeFattura, style=righeStyle, repeatRows=1, colWidths=colWidths) ] story_fattura.append( KeepTogether( Table(righeTotali, style=totaliStyle, colWidths=(width - doc.leftMargin - doc.rightMargin - 1.6 * cm, 1.6 * cm)))) if ricevutaMultipla: # le ricevute si raddoppiano con 2 template diversi # raddoppio lo story di questa fattura cambiando template story_fattura = story_fattura + [ NextPageTemplate("ConsorzioConducente"), PageBreak() ] + story_fattura fatture_rimanenti -= 1 if fatture_rimanenti: story_fattura += [ NextPageTemplate(NormalTemplates[-1]), PageBreak() ] NormalTemplates.reverse() # reverse current, next normal template story = story + story_fattura doc.build(story, canvasmaker=NumberedCanvas) return response
def __init__(self, dictValeurs={}, dictOptions={}, IDmodele=None, ouverture=True, nomFichier=None): """ Impression """ global DICT_VALEURS, DICT_OPTIONS DICT_VALEURS = dictValeurs DICT_OPTIONS = dictOptions # Initialisation du document if nomFichier == None: nomDoc = FonctionsPerso.GenerationNomDoc("INSCRIPTIONS", "pdf") else: nomDoc = nomFichier doc = BaseDocTemplate(nomDoc, pagesize=TAILLE_PAGE, showBoundary=False) # Mémorise le ID du modèle modeleDoc = DLG_Noedoc.ModeleDoc(IDmodele=IDmodele) doc.modeleDoc = modeleDoc # Importe le template de la première page doc.addPageTemplates(MyPageTemplate(pageSize=TAILLE_PAGE, doc=doc)) story = [] styleSheet = getSampleStyleSheet() h3 = styleSheet['Heading3'] styleTexte = styleSheet['BodyText'] styleTexte.fontName = "Helvetica" styleTexte.fontSize = 9 styleTexte.borderPadding = 9 styleTexte.leading = 12 # ----------- Insertion du contenu des frames -------------- listeLabels = [] for IDinscription, dictValeur in dictValeurs.items(): listeLabels.append((dictValeur["{FAMILLE_NOM}"], IDinscription)) listeLabels.sort() for labelDoc, IDinscription in listeLabels: dictValeur = dictValeurs[IDinscription] if dictValeur["select"] == True: story.append(DocAssign("IDinscription", IDinscription)) nomSansCivilite = dictValeur["{FAMILLE_NOM}"] story.append(Bookmark(nomSansCivilite, str(IDinscription))) # ----------- Insertion du cadre principal -------------- cadre_principal = doc.modeleDoc.FindObjet("cadre_principal") if cadre_principal != None: if "intro" in DICT_OPTIONS and DICT_OPTIONS[ "intro"] != None or "tableau" in DICT_OPTIONS and DICT_VALEURS[ "tableau"] == True: # ------------------- TITRE ----------------- dataTableau = [] largeursColonnes = [ TAILLE_CADRE_CONTENU[2], ] dataTableau.append( (_(u"Confirmation d'inscription"), )) dataTableau.append((u"", )) style = TableStyle([ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('FONT', (0, 0), (0, 0), "Helvetica-Bold", 19), ('FONT', (0, 1), (0, 1), "Helvetica", 8), ('LINEBELOW', (0, 0), (0, 0), 0.25, colors.black), ('ALIGN', (0, 0), (-1, -1), 'LEFT'), ]) tableau = Table(dataTableau, largeursColonnes) tableau.setStyle(style) story.append(tableau) story.append(Spacer(0, 10)) # TEXTE D'INTRODUCTION paraStyleIntro = ParagraphStyle( name="intro", fontName="Helvetica", fontSize=11, leading=14, spaceBefore=0, spaceafter=0, leftIndent=0, rightIndent=0, alignment=0, ) if "intro" in DICT_OPTIONS and DICT_OPTIONS[ "intro"] != None: texteIntro = DICT_VALEURS["intro"] story.append( Paragraph(u"<i>%s</i>" % texteIntro, paraStyleIntro)) story.append(Spacer(0, 20)) if "tableau" in DICT_OPTIONS and DICT_OPTIONS[ "tableau"] == True: # ------------------- TABLEAU CONTENU ----------------- dataTableau = [] largeursColonnes = [80, 280] paraStyle = ParagraphStyle( name="detail", fontName="Helvetica-Bold", fontSize=9, ) dataTableau.append( (_(u"Nom"), Paragraph(DICT_VALEURS["{INDIVIDU_NOM}"], paraStyle))) dataTableau.append( (_(u"Prénom"), Paragraph(DICT_VALEURS["{INDIVIDU_PRENOM}"], paraStyle))) dataTableau.append( (_(u"Activité"), Paragraph(DICT_VALEURS["{ACTIVITE_NOM_LONG}"], paraStyle))) dataTableau.append( (_(u"Groupe"), Paragraph(DICT_VALEURS["{GROUPE_NOM_LONG}"], paraStyle))) dataTableau.append( (_(u"Catégorie"), Paragraph(DICT_VALEURS["{NOM_CATEGORIE_TARIF}"], paraStyle))) style = TableStyle([ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('FONT', (0, 0), (0, -1), "Helvetica", 9), ('GRID', (0, 0), (-1, -1), 0.25, colors.black), ('ALIGN', (0, 0), (0, -1), 'RIGHT'), ]) tableau = Table(dataTableau, largeursColonnes) tableau.setStyle(style) story.append(tableau) # Saut de page story.append(PageBreak()) # Finalisation du PDF doc.build(story) # Ouverture du PDF if ouverture == True: FonctionsPerso.LanceFichierExterne(nomDoc)
def Impression(self, listeActivites, listePeriodes): # Création du PDF self.taille_page = A4 self.orientation = "PORTRAIT" if self.orientation == "PORTRAIT" : self.hauteur_page = self.taille_page[1] self.largeur_page = self.taille_page[0] else: self.hauteur_page = self.taille_page[0] self.largeur_page = self.taille_page[1] # Création des conditions pour les requêtes SQL conditionsPeriodes = GetSQLdates(listePeriodes) if len(listeActivites) == 0 : conditionActivites = "()" elif len(listeActivites) == 1 : conditionActivites = "(%d)" % listeActivites[0] else : conditionActivites = str(tuple(listeActivites)) # Récupération des individus grâce à leurs consommations self.EcritStatusBar(_(u"Recherche des individus...")) DB = GestionDB.DB() req = """SELECT individus.IDindividu, IDcivilite, nom, prenom, date_naiss FROM consommations LEFT JOIN individus ON individus.IDindividu = consommations.IDindividu WHERE etat IN ("reservation", "present") AND IDactivite IN %s AND %s GROUP BY individus.IDindividu ORDER BY nom, prenom ;""" % (conditionActivites, conditionsPeriodes) DB.ExecuterReq(req) listeIndividus = DB.ResultatReq() DB.Close() if len(listeIndividus) == 0 : dlg = wx.MessageDialog(self, _(u"Aucun individu n'a été trouvé avec les paramètres spécifiés !"), _(u"Erreur"), wx.OK | wx.ICON_EXCLAMATION) dlg.ShowModal() dlg.Destroy() self.EcritStatusBar(u"") return dictIndividus = {} listeIDindividus = [] dictAnniversaires = {} self.EcritStatusBar(_(u"Recherche des dates de naissance...")) for IDindividu, IDcivilite, nom, prenom, date_naiss in listeIndividus : if date_naiss != None : date_naiss = DateEngEnDateDD(date_naiss) age = GetAge(date_naiss) jour = date_naiss.day mois = date_naiss.month # Mémorisation de l'individu dictIndividus[IDindividu] = { "IDcivilite" : IDcivilite, "nom" : nom, "prenom" : prenom, "age" : age, "date_naiss" : date_naiss, } # Mémorisation du IDindividu if dictAnniversaires.has_key(mois) == False : dictAnniversaires[mois] = {} if dictAnniversaires[mois].has_key(jour) == False : dictAnniversaires[mois][jour] = [] dictAnniversaires[mois][jour].append(IDindividu) if IDindividu not in listeIDindividus : listeIDindividus.append(IDindividu) # Récupération des photos individuelles dictPhotos = {} taillePhoto = 128 if self.ctrl_photos.GetSelection() == 0 : tailleImageFinal = 16 if self.ctrl_photos.GetSelection() == 1 : tailleImageFinal = 32 if self.ctrl_photos.GetSelection() == 2 : tailleImageFinal = 64 if self.check_photos.GetValue() == True : index = 0 for IDindividu in listeIDindividus : self.EcritStatusBar(_(u"Recherche des photos... %d/%d") % (index, len(listeIDindividus))) IDcivilite = dictIndividus[IDindividu]["IDcivilite"] nomFichier = Chemins.GetStaticPath("Images/128x128/%s" % DICT_CIVILITES[IDcivilite]["nomImage"]) IDphoto, bmp = CTRL_Photo.GetPhoto(IDindividu=IDindividu, nomFichier=nomFichier, taillePhoto=(taillePhoto, taillePhoto), qualite=100) # Création de la photo dans le répertoire Temp nomFichier = UTILS_Fichiers.GetRepTemp(fichier="photoTmp%d.jpg" % IDindividu) bmp.SaveFile(nomFichier, type=wx.BITMAP_TYPE_JPEG) img = Image(nomFichier, width=tailleImageFinal, height=tailleImageFinal) dictPhotos[IDindividu] = img index += 1 # ---------------- Création du PDF ------------------- self.EcritStatusBar(_(u"Création du PDF...")) # Initialisation du PDF nomDoc = FonctionsPerso.GenerationNomDoc("ANNIVERSAIRES", "pdf") if sys.platform.startswith("win") : nomDoc = nomDoc.replace("/", "\\") doc = BaseDocTemplate(nomDoc, pagesize=(self.largeur_page, self.hauteur_page), topMargin=30, bottomMargin=30, showBoundary=False) doc.addPageTemplates(MyPageTemplate(pageSize=(self.largeur_page, self.hauteur_page))) story = [] # Mois listeMois = dictAnniversaires.keys() listeMois.sort() for numMois in listeMois : # Mémorise le numéro de mois pour le titre de la page nomMois = LISTE_NOMS_MOIS[numMois-1] story.append(DocAssign("numMois", numMois)) # Jours dictJours = dictAnniversaires[numMois] listeJours = dictJours.keys() listeJours.sort() for numJour in listeJours : # Initialisation du tableau dataTableau = [] largeursColonnes = [] # Recherche des entêtes de colonnes : if self.check_photos.GetValue() == True : largeursColonnes.append(tailleImageFinal+6) # Colonne nom de l'individu largeursColonnes.append(LARGEUR_COLONNE-sum(largeursColonnes)) # Label numéro de jour ligne = [] ligne.append(str(numJour)) if self.check_photos.GetValue() == True : ligne.append(u"") dataTableau.append(ligne) # Individus listeIndividus = dictAnniversaires[numMois][numJour] for IDindividu in listeIndividus : ligne = [] # Photo if self.check_photos.GetValue() == True and IDindividu in dictPhotos : img = dictPhotos[IDindividu] ligne.append(img) # Nom nom = dictIndividus[IDindividu]["nom"] prenom = dictIndividus[IDindividu]["prenom"] ligne.append(u"%s %s" % (nom, prenom)) # Ajout de la ligne individuelle dans le tableau dataTableau.append(ligne) couleurFondJour = (0.8, 0.8, 1) # Vert -> (0.5, 1, 0.2) couleurFondTableau = (1, 1, 1) style = TableStyle([ ('VALIGN', (0,0), (-1,-1), 'MIDDLE'), # Centre verticalement toutes les cases ('BACKGROUND', (0,0), (-1,-1), couleurFondTableau), # Donne la couleur de fond du titre de groupe ('FONT',(0,0),(-1,-1), "Helvetica", 7), # Donne la police de caract. + taille de police ('GRID', (0,0), (-1,-1), 0.25, colors.black), # Crée la bordure noire pour tout le tableau ('ALIGN', (0,1), (-1,-1), 'CENTRE'), # Centre les cases ('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), couleurFondJour), # Donne la couleur de fond du titre de groupe ]) # Création du tableau tableau = Table(dataTableau, largeursColonnes) tableau.setStyle(style) story.append(tableau) story.append(Spacer(0, 10)) # Saut de page après un mois story.append(PageBreak()) # Enregistrement du PDF doc.build(story) # Affichage du PDF FonctionsPerso.LanceFichierExterne(nomDoc) self.EcritStatusBar(u"")
def report(fname, shot, versions): # pdf properties title = "Report" author = "Rob Blau" # define frames for page layout page = PageTemplate(frames=[ Frame(x1=0.1*inch, y1=8.9*inch, width=3*inch, height=2*inch), # shot thumbnail Frame(x1=0.1*inch, y1=0.1*inch, width=8.3*inch, height=4*inch), # versions table ]) # create the doc doc = BaseDocTemplate( fname, pagesize=letter, pageTemplates=page, title=title, author=author, ) # styles styles = reportlab.lib.styles.getSampleStyleSheet() # content story = [] # shot thumbnail data = [['Shot Thumbnail'], [get_image(shot['image'], 3*inch, 1.5*inch)]] shot_thumbnail = Table(data, colWidths=3*inch) shot_thumbnail.setStyle(TableStyle([ ('BOX', (0,0), (-1,-1), 0.25, colors.black), ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('TEXTCOLOR', (0,0), (0,0), colors.white), ('BACKGROUND', (0,0), (0,0), colors.black), ('ALIGN', (0,1), (0,1), 'CENTER'), ])) story.append(shot_thumbnail) story.append(FrameBreak()) # versions grid data = [ ['Versions', '', '', ''], [Paragraph('<b>%s</b>' % t, styles['BodyText']) for t in ['Status', 'Name', 'Notes', 'Frame Range']], ] for v in versions: data.append([ Paragraph(v['sg_status_list'] or '', styles['BodyText']), Paragraph(v['code'] or '', styles['BodyText']), Paragraph(v['description'] or '', styles['BodyText']), Paragraph(v['frame_range'] or '', styles['BodyText']), ]) version_table = Table(data) version_table.setStyle(TableStyle([ ('BOX', (0,0), (-1,-1), 0.25, colors.black), ('INNERGRID', (0,0), (-1,-1), 0.25, colors.black), ('TEXTCOLOR', (0,0), (0,0), colors.white), ('BACKGROUND', (0,0), (0,0), colors.black), ('SPAN', (0,0), (-1, 0)), ])) story.append(version_table) story.append(FrameBreak) # and save doc.build(story)
def save(self, flowables, file_h, canvasmaker=canvas.Canvas): BaseDocTemplate.build(self, flowables, filename=file_h, canvasmaker=canvasmaker)
def build(self, flowables, filename=None, canvasmaker=ReportCanvas): BaseDocTemplate.build(self, flowables, filename, canvasmaker)
def __init__(self, dictValeurs={}, dictOptions={}, IDmodele=None, mode="facture", ouverture=True, nomFichier=None, titre=None): """ Impression """ global DICT_VALEURS, DICT_OPTIONS DICT_VALEURS = dictValeurs DICT_OPTIONS = dictOptions self.mode = mode detail = 0 if dictOptions["affichage_prestations"] != None : detail = dictOptions["affichage_prestations"] # Initialisation du document if nomFichier == None : nomDoc = _(u"Temp/%ss_%s.pdf") % (mode, FonctionsPerso.GenerationIDdoc()) else : nomDoc = nomFichier doc = BaseDocTemplate(nomDoc, pagesize=TAILLE_PAGE, showBoundary=False) # Mémorise le ID du modèle modeleDoc = DLG_Noedoc.ModeleDoc(IDmodele=IDmodele) doc.modeleDoc = modeleDoc # Vérifie qu'un cadre principal existe bien dans le document if doc.modeleDoc.FindObjet("cadre_principal") == None : raise Exception("Votre modèle de document doit obligatoirement comporter un cadre principal. Retournez dans l'éditeur de document et utilisez pour votre modèle la commande 'Insérer un objet spécial > Insérer le cadre principal'.") # Importe le template de la première page doc.addPageTemplates(MyPageTemplate(pageSize=TAILLE_PAGE, doc=doc)) story = [] styleSheet = getSampleStyleSheet() h3 = styleSheet['Heading3'] styleTexte = styleSheet['BodyText'] styleTexte.fontName = "Helvetica" styleTexte.fontSize = 9 styleTexte.borderPadding = 9 styleTexte.leading = 12 ## # Définit le template des pages suivantes ## story.append(NextPageTemplate("suivante")) # ----------- Insertion du contenu des frames -------------- listeNomsSansCivilite = [] for IDcompte_payeur, dictValeur in dictValeurs.iteritems() : listeNomsSansCivilite.append((dictValeur["nomSansCivilite"], IDcompte_payeur)) listeNomsSansCivilite.sort() for nomSansCivilite, IDcompte_payeur in listeNomsSansCivilite : dictValeur = dictValeurs[IDcompte_payeur] if dictValeur["select"] == True : story.append(DocAssign("IDcompte_payeur", IDcompte_payeur)) nomSansCivilite = dictValeur["nomSansCivilite"] story.append(Bookmark(nomSansCivilite, str(IDcompte_payeur))) # ------------------- TITRE ----------------- if dictOptions["afficher_titre"] == True : if titre == None : if mode == "facture" : titre = _(u"Facture") if mode == "attestation" : titre = _(u"Attestation de présence") if dictValeur.has_key("texte_titre") : titre = dictValeur["texte_titre"] dataTableau = [] largeursColonnes = [ CADRE_CONTENU[2], ] dataTableau.append((titre,)) texteDateDebut = DateEngFr(str(dictValeur["date_debut"])) texteDateFin = DateEngFr(str(dictValeur["date_fin"])) if dictOptions["afficher_periode"] == True : dataTableau.append((_(u"Période du %s au %s") % (texteDateDebut, texteDateFin),)) styles = [ ('VALIGN', (0,0), (-1,-1), 'MIDDLE'), ('FONT',(0,0),(0,0), "Helvetica-Bold", dictOptions["taille_texte_titre"]), ('LINEBELOW', (0,0), (0,0), 0.25, colors.black), ('ALIGN', (0,0), (-1,-1), 'LEFT'), ] if dictOptions["afficher_periode"] == True : styles.append(('FONT',(0,1),(0,1), "Helvetica", dictOptions["taille_texte_periode"])) tableau = Table(dataTableau, largeursColonnes) tableau.setStyle(TableStyle(styles)) story.append(tableau) story.append(Spacer(0,20)) # TEXTE D'INTRODUCTION pour Attestation ## if mode == "attestation" and dictValeur["intro"] != None : ## texteIntro = dictValeur["intro"] ## paraStyle = ParagraphStyle(name="intro", ## fontName="Helvetica", ## fontSize=9, ## leading=14, ## spaceBefore=0, ## spaceafter=0, ## leftIndent=20, ## rightIndent=20, ## alignment=1, ## ) ## story.append(Paragraph(u"<i>%s</i>" % texteIntro, paraStyle)) ## story.append(Spacer(0,20)) if dictOptions["texte_introduction"] != "" : paraStyle = ParagraphStyle(name="introduction", fontName="Helvetica", fontSize=dictOptions["taille_texte_introduction"], leading=14, spaceBefore=0, spaceafter=0, leftIndent=5, rightIndent=5, alignment=dictOptions["alignement_texte_introduction"], backColor=ConvertCouleurWXpourPDF(dictOptions["couleur_fond_introduction"]), borderColor=ConvertCouleurWXpourPDF(dictOptions["couleur_bord_introduction"]), borderWidth=0.5, borderPadding=5, ) texte = dictValeur["texte_introduction"].replace("\\n", "<br/>") if dictOptions["style_texte_introduction"] == 0 : texte = u"<para>%s</para>" % texte if dictOptions["style_texte_introduction"] == 1 : texte = u"<para><i>%s</i></para>" % texte if dictOptions["style_texte_introduction"] == 2 : texte = u"<para><b>%s</b></para>" % texte if dictOptions["style_texte_introduction"] == 3 : texte = u"<para><i><b>%s</b></i></para>" % texte story.append(Paragraph(texte, paraStyle)) story.append(Spacer(0,20)) couleurFond = ConvertCouleurWXpourPDF(dictOptions["couleur_fond_1"]) # (0.8, 0.8, 1) couleurFondActivite = ConvertCouleurWXpourPDF(dictOptions["couleur_fond_2"]) # (0.92, 0.92, 1) # ------------------- TABLEAU CONTENU ----------------- montantPeriode = FloatToDecimal(0.0) montantVentilation = FloatToDecimal(0.0) # Recherche si TVA utilisée activeTVA = False for IDindividu, dictIndividus in dictValeur["individus"].iteritems() : for IDactivite, dictActivites in dictIndividus["activites"].iteritems() : for date, dictDates in dictActivites["presences"].iteritems() : for dictPrestation in dictDates["unites"] : if dictPrestation["tva"] != None and dictPrestation["tva"] != 0.0 : activeTVA = True # Remplissage for IDindividu, dictIndividus in dictValeur["individus"].iteritems() : if dictIndividus["select"] == True : listeIndexActivites = [] montantPeriode += dictIndividus["total"] montantVentilation += dictIndividus["ventilation"] # Initialisation des largeurs de tableau largeurColonneDate = dictOptions["largeur_colonne_date"] largeurColonneMontantHT = dictOptions["largeur_colonne_montant_ht"] largeurColonneTVA = dictOptions["largeur_colonne_montant_tva"] largeurColonneMontantTTC = dictOptions["largeur_colonne_montant_ttc"] largeurColonneBaseTTC = largeurColonneMontantTTC if activeTVA == True and detail == 0 : largeurColonneIntitule = CADRE_CONTENU[2] - largeurColonneDate - largeurColonneMontantHT - largeurColonneTVA - largeurColonneMontantTTC largeursColonnes = [ largeurColonneDate, largeurColonneIntitule, largeurColonneMontantHT, largeurColonneTVA, largeurColonneMontantTTC] else : if detail != 0 : largeurColonneIntitule = CADRE_CONTENU[2] - largeurColonneDate - largeurColonneBaseTTC - largeurColonneMontantTTC largeursColonnes = [ largeurColonneDate, largeurColonneIntitule, largeurColonneBaseTTC, largeurColonneMontantTTC] else : largeurColonneIntitule = CADRE_CONTENU[2] - largeurColonneDate - largeurColonneMontantTTC largeursColonnes = [ largeurColonneDate, largeurColonneIntitule, largeurColonneMontantTTC] # Insertion du nom de l'individu paraStyle = ParagraphStyle(name="individu", fontName="Helvetica", fontSize=dictOptions["taille_texte_individu"], leading=dictOptions["taille_texte_individu"], spaceBefore=0, spaceafter=0, ) texteIndividu = Paragraph(dictIndividus["texte"], paraStyle) dataTableau = [] dataTableau.append([texteIndividu,]) tableau = Table(dataTableau, [CADRE_CONTENU[2],]) listeStyles = [ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('FONT', (0, 0), (-1, -1), "Helvetica", dictOptions["taille_texte_individu"]), ('GRID', (0, 0), (-1, -1), 0.25, colors.black), ('BACKGROUND', (0, 0), (-1, 0), couleurFond), ] tableau.setStyle(TableStyle(listeStyles)) story.append(tableau) # Insertion du nom de l'activité for IDactivite, dictActivites in dictIndividus["activites"].iteritems() : texteActivite = dictActivites["texte"] if texteActivite != None : dataTableau = [] dataTableau.append([texteActivite,]) tableau = Table(dataTableau, [CADRE_CONTENU[2],]) listeStyles = [ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('FONT', (0, 0), (-1, -1), "Helvetica", dictOptions["taille_texte_activite"]), ('GRID', (0, 0), (-1, -1), 0.25, colors.black), ('ALIGN', (0, 0), (-1, -1), 'LEFT'), ('BACKGROUND', (0, 0), (-1, 0), couleurFondActivite), ] tableau.setStyle(TableStyle(listeStyles)) story.append(tableau) # Style de paragraphe normal paraStyle = ParagraphStyle(name="prestation", fontName="Helvetica", fontSize=dictOptions["taille_texte_prestation"], leading=dictOptions["taille_texte_prestation"], spaceBefore=0, spaceAfter=0, ) paraLabelsColonnes = ParagraphStyle(name="paraLabelsColonnes", fontName="Helvetica", fontSize=dictOptions["taille_texte_noms_colonnes"], leading=dictOptions["taille_texte_noms_colonnes"], spaceBefore=0, spaceAfter=0, ) if detail != 0 : # -------------- MODE REGROUPE ---------------- # Regroupement par prestations identiques dictRegroupement = {} for date, dictDates in dictActivites["presences"].iteritems() : total = dictDates["total"] for dictPrestation in dictDates["unites"] : label = dictPrestation["label"] listeDatesUnite = GetDatesListes(dictPrestation["listeDatesConso"]) montant = dictPrestation["montant"] deductions = dictPrestation["deductions"] tva = dictPrestation["tva"] if detail == 1 : labelkey = label if detail == 2 : labelkey = label + " P.U. " + "%.2f %s" % (montant, SYMBOLE) if dictRegroupement.has_key(labelkey) == False : dictRegroupement[labelkey] = {"labelpresta" : label, "total" : 0, "nbre" : 0, "base" : 0, "dates_forfait" : None} dictRegroupement[labelkey]["base"] = montant dictRegroupement[labelkey]["total"] += montant dictRegroupement[labelkey]["nbre"] += 1 if detail == 1 : dictRegroupement[labelkey]["base"] = dictRegroupement[labelkey]["total"] / dictRegroupement[labelkey]["nbre"] if len(listeDatesUnite) > 1 : listeDatesUnite.sort() date_debut = listeDatesUnite[0] date_fin = listeDatesUnite[-1] nbreDates = len(listeDatesUnite) dictRegroupement[labelkey]["dates_forfait"] = _(u"<BR/><font size=5>Du %s au %s soit %d jours</font>") % (DateEngFr(str(date_debut)), DateEngFr(str(date_fin)), nbreDates) # Insertion des prestations regroupées listeLabels = dictRegroupement.keys() listeLabels.sort() dataTableau = [( Paragraph(_(u"<para align='center'>Quantité</para>"), paraLabelsColonnes), Paragraph(_(u"<para align='center'>Prestation</para>"), paraLabelsColonnes), Paragraph(_(u"<para align='center'>Base</para>"), paraLabelsColonnes), Paragraph(_(u"<para align='center'>Montant</para>"), paraLabelsColonnes), ),] for labelkey in listeLabels : label = dictRegroupement[labelkey]["labelpresta"] nbre = dictRegroupement[labelkey]["nbre"] total = dictRegroupement[labelkey]["total"] base = dictRegroupement[labelkey]["base"] # recherche d'un commentaire if dictOptions.has_key("dictCommentaires") : key = (label, IDactivite) if dictOptions["dictCommentaires"].has_key(key) : commentaire = dictOptions["dictCommentaires"][key] label = "%s <i><font color='#939393'>%s</font></i>" % (label, commentaire) # Formatage du label intitule = Paragraph(label, paraStyle) # Rajout des dates de forfait #dates_forfait = dictRegroupement[label]["dates_forfait"] #if dates_forfait != None : # intitule = [intitule, Paragraph(dates_forfait, paraStyle)] dataTableau.append([Paragraph(u"<para align='center'>%d</para>" % nbre, paraStyle), intitule, Paragraph(u"<para align='center'>%.02f %s</para>" % (base, SYMBOLE), paraStyle), Paragraph(u"<para align='center'>%.02f %s</para>" % (total, SYMBOLE), paraStyle)]) else : # -------------------------------------------------------------- MODE DETAILLE ------------------------------------------------------------------ # Insertion de la date listeDates = [] for date, dictDates in dictActivites["presences"].iteritems() : listeDates.append(date) listeDates.sort() paraStyle = ParagraphStyle(name="prestation", fontName="Helvetica", fontSize=dictOptions["taille_texte_prestation"], leading=dictOptions["taille_texte_prestation"], spaceBefore=0, spaceAfter=0, ) dataTableau = [] if activeTVA == True : dataTableau.append([ Paragraph(_(u"<para align='center'>Date</para>"), paraLabelsColonnes), Paragraph(_(u"<para align='center'>Prestation</para>"), paraLabelsColonnes), Paragraph(_(u"<para align='center'>Montant HT</para>"), paraLabelsColonnes), Paragraph(_(u"<para align='center'>Taux TVA</para>"), paraLabelsColonnes), Paragraph(_(u"<para align='center'>Montant TTC</para>"), paraLabelsColonnes), ]) for date in listeDates : dictDates = dictActivites["presences"][date] date = dictDates["texte"] prestations = dictDates["unites"] # Insertion des unités de présence listeIntitules = [] listeMontantsHT = [] listeTVA = [] listeMontantsTTC = [] texteIntitules = u"" texteMontantsHT = u"" texteTVA = u"" texteMontantsTTC = u"" for dictPrestation in prestations : label = dictPrestation["label"] listeDatesUnite = GetDatesListes(dictPrestation["listeDatesConso"]) montant_initial = dictPrestation["montant_initial"] montant = dictPrestation["montant"] deductions = dictPrestation["deductions"] tva = dictPrestation["tva"] # Date texteDate = Paragraph("<para align='center'>%s</para>" % date, paraStyle) # recherche d'un commentaire if dictOptions.has_key("dictCommentaires") : key = (label, IDactivite) if dictOptions["dictCommentaires"].has_key(key) : commentaire = dictOptions["dictCommentaires"][key] label = "%s <i><font color='#939393'>%s</font></i>" % (label, commentaire) # Affiche le Label de la prestation listeIntitules.append(Paragraph(label, paraStyle)) # Recherche si c'est un forfait if len(listeDatesUnite) > 1 : listeDatesUnite.sort() date_debut = listeDatesUnite[0] date_fin = listeDatesUnite[-1] nbreDates = len(listeDatesUnite) label = _(u"<BR/><font size=5>Du %s au %s soit %d jours</font>") % (DateEngFr(str(date_debut)), DateEngFr(str(date_fin)), nbreDates) listeIntitules.append(Paragraph(label, paraStyle)) # TVA if activeTVA == True : if tva == None : tva = 0.0 montantHT = (100.0 * float(montant)) / (100 + float(tva)) #montant - montant * 1.0 * float(tva) / 100 listeMontantsHT.append(Paragraph(u"<para align='center'>%.02f %s</para>" % (montantHT, SYMBOLE), paraStyle)) listeTVA.append(Paragraph(u"<para align='center'>%.02f %%</para>" % tva, paraStyle)) else : listeMontantsHT.append("") listeTVA.append("") # Affiche total listeMontantsTTC.append(Paragraph(u"<para align='center'>%.02f %s</para>" % (montant, SYMBOLE), paraStyle)) # Déductions if len(deductions) > 0 : for dictDeduction in deductions : listeIntitules.append(Paragraph(u"<para align='left'><font size=5 color='#939393'>- %.02f %s : %s</font></para>" % (dictDeduction["montant"], SYMBOLE, dictDeduction["label"]), paraStyle)) #listeIntitules.append(Paragraph(u"<para align='left'><font size=5 color='#939393'>%s</font></para>" % dictDeduction["label"], paraStyle)) listeMontantsHT.append(Paragraph(" ", paraStyle)) listeTVA.append(Paragraph(" ", paraStyle)) listeMontantsTTC.append(Paragraph(" ", paraStyle)) #listeMontantsTTC.append(Paragraph(u"<para align='center'><font size=5 color='#939393'>- %.02f %s</font></para>" % (dictDeduction["montant"], SYMBOLE), paraStyle)) if len(listeIntitules) == 1 : texteIntitules = listeIntitules[0] texteMontantsHT = listeMontantsHT[0] texteTVA = listeTVA[0] texteMontantsTTC = listeMontantsTTC[0] if len(listeIntitules) > 1 : texteIntitules = listeIntitules texteMontantsHT = listeMontantsHT texteTVA = listeTVA texteMontantsTTC = listeMontantsTTC if activeTVA == True : dataTableau.append([texteDate, texteIntitules, texteMontantsHT, texteTVA, texteMontantsTTC]) else : dataTableau.append([texteDate, texteIntitules, texteMontantsTTC]) # Style du tableau des prestations tableau = Table(dataTableau, largeursColonnes) listeStyles = [ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('FONT', (0, 0), (-1, -1), "Helvetica", dictOptions["taille_texte_prestation"]), ('GRID', (0, 0), (-1,-1), 0.25, colors.black), ('ALIGN', (0, 0), (-1, -1), 'CENTRE'), ('ALIGN', (1, 0), (1, -1), 'LEFT'), ('TOPPADDING', (0, 0), (-1, -1), 1), ('BOTTOMPADDING', (0, 0), (-1, -1), 3), ] tableau.setStyle(TableStyle(listeStyles)) story.append(tableau) # Insertion des totaux dataTableau = [] if activeTVA == True and detail == 0 : dataTableau.append(["", "", "", "", Paragraph("<para align='center'>%.02f %s</para>" % (dictIndividus["total"], SYMBOLE) , paraStyle)]) else : if detail != 0 : dataTableau.append(["", "", "", Paragraph("<para align='center'>%.02f %s</para>" % (dictIndividus["total"], SYMBOLE) , paraStyle)]) else : dataTableau.append(["", "", Paragraph("<para align='center'>%.02f %s</para>" % (dictIndividus["total"], SYMBOLE) , paraStyle)]) listeStyles = [ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('FONT', (0, 0), (-1, -1), "Helvetica", dictOptions["taille_texte_prestation"]), ('GRID', (-1, -1), (-1,-1), 0.25, colors.black), ('ALIGN', (-1, -1), (-1, -1), 'CENTRE'), ('BACKGROUND', (-1, -1), (-1, -1), couleurFond), ('TOPPADDING', (0, 0), (-1, -1), 1), ('BOTTOMPADDING', (0, 0), (-1, -1), 3), ] # Création du tableau tableau = Table(dataTableau, largeursColonnes) tableau.setStyle(TableStyle(listeStyles)) story.append(tableau) story.append(Spacer(0, 10)) # Intégration des messages, des reports et des qf listeMessages = [] paraStyle = ParagraphStyle(name="message", fontName="Helvetica", fontSize=dictOptions["taille_texte_messages"], leading=dictOptions["taille_texte_messages"], #spaceBefore=0, spaceAfter=2, ) # Date d'échéance ## if dictOptions["echeance"] != None : ## listeMessages.append(Paragraph(dictOptions["echeance"], paraStyle)) # QF aux dates de facture if mode == "facture" and dictOptions["afficher_qf_dates"] == True : dictQfdates = dictValeur["qfdates"] listeDates = dictQfdates.keys() listeDates.sort() if len(listeDates) > 0 : for dates in listeDates : texteQf = _(u"--- Votre QF %s : <b>%s</b> ---") % (dates, dictQfdates[dates]) listeMessages.append(Paragraph(texteQf, paraStyle)) # Reports if mode == "facture" and dictOptions["afficher_impayes"] == True : dictReports = dictValeur["reports"] listePeriodes = dictReports.keys() listePeriodes.sort() if len(listePeriodes) > 0 : texteReport = _(u"<b>Impayés : </b>Merci de bien vouloir nous retourner également le règlement des prestations antérieures : ") for periode in listePeriodes : annee, mois = periode nomPeriode = PeriodeComplete(mois, annee) montant_impaye = dictReports[periode] texteReport += u"%s (%.02f %s), " % (nomPeriode, montant_impaye, SYMBOLE) texteReport = texteReport[:-2] + u"." listeMessages.append(Paragraph(texteReport, paraStyle)) # Messages if mode == "facture" : if dictOptions["afficher_messages"] == True : for message in dictOptions["messages"] : listeMessages.append(Paragraph(message, paraStyle)) for message_familial in dictValeur["messages_familiaux"] : texte = message_familial["texte"] if len(texte) > 0 and texte[-1] not in ".!?" : texte = texte + u"." texte = _(u"<b>Message : </b>%s") % texte listeMessages.append(Paragraph(texte, paraStyle)) if len(listeMessages) > 0 : listeMessages.insert(0, Paragraph(_(u"<u>Informations :</u>"), paraStyle)) # ------------------ CADRE TOTAUX ------------------------ dataTableau = [] largeurColonneLabel = 110 largeursColonnes = [ CADRE_CONTENU[2] - largeurColonneMontantTTC - largeurColonneLabel, largeurColonneLabel, largeurColonneMontantTTC] dataTableau.append((listeMessages, _(u"TOTAL période:"), u"%.02f %s" % (dictValeur["total"], SYMBOLE))) dataTableau.append(("", _(u"Montant déjà réglé :"), u"%.02f %s" % (dictValeur["ventilation"], SYMBOLE))) dataTableau.append(("", _(u"Reste à régler :"), u"%.02f %s" % (dictValeur["solde"], SYMBOLE) )) style = [ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('FONT', (1, 0), (1, -1), "Helvetica-Bold", dictOptions["taille_texte_labels_totaux"]), ('FONT', (2, 0), (2, -1), "Helvetica-Bold", dictOptions["taille_texte_montants_totaux"]), ('GRID', (2, 0), (2, 0), 0.25, colors.black), ('GRID', (2, 1), (2, 1), 0.25, colors.black), ('GRID', (2, 2), (2, 2), 0.25, colors.black), ('ALIGN', (1, 0), (1, -1), 'RIGHT'), ('ALIGN', (2, 0), (2, -1), 'CENTRE'), ('BACKGROUND', (2, 2), (2, 2), couleurFond), ('SPAN', (0, 0), (0, -1)), ] if mode == "facture" and len(listeMessages) > 0 : #style.append( ('BACKGROUND', (0, 0), (0, 0), couleurFondActivite) ) style.append( ('FONT', (0, 0), (0, -1), "Helvetica", 8) ) style.append( ('VALIGN', (0, 0), (0, -1), 'TOP') ) tableau = Table(dataTableau, largeursColonnes, rowHeights=[18, 18, None]) tableau.setStyle(TableStyle(style)) story.append(tableau) # ------------------------- PRELEVEMENTS -------------------- if dictOptions.has_key("afficher_avis_prelevements") and dictValeur.has_key("prelevement") : if dictValeur["prelevement"] != None and dictOptions["afficher_avis_prelevements"] == True : paraStyle = ParagraphStyle(name="intro", fontName="Helvetica", fontSize=8, leading=11, spaceBefore=2, spaceafter=2, alignment=1, backColor=couleurFondActivite, ) story.append(Spacer(0,20)) story.append(Paragraph(u"<para align='center'><i>%s</i></para>" % dictValeur["prelevement"], paraStyle)) # Texte conclusion if dictOptions["texte_conclusion"] != "" : story.append(Spacer(0,20)) paraStyle = ParagraphStyle(name="conclusion", fontName="Helvetica", fontSize=dictOptions["taille_texte_conclusion"], leading=14, spaceBefore=0, spaceafter=0, leftIndent=5, rightIndent=5, alignment=dictOptions["alignement_texte_conclusion"], backColor=ConvertCouleurWXpourPDF(dictOptions["couleur_fond_conclusion"]), borderColor=ConvertCouleurWXpourPDF(dictOptions["couleur_bord_conclusion"]), borderWidth=0.5, borderPadding=5, ) texte = dictValeur["texte_conclusion"].replace("\\n", "<br/>") if dictOptions["style_texte_conclusion"] == 0 : texte = u"<para>%s</para>" % texte if dictOptions["style_texte_conclusion"] == 1 : texte = u"<para><i>%s</i></para>" % texte if dictOptions["style_texte_conclusion"] == 2 : texte = u"<para><b>%s</b></para>" % texte if dictOptions["style_texte_conclusion"] == 3 : texte = u"<para><i><b>%s</b></i></para>" % texte story.append(Paragraph(texte, paraStyle)) # Image signature if dictOptions["image_signature"] != "" : cheminImage = dictOptions["image_signature"] if os.path.isfile(cheminImage) : img = Image(cheminImage) largeur, hauteur = int(img.drawWidth * 1.0 * dictOptions["taille_image_signature"] / 100.0), int(img.drawHeight * 1.0 * dictOptions["taille_image_signature"] / 100.0) if largeur > CADRE_CONTENU[2] or hauteur > CADRE_CONTENU[3] : raise Exception(_(u"L'image de signature est trop grande. Veuillez diminuer sa taille avec le parametre Taille.")) img.drawWidth, img.drawHeight = largeur, hauteur if dictOptions["alignement_image_signature"] == 0 : img.hAlign = "LEFT" if dictOptions["alignement_image_signature"] == 1 : img.hAlign = "CENTER" if dictOptions["alignement_image_signature"] == 2 : img.hAlign = "RIGHT" story.append(Spacer(0,20)) story.append(img) # Saut de page story.append(PageBreak()) # Finalisation du PDF ## try : doc.build(story) ## except Exception, err : ## print "Erreur dans ouverture PDF :", err ## if "Permission denied" in err : ## dlg = wx.MessageDialog(None, _(u"Noethys ne peut pas créer le PDF.\n\nVeuillez vérifier qu'un autre PDF n'est pas déjà ouvert en arrière-plan..."), _(u"Erreur d'édition"), wx.OK | wx.ICON_ERROR) ## dlg.ShowModal() ## dlg.Destroy() ## return # Ouverture du PDF if ouverture == True : FonctionsPerso.LanceFichierExterne(nomDoc)
def __init__(self, dictComptes={}, dictOptions={}, IDmodele=None, ouverture=True, nomFichier=None): """ Impression """ global DICT_COMPTES, DICT_OPTIONS DICT_COMPTES = dictComptes DICT_OPTIONS = dictOptions # Initialisation du document if nomFichier == None : nomDoc = FonctionsPerso.GenerationNomDoc("ATTESTATIONS_FISCALES", "pdf") else : nomDoc = nomFichier doc = BaseDocTemplate(nomDoc, pagesize=TAILLE_PAGE, showBoundary=False) # Mémorise le ID du modèle modeleDoc = DLG_Noedoc.ModeleDoc(IDmodele=IDmodele) doc.modeleDoc = modeleDoc # Vérifie qu'un cadre principal existe bien dans le document if doc.modeleDoc.FindObjet("cadre_principal") == None : raise Exception("Votre modele de document doit obligatoirement comporter un cadre principal. Retournez dans l'editeur de document et utilisez pour votre modele la commande 'Inserer un objet special > Inserer le cadre principal'.") # Mémorise le ID du modèle modeleDoc = DLG_Noedoc.ModeleDoc(IDmodele=IDmodele) doc.modeleDoc = modeleDoc # Importe le template de la première page doc.addPageTemplates(MyPageTemplate(pageSize=TAILLE_PAGE, doc=doc)) story = [] styleSheet = getSampleStyleSheet() h3 = styleSheet['Heading3'] styleTexte = styleSheet['BodyText'] styleTexte.fontName = "Helvetica" styleTexte.fontSize = 9 styleTexte.borderPadding = 9 styleTexte.leading = 12 ## # Définit le template des pages suivantes ## story.append(NextPageTemplate("suivante")) # ----------- Insertion du contenu des frames -------------- listeNomsSansCivilite = [] for IDcompte_payeur, dictCompte in dictComptes.iteritems() : listeNomsSansCivilite.append((dictCompte["{FAMILLE_NOM}"], IDcompte_payeur)) listeNomsSansCivilite.sort() for nomSansCivilite, IDcompte_payeur in listeNomsSansCivilite : dictCompte = dictComptes[IDcompte_payeur] story.append(DocAssign("IDcompte_payeur", IDcompte_payeur)) nomSansCivilite = dictCompte["{FAMILLE_NOM}"] story.append(Bookmark(nomSansCivilite, str(IDcompte_payeur))) # ------------------- TITRE ----------------- dataTableau = [] largeursColonnes = [ TAILLE_CADRE_CONTENU[2], ] dataTableau.append((dictOptions["titre"],)) texteDateReference = UTILS_Dates.DateEngFr(str(datetime.date.today())) dataTableau.append((_(u"Période du %s au %s") % (UTILS_Dates.DateDDEnFr(dictOptions["date_debut"]), UTILS_Dates.DateDDEnFr(dictOptions["date_fin"])),)) style = TableStyle([ ('VALIGN', (0,0), (-1,-1), 'MIDDLE'), ('FONT',(0,0),(0,0), "Helvetica-Bold", 19), ('FONT',(0,1),(0,1), "Helvetica", 8), ('LINEBELOW', (0,0), (0,0), 0.25, colors.black), ('ALIGN', (0,0), (-1,-1), 'LEFT'), ]) tableau = Table(dataTableau, largeursColonnes) tableau.setStyle(style) story.append(tableau) story.append(Spacer(0, 30)) couleurFond = (0.8, 0.8, 1) couleurFondActivite = (0.92, 0.92, 1) # TEXTE CONTENU paraStyle = ParagraphStyle(name="contenu", fontName="Helvetica", fontSize=11, leading=16, spaceBefore=0, spaceafter=0, leftIndent=6, rightIndent=6, ) # INTRO texte = dictCompte["{INTRO}"] if texte != "" : listeParagraphes = texte.split("</para>") for paragraphe in listeParagraphes : textePara = Paragraph(u"%s" % paragraphe, paraStyle) story.append(textePara) story.append(Spacer(0, 25)) # DETAIL par enfant dataTableau = [(_(u"Nom et prénom"), _(u"Date de naissance"), _(u"Montant")),] largeursColonnes = [ 220, 80, 80] paraStyle = ParagraphStyle(name="detail", fontName="Helvetica-Bold", fontSize=9, ) for nomCompletIndividu, dictIndividu in dictCompte["individus"] : dataTableau.append( (nomCompletIndividu, dictIndividu["date_naiss"], u"%.2f %s" % (dictIndividu["regle"], SYMBOLE)) ) dataTableau.append( ("", "Total :", dictCompte["{MONTANT_REGLE}"]) ) style = TableStyle([ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('ALIGN', (0, 0), (-1, -1), 'CENTER'), ('GRID', (0, 0), (-1, -2), 0.25, colors.black), ('FONT', (0, 0), (-1, 0), "Helvetica", 6), ('FONT', (0, 1), (-1, -1), "Helvetica", 10), ('TOPPADDING', (0, 1), (-1, -2), 10), ('BOTTOMPADDING', (0, 1), (-1, -2), 10), ('GRID', (-1, -1), (-1, -1), 0.25, colors.black), ('FONT', (-1, -1), (-1, -1), "Helvetica-Bold", 10), ('ALIGN', (-2, -1), (-2, -1), 'RIGHT'), ('FONT', (-2, -1), (-2, -1), "Helvetica", 6), ]) tableau = Table(dataTableau, largeursColonnes) tableau.setStyle(style) story.append(tableau) # Saut de page story.append(PageBreak()) # Finalisation du PDF doc.build(story) # Ouverture du PDF if ouverture == True : FonctionsPerso.LanceFichierExterne(nomDoc)
# ------------------------------------- # BEGIN TO ADD CONTENT # when to add content at document, is # similar to write a story step by step # and you should use a list of flowables # that help to write it. # ------------------------------------- # list of flowables that represent the content of document content = [] # add the first flowable called Paragraph, that allow write text content.append( Paragraph("This is a Paragraph ", ParagraphStyle( 'MyStyle1', fontSize=10, ))) content.append(NextPageTemplate('page_design_two')) content.append(PageBreak()) content.append( Paragraph("This is a Paragraph on the page 2 ", ParagraphStyle( 'MyStyle1', fontSize=10, ))) # when finish of write content, so you can send build it document.build(content, filename="Training_pdf" #canvasmaker=canvas.Canvas )
def __init__(self, dictValeurs={}, dictOptions={}, IDmodele=None, ouverture=True, nomFichier=None): """ Impression """ global DICT_VALEURS, DICT_OPTIONS DICT_VALEURS = dictValeurs DICT_OPTIONS = dictOptions # Initialisation du document if nomFichier == None: nomDoc = FonctionsPerso.GenerationNomDoc("INSCRIPTIONS", "pdf") else: nomDoc = nomFichier doc = BaseDocTemplate(nomDoc, pagesize=TAILLE_PAGE, showBoundary=False) # Mémorise le ID du modèle modeleDoc = DLG_Noedoc.ModeleDoc(IDmodele=IDmodele) doc.modeleDoc = modeleDoc # Importe le template de la première page doc.addPageTemplates(MyPageTemplate(pageSize=TAILLE_PAGE, doc=doc)) story = [] styleSheet = getSampleStyleSheet() h3 = styleSheet['Heading3'] styleTexte = styleSheet['BodyText'] styleTexte.fontName = "Helvetica" styleTexte.fontSize = 9 styleTexte.borderPadding = 9 styleTexte.leading = 12 # ----------- Insertion du contenu des frames -------------- listeLabels = [] for IDinscription, dictValeur in dictValeurs.iteritems(): listeLabels.append((dictValeur["{FAMILLE_NOM}"], IDinscription)) listeLabels.sort() for labelDoc, IDinscription in listeLabels: dictValeur = dictValeurs[IDinscription] if dictValeur["select"] == True: story.append(DocAssign("IDinscription", IDinscription)) nomSansCivilite = dictValeur["{FAMILLE_NOM}"] story.append(Bookmark(nomSansCivilite, str(IDinscription))) # ----------- Insertion du cadre principal -------------- cadre_principal = doc.modeleDoc.FindObjet("cadre_principal") if cadre_principal != None: if DICT_OPTIONS.has_key("intro") and DICT_OPTIONS["intro"] != None or DICT_OPTIONS.has_key("tableau" ) and DICT_VALEURS["tableau"] == True: # ------------------- TITRE ----------------- dataTableau = [] largeursColonnes = [TAILLE_CADRE_CONTENU[2], ] dataTableau.append((_(u"Confirmation d'inscription"),)) dataTableau.append((u"",)) style = TableStyle([ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('FONT', (0, 0), (0, 0), "Helvetica-Bold", 19), ('FONT', (0, 1), (0, 1), "Helvetica", 8), ('LINEBELOW', (0, 0), (0, 0), 0.25, colors.black), ('ALIGN', (0, 0), (-1, -1), 'LEFT'), ]) tableau = Table(dataTableau, largeursColonnes) tableau.setStyle(style) story.append(tableau) story.append(Spacer(0, 10)) # TEXTE D'INTRODUCTION paraStyleIntro = ParagraphStyle(name="intro", fontName="Helvetica", fontSize=11, leading=14, spaceBefore=0, spaceafter=0, leftIndent=0, rightIndent=0, alignment=0, ) if DICT_OPTIONS.has_key("intro") and DICT_OPTIONS["intro"] != None: texteIntro = DICT_VALEURS["intro"] story.append(Paragraph(u"<i>%s</i>" % texteIntro, paraStyleIntro)) story.append(Spacer(0, 20)) if DICT_OPTIONS.has_key("tableau") and DICT_OPTIONS["tableau"] == True: # ------------------- TABLEAU CONTENU ----------------- dataTableau = [] largeursColonnes = [80, 280] paraStyle = ParagraphStyle(name="detail", fontName="Helvetica-Bold", fontSize=9, ) dataTableau.append((_(u"Nom"), Paragraph(DICT_VALEURS["{INDIVIDU_NOM}"], paraStyle))) dataTableau.append((_(u"Prénom"), Paragraph(DICT_VALEURS["{INDIVIDU_PRENOM}"], paraStyle))) dataTableau.append((_(u"Activité"), Paragraph(DICT_VALEURS["{ACTIVITE_NOM_LONG}"], paraStyle))) dataTableau.append((_(u"Groupe"), Paragraph(DICT_VALEURS["{GROUPE_NOM_LONG}"], paraStyle))) dataTableau.append((_(u"Catégorie"), Paragraph(DICT_VALEURS["{NOM_CATEGORIE_TARIF}"], paraStyle))) style = TableStyle([ ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), ('FONT', (0, 0), (0, -1), "Helvetica", 9), ('GRID', (0, 0), (-1, -1), 0.25, colors.black), ('ALIGN', (0, 0), (0, -1), 'RIGHT'), ]) tableau = Table(dataTableau, largeursColonnes) tableau.setStyle(style) story.append(tableau) # Saut de page story.append(PageBreak()) # Finalisation du PDF doc.build(story) # Ouverture du PDF if ouverture == True: FonctionsPerso.LanceFichierExterne(nomDoc)