コード例 #1
0
ファイル: OL_Factures.py プロジェクト: nicolas-pantel/Noethys
    def EnvoyerEmail(self, event):
        """ Envoyer la facture par Email """
        if len(self.Selection()) == 0:
            dlg = wx.MessageDialog(
                self,
                _(u"Vous n'avez sélectionné aucune facture à envoyer par Email !"
                  ), _(u"Erreur de saisie"), wx.OK | wx.ICON_EXCLAMATION)
            dlg.ShowModal()
            dlg.Destroy()
            return
        track = self.Selection()[0]
        if track.etat == "annulation":
            dlg = wx.MessageDialog(
                self,
                _(u"Vous ne pouvez pas envoyer par Email une facture annulée !"
                  ), _(u"Information"), wx.OK | wx.ICON_EXCLAMATION)
            dlg.ShowModal()
            dlg.Destroy()
            return

        # Envoi du mail
        from Utils import UTILS_Envoi_email
        UTILS_Envoi_email.EnvoiEmailFamille(
            parent=self,
            IDfamille=track.IDfamille,
            nomDoc=FonctionsPerso.GenerationNomDoc("FACTURE", "pdf"),
            categorie="facture")
コード例 #2
0
 def OnBoutonEmail(self, event):
     """ Envoi par mail """
     from Utils import UTILS_Envoi_email
     UTILS_Envoi_email.EnvoiEmailFamille(
         parent=self,
         IDfamille=self.IDfamille,
         nomDoc=FonctionsPerso.GenerationNomDoc("RECUDONAUXOEUVRES", "pdf"),
         categorie="recu_don_oeuvres")
コード例 #3
0
    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)
コード例 #4
0
 def OnBoutonEmail(self, event):
     """ Envoi par mail """
     from Utils import UTILS_Envoi_email
     UTILS_Envoi_email.EnvoiEmailFamille(
         parent=self,
         IDfamille=self.IDfamille,
         nomDoc=FonctionsPerso.GenerationNomDoc("RECU", "pdf"),
         categorie="recu_reglement",
         listeAdresses=self.listeAdresses)
コード例 #5
0
 def OnBoutonEmail(self, event):
     """ Envoi par mail """
     from Utils import UTILS_Envoi_email
     UTILS_Envoi_email.EnvoiEmailFamille(
         parent=self,
         IDfamille=self.IDfamille,
         nomDoc=FonctionsPerso.GenerationNomDoc("INSCRIPTION", "pdf"),
         categorie="inscription",
         listeAdresses=self.listeAdresses)
コード例 #6
0
 def OnBoutonEmail(self, event):
     restaurateur_mail = self.ctrl_repas.GetDonnees()["restaurateur_mail"]
     if restaurateur_mail in ("", None):
         dlg = wx.MessageDialog(
             self,
             _(u"Vous devez d'abord renseigner l'adresse mail du restaurateur !"
               ), _(u"Erreur de saisie"), wx.OK | wx.ICON_EXCLAMATION)
         dlg.ShowModal()
         dlg.Destroy()
         return False
     from Utils import UTILS_Envoi_email
     UTILS_Envoi_email.EnvoiEmailFamille(
         parent=self,
         nomDoc=FonctionsPerso.GenerationNomDoc("COMMANDE_REPAS", "pdf"),
         categorie="commande_repas",
         listeAdresses=[
             restaurateur_mail,
         ])
コード例 #7
0
 def EnvoyerEmail(self, event):
     """ Envoyer la location par Email """
     if len(self.Selection()) == 0:
         dlg = wx.MessageDialog(
             self,
             _(u"Vous n'avez sélectionné aucune location à envoyer par Email !"
               ), _(u"Erreur de saisie"), wx.OK | wx.ICON_EXCLAMATION)
         dlg.ShowModal()
         dlg.Destroy()
         return
     track = self.Selection()[0]
     # Envoi du mail
     from Utils import UTILS_Envoi_email
     UTILS_Envoi_email.EnvoiEmailFamille(
         parent=self,
         IDfamille=track.IDfamille,
         nomDoc=FonctionsPerso.GenerationNomDoc("LOCATION", "pdf"),
         categorie="location")
コード例 #8
0
    def ImpressionTEST(self):
        texte = self.HtmlEnReportlab(self.GetHtmlText())

        # Création du PDF
        from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, PageBreak
        from reportlab.platypus.flowables import ParagraphAndImage, Image
        from reportlab.rl_config import defaultPageSize
        from reportlab.lib.units import inch, cm
        from reportlab.lib.utils import ImageReader
        from reportlab.lib import colors
        from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
        self.hauteur_page = defaultPageSize[1]
        self.largeur_page = defaultPageSize[0]

        # Initialisation du PDF
        PAGE_HEIGHT = defaultPageSize[1]
        PAGE_WIDTH = defaultPageSize[0]
        nomDoc = FonctionsPerso.GenerationNomDoc("TEST_TEXTE_RAPPEL", "pdf")
        if sys.platform.startswith("win"): nomDoc = nomDoc.replace("/", "\\")
        doc = SimpleDocTemplate(nomDoc, topMargin=30, bottomMargin=30)
        story = []

        # Test texte
        paraStyle = ParagraphStyle(
            name="test",
            fontName="Helvetica",
            fontSize=9,
            #leading=7,
            spaceBefore=0,
            spaceafter=0,
        )

        listeParagraphes = texte.split("</para>")
        for paragraphe in listeParagraphes:
            textePara = Paragraph(u"%s</para>" % paragraphe, paraStyle)
            story.append(textePara)

        # Enregistrement du PDF
        doc.build(story)

        # Affichage du PDF
        FonctionsPerso.LanceFichierExterne(nomDoc)
コード例 #9
0
 def CreationPDF(self, nomDoc=FonctionsPerso.GenerationNomDoc("RELEVE_PRESTATIONS", "pdf"), afficherDoc=True):
     dictOptionsImpression = {}
     
     # Création PDF
     listePeriodes = self.ctrl_periodes.GetListePeriodes() 
     if len(listePeriodes) == 0 :
         dlg = wx.MessageDialog(self, _(u"Vous devez paramétrer au moins une période dans la liste !"), _(u"Erreur de saisie"), wx.OK | wx.ICON_EXCLAMATION)
         dlg.ShowModal()
         dlg.Destroy()
         return False
     
     # Récupère couleur fond de titre
     if self.checkbox_couleur.GetValue() == True :
         dictOptionsImpression["couleur"] = self.ctrl_couleur.GetColour()
     else :
         dictOptionsImpression["couleur"] = False
     
     # Impression
     impression = Impression(IDfamille=self.IDfamille, listePeriodes=listePeriodes, dictOptionsImpression=dictOptionsImpression)
     dictChamps = impression.CreationPDF(nomDoc, afficherDoc) 
     return dictChamps
コード例 #10
0
    def OnBoutonOk(self, event):
        dictOptions = self.ctrl_parametres.GetOptions()
        if dictOptions == False:
            return

        # Récupération des paramètres
        listeIDfactures = []
        montantTotal = FloatToDecimal(0.0)
        for track in self.tracks:
            listeIDfactures.append(track.IDfacture)
            montantTotal += track.total

        if len(listeIDfactures) == 0: conditionFactures = "()"
        elif len(listeIDfactures) == 1:
            conditionFactures = "(%d)" % listeIDfactures[0]
        else:
            conditionFactures = str(tuple(listeIDfactures))

        DB = GestionDB.DB()
        req = """
        SELECT prestations.IDprestation, prestations.IDfacture, prestations.label, prestations.montant, 
        prestations.IDindividu, individus.nom, individus.prenom,
        prestations.IDactivite, activites.nom
        FROM prestations
        LEFT JOIN individus ON prestations.IDindividu = individus.IDindividu
        LEFT JOIN activites ON activites.IDactivite = prestations.IDactivite
        WHERE prestations.IDfacture IN %s
        GROUP BY prestations.IDprestation
        ORDER BY prestations.date
        ;""" % conditionFactures
        DB.ExecuterReq(req)
        listePrestations = DB.ResultatReq()

        # Récupération des prélèvements
        req = """SELECT
            prelevements.IDprelevement, prelevements.prelevement_iban,
            prelevements.IDfacture, lots_prelevements.date,
            prelevement_reference_mandat, titulaire
            FROM prelevements
            LEFT JOIN lots_prelevements ON lots_prelevements.IDlot = prelevements.IDlot
            WHERE prelevements.IDfacture IN %s
            ;""" % conditionFactures
        DB.ExecuterReq(req)
        listePrelevements = DB.ResultatReq()
        # Pièces PES ORMC
        req = """SELECT
            pes_pieces.IDpiece, pes_pieces.prelevement_iban, pes_pieces.IDfacture,
            pes_lots.date_prelevement, pes_pieces.prelevement_IDmandat, pes_pieces.prelevement_titulaire
            FROM pes_pieces
            LEFT JOIN pes_lots ON pes_lots.IDlot = pes_pieces.IDlot
            WHERE pes_pieces.prelevement_IDmandat IS NOT NULL AND pes_pieces.prelevement=1 AND pes_pieces.IDfacture IN %s
            ;""" % conditionFactures
        DB.ExecuterReq(req)
        listePieces = DB.ResultatReq()
        dictPrelevements = {}
        for listeDonneesPrel in (listePrelevements, listePieces):
            for IDprelevement, iban, IDfacture, datePrelevement, rum, titulaire in (
                    listeDonneesPrel):
                datePrelevement = UTILS_Dates.DateEngFr(datePrelevement)
                dictPrelevements[IDfacture] = {
                    "IDprelevement": IDprelevement,
                    "datePrelevement": datePrelevement,
                    "iban": iban,
                    "rum": rum,
                    "titulaire": titulaire
                }

        DB.Close()
        # Calcul totaux prélèvements
        nbrFactPrelev = len(dictPrelevements)
        montantTotalPrelev = 0.0
        for track in self.tracks:
            if track.IDfacture in dictPrelevements:
                montantTotalPrelev += -track.solde

        dictPrestations = {}
        dictIndividus = {}
        dictActivites = {}
        dictTotaux = {}
        for IDprestation, IDfacture, label, montant, IDindividu, nom, prenom, IDactivite, nomActivite in listePrestations:

            if dictActivites != None and (IDactivite
                                          in dictActivites) == False:
                dictActivites[IDactivite] = nomActivite

            if IDindividu != None and (
                    IDindividu in dictIndividus) == False and prenom != None:
                dictIndividus[IDindividu] = u"%s %s" % (nom, prenom)

            if (IDfacture in dictPrestations) == False:
                dictPrestations[IDfacture] = {}
            if (IDindividu in dictPrestations[IDfacture]) == False:
                dictPrestations[IDfacture][IDindividu] = {}
            if (label in dictPrestations[IDfacture][IDindividu]) == False:
                dictPrestations[IDfacture][IDindividu][label] = {
                    "quantite": 0,
                    "montant": 0.0,
                    "IDactivite": IDactivite
                }

            if (IDactivite in dictTotaux) == False:
                dictTotaux[IDactivite] = {}
            if (label in dictTotaux[IDactivite]) == False:
                dictTotaux[IDactivite][label] = {"quantite": 0, "montant": 0.0}

            dictTotaux[IDactivite][label]["quantite"] += 1
            dictTotaux[IDactivite][label]["montant"] += montant

            dictPrestations[IDfacture][IDindividu][label]["quantite"] += 1
            dictPrestations[IDfacture][IDindividu][label]["montant"] += montant

        # Création du PDF
        from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, PageBreak
        from reportlab.platypus.flowables import ParagraphAndImage, Image
        from reportlab.rl_config import defaultPageSize
        from reportlab.lib.units import inch, cm
        from reportlab.lib.utils import ImageReader
        from reportlab.lib import colors
        from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
        self.hauteur_page = defaultPageSize[1]
        self.largeur_page = defaultPageSize[0]

        # Initialisation du PDF
        PAGE_WIDTH, PAGE_HEIGHT = defaultPageSize
        nomDoc = FonctionsPerso.GenerationNomDoc("RECAP_FACTURES", "pdf")
        if sys.platform.startswith("win"): nomDoc = nomDoc.replace("/", "\\")
        doc = SimpleDocTemplate(nomDoc, topMargin=30, bottomMargin=30)
        story = []

        largeurContenu = 520

        # Création du titre du document
        def Header():
            dataTableau = []
            largeursColonnes = ((420, 100))
            dateDuJour = UTILS_Dates.DateEngFr(str(datetime.date.today()))
            dataTableau.append(
                (dictOptions["titre_texte"], _(u"%s\nEdité le %s") %
                 (UTILS_Organisateur.GetNom(), dateDuJour)))
            style = TableStyle([
                ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                ('ALIGN', (0, 0), (0, 0),
                 ConvertAlignement1(dictOptions["titre_alignement"])),
                ('FONT', (0, 0), (0, 0), "Helvetica-Bold",
                 dictOptions["titre_taille_texte"]),
                ('ALIGN', (1, 0), (1, 0), 'RIGHT'),
                ('FONT', (1, 0), (1, 0), "Helvetica", 6),
            ])
            tableau = Table(dataTableau, largeursColonnes)
            tableau.setStyle(style)
            story.append(tableau)
            story.append(Spacer(0, 20))

        # Insère un header
        Header()

        couleurFond1 = ConvertCouleurWXpourPDF(dictOptions["couleur_fond_1"])
        couleurFond2 = ConvertCouleurWXpourPDF(dictOptions["couleur_fond_2"])

        styleIntroduction = ParagraphStyle(
            name="introduction",
            fontName="Helvetica",
            alignment=ConvertAlignement2(dictOptions["intro_alignement"]),
            fontSize=dictOptions["intro_taille_texte"],
            spaceAfter=0,
            leading=8,
            spaceBefore=0)
        styleConclusion = ParagraphStyle(
            name="conclusion",
            fontName="Helvetica",
            alignment=ConvertAlignement2(dictOptions["conclusion_alignement"]),
            fontSize=dictOptions["conclusion_taille_texte"],
            spaceAfter=0,
            leading=8,
            spaceBefore=0)

        styleLabel = ParagraphStyle(name="label",
                                    fontName="Helvetica",
                                    alignment=1,
                                    fontSize=5,
                                    spaceAfter=0,
                                    leading=8,
                                    spaceBefore=0)
        styleTexte = ParagraphStyle(name="label",
                                    fontName="Helvetica",
                                    alignment=0,
                                    fontSize=7,
                                    spaceAfter=0,
                                    leading=8,
                                    spaceBefore=0)
        styleTexte2 = ParagraphStyle(name="label",
                                     fontName="Helvetica",
                                     alignment=1,
                                     fontSize=7,
                                     spaceAfter=0,
                                     leading=8,
                                     spaceBefore=0)
        styleMontant = ParagraphStyle(name="label",
                                      fontName="Helvetica",
                                      alignment=2,
                                      fontSize=7,
                                      spaceAfter=0,
                                      leading=8,
                                      spaceBefore=0)

        # Intro
        story.append(Paragraph(dictOptions["intro_texte"], styleIntroduction))
        story.append(Spacer(0, 20))

        # Factures
        if dictOptions["type_document"] in (0, 1):

            for track in self.tracks:

                numero = track.numero
                if track.etat == "annulation":
                    numero = u"%s (Annulée)" % numero

                solde = track.solde
                if solde != 0.0:
                    solde = -solde

                # Numéro de facture
                dataTableau = []
                largeursColonnes = [100, 100, largeurContenu - 100 - 100]
                dataTableau.append((
                    _(u"Facture n°%s") % numero,
                    u"%.2f %s" % (solde, SYMBOLE),
                    _(u"Edité le %s | Echéance le %s | Période du %s au %s")
                    % (UTILS_Dates.DateDDEnFr(track.date_edition),
                       UTILS_Dates.DateDDEnFr(track.date_echeance),
                       UTILS_Dates.DateDDEnFr(track.date_debut),
                       UTILS_Dates.DateDDEnFr(track.date_fin)),
                ))
                tableau = Table(dataTableau, largeursColonnes)
                listeStyles = [
                    ('FONT', (0, 0), (1, -1), "Helvetica-Bold", 7),
                    ('FONT', (2, -1), (2, -1), "Helvetica", 6),
                    ('BACKGROUND', (0, 0), (-1, -1), couleurFond1),
                    ('ALIGN', (2, -1), (2, -1), 'RIGHT'),
                    ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                ]
                tableau.setStyle(TableStyle(listeStyles))
                story.append(tableau)

                # Famille
                if track.prelevement == True:
                    if track.IDfacture in dictPrelevements:
                        textePrelevement = _(
                            u"IBAN : %s | RUM : %s | Titulaire : %s | Le : %s "
                        ) % (dictPrelevements[track.IDfacture]["iban"],
                             dictPrelevements[track.IDfacture]["rum"],
                             dictPrelevements[track.IDfacture]["titulaire"],
                             dictPrelevements[
                                 track.IDfacture]["datePrelevement"])
                    else:
                        textePrelevement = _(
                            u"N° Compte : %s | Etab : %s | Guichet : %s | Clé : %s | Titulaire : %s"
                        ) % (track.prelevement_numero, track.prelevement_etab,
                             track.prelevement_guichet, track.prelevement_cle,
                             track.prelevement_payeur)
                else:
                    textePrelevement = u""

                if track.adresse_famille["rue"] != None:
                    rue = track.adresse_famille["rue"]
                else:
                    rue = u""
                if track.adresse_famille["cp"] != None:
                    cp = track.adresse_famille["cp"]
                else:
                    cp = u""
                if track.adresse_famille["ville"] != None:
                    ville = track.adresse_famille["ville"]
                else:
                    ville = u""

                dataTableau = []
                dataTableau.append(
                    (Paragraph(_(u"Famille"),
                               styleLabel), Paragraph(_(u"Adresse"),
                                                      styleLabel),
                     Paragraph(_(u"Prélèvement bancaire"), styleLabel)))
                dataTableau.append(
                    (Paragraph(track.nomsTitulaires,
                               styleTexte), (Paragraph(rue, styleTexte),
                                             Paragraph(u"%s %s" % (cp, ville),
                                                       styleTexte)),
                     Paragraph(textePrelevement, styleTexte)))

                largeursColonnes = [180, 140, largeurContenu - 320]
                tableau = Table(dataTableau, largeursColonnes)
                listeStyles = [
                    ('TOPPADDING', (0, 0), (-1, 0), 0),
                    ('BOTTOMPADDING', (0, 0), (-1, 0), -1),
                    ('FONT', (0, -1), (-1, -1), "Helvetica", 7),
                    ('GRID', (0, 0), (-1, 0), 0.25, colors.black),
                    ('BOX', (0, 1), (-1, 1), 0.25, colors.black),
                    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                    ('BACKGROUND', (0, 0), (-1, 0), couleurFond2),
                ]
                tableau.setStyle(TableStyle(listeStyles))
                story.append(tableau)

                # Récupération des champs personnalisés
                dataTableau = []

                label_1, label_2, label_3, question_1, question_2, question_3 = "", "", "", "", "", ""
                for dictReponse in self.Questionnaires.GetDonnees(
                        track.IDfamille):
                    if dictReponse["champ"] == dictOptions["question_1"]:
                        label_1, question_1 = dictReponse[
                            "label"], dictReponse["reponse"]
                    if dictReponse["champ"] == dictOptions["question_2"]:
                        label_2, question_2 = dictReponse[
                            "label"], dictReponse["reponse"]
                    if dictReponse["champ"] == dictOptions["question_3"]:
                        label_3, question_3 = dictReponse[
                            "label"], dictReponse["reponse"]

                if len(label_1) > 0 or len(label_2) > 0 or len(label_3) > 0:
                    dataTableau.append(
                        (Paragraph(label_1,
                                   styleLabel), Paragraph(label_2, styleLabel),
                         Paragraph(label_3, styleLabel)))
                    dataTableau.append((Paragraph(question_1, styleTexte),
                                        Paragraph(question_2, styleTexte),
                                        Paragraph(question_3, styleTexte)))
                    largeursColonnes = [
                        largeurContenu / 3.0, largeurContenu / 3.0,
                        largeurContenu / 3.0
                    ]
                    tableau = Table(dataTableau, largeursColonnes)
                    listeStyles = [
                        ('TOPPADDING', (0, 0), (-1, 0), 0),
                        ('BOTTOMPADDING', (0, 0), (-1, 0), -1),
                        ('FONT', (0, -1), (-1, -1), "Helvetica", 7),
                        ('GRID', (0, 0), (-1, 0), 0.25, colors.black),
                        ('BOX', (0, 1), (-1, 1), 0.25, colors.black),
                        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                        ('BACKGROUND', (0, 0), (-1, 0), couleurFond2),
                    ]
                    tableau.setStyle(TableStyle(listeStyles))
                    story.append(tableau)

                # Détail des prestations
                if dictOptions[
                        "type_document"] == 0 and track.IDfacture in dictPrestations:

                    # Préparation des champs individuels supplémentaires
                    liste_champs_ind = []
                    for key in ("champ_ind_1", "champ_ind_2", "champ_ind_3"):
                        if dictOptions[key] not in ("non", "", None):
                            liste_champs_ind.append(dictOptions[key])

                    if len(liste_champs_ind) == 0:
                        dataTableau = [
                            (Paragraph(_(u"Individu"), styleLabel),
                             Paragraph(_(u"Activité"), styleLabel),
                             Paragraph(_(u"Prestation"), styleLabel),
                             Paragraph(_(u"Quantité"), styleLabel),
                             Paragraph(_(u"Montant total"), styleLabel)),
                        ]
                        largeursColonnes = [130, 120, 185, 35, 50]
                    else:
                        # On rajoute la colonne Infos individuelles :
                        dataTableau = [
                            (Paragraph(_(u"Individu"), styleLabel),
                             Paragraph(_(u"Informations"), styleLabel),
                             Paragraph(_(u"Activité"), styleLabel),
                             Paragraph(_(u"Prestation"), styleLabel),
                             Paragraph(_(u"Quantité"), styleLabel),
                             Paragraph(_(u"Montant total"), styleLabel)),
                        ]
                        largeursColonnes = [120, 110, 100, 105, 35, 50]

                    for IDindividu, dictLabels in dictPrestations[
                            track.IDfacture].items():

                        if IDindividu in dictIndividus:
                            labelIndividu = dictIndividus[IDindividu]
                        else:
                            labelIndividu = u""

                        listeActivites = []
                        listeLabels = []
                        listeQuantites = []
                        listeMontants = []
                        for labelPrestation, dictTemp in dictLabels.items():

                            if dictTemp["IDactivite"] != None and dictTemp[
                                    "IDactivite"] in dictActivites:
                                labelActivite = dictActivites[
                                    dictTemp["IDactivite"]]
                            else:
                                labelActivite = u""

                            listeActivites.append(
                                Paragraph(labelActivite[:35], styleTexte2))
                            listeLabels.append(
                                Paragraph(labelPrestation[:40], styleTexte2))
                            listeQuantites.append(
                                Paragraph(str(dictTemp["quantite"]),
                                          styleTexte2))
                            listeMontants.append(
                                Paragraph(
                                    u"%.2f %s" %
                                    (dictTemp["montant"], SYMBOLE),
                                    styleMontant))

                        ligne = [
                            Paragraph(labelIndividu, styleTexte2),
                            listeActivites,
                            listeLabels,
                            listeQuantites,
                            listeMontants,
                        ]

                        # Récupération des infos individuelles
                        if len(liste_champs_ind) > 0:
                            liste_textes_ind = []
                            for key in liste_champs_ind:
                                # Ecole
                                if "ecole" in key or "classe" in key or "niveau" in key:
                                    if "date_debut" in key:
                                        date_reference = track.date_debut
                                    else:
                                        date_reference = track.date_fin
                                    infosIndividus = UTILS_Infos_individus.Informations(
                                        date_reference=date_reference,
                                        qf=False,
                                        inscriptions=False,
                                        messages=False,
                                        infosMedicales=False,
                                        cotisationsManquantes=False,
                                        piecesManquantes=False,
                                        questionnaires=False,
                                        scolarite=True)
                                    dictInfosIndividus = infosIndividus.GetDictValeurs(
                                        mode="individu",
                                        ID=IDindividu,
                                        formatChamp=False)
                                    texte = ""
                                    if "ecole" in key and "SCOLARITE_NOM_ECOLE" in dictInfosIndividus:
                                        texte = dictInfosIndividus[
                                            "SCOLARITE_NOM_ECOLE"]
                                    if "classe" in key and "SCOLARITE_NOM_CLASSE" in dictInfosIndividus:
                                        texte = dictInfosIndividus[
                                            "SCOLARITE_NOM_CLASSE"]
                                    if "niveau" in key and "SCOLARITE_NOM_NIVEAU" in dictInfosIndividus:
                                        texte = dictInfosIndividus[
                                            "SCOLARITE_NOM_NIVEAU"]
                                    liste_textes_ind.append(
                                        Paragraph(texte, styleTexte2))

                            ligne.insert(1, liste_textes_ind)

                        # Insertion de la ligne dans le tableau
                        dataTableau.append(ligne)

                    tableau = Table(dataTableau, largeursColonnes)
                    listeStyles = [
                        ('TOPPADDING', (0, 0), (-1, 0), 0),
                        ('BOTTOMPADDING', (0, 0), (-1, 0), -1),
                        ('FONT', (0, -1), (-1, -1), "Helvetica", 7),
                        ('GRID', (0, 0), (-1, -1), 0.25, colors.black),
                        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                        ('BACKGROUND', (0, 0), (-1, 0), couleurFond2),
                    ]
                    tableau.setStyle(TableStyle(listeStyles))
                    story.append(tableau)

                story.append(Spacer(0, 10))

        # Totaux
        dataTableau = [
            (_(u"Totaux par activités et prestations"), "", "", ""),
            (Paragraph(_(u"Activités"),
                       styleLabel), Paragraph(_(u"Prestations"), styleLabel),
             Paragraph(_(u"Quantité"),
                       styleLabel), Paragraph(_(u"Montant"), styleLabel)),
        ]
        largeursColonnes = [195, 240, 35, 50]

        for IDactivite, dictLabels in dictTotaux.items():

            if IDactivite == None:
                nomActivite = _(u"Prestations diverses")
            else:
                nomActivite = dictActivites[IDactivite]

            listeLabels = []
            listeQuantites = []
            listeMontants = []
            quantiteActivite = 0
            totalActivite = 0.0
            for label, dictTemp in dictLabels.items():
                listeLabels.append(Paragraph(label, styleTexte2))
                listeQuantites.append(
                    Paragraph(str(dictTemp["quantite"]), styleTexte2))
                listeMontants.append(
                    Paragraph(u"%.2f %s" % (dictTemp["montant"], SYMBOLE),
                              styleMontant))
                quantiteActivite += dictTemp["quantite"]
                totalActivite += dictTemp["montant"]

            listeLabels.append(
                Paragraph(_(u"<b><i>Total de l'activité</i></b>"),
                          styleTexte2))
            listeQuantites.append(
                Paragraph("<b><i>%d</i></b>" % quantiteActivite, styleTexte2))
            listeMontants.append(
                Paragraph(u"<b><i>%.2f %s</i></b>" % (totalActivite, SYMBOLE),
                          styleMontant))

            dataTableau.append((
                Paragraph(nomActivite, styleTexte2),
                listeLabels,
                listeQuantites,
                listeMontants,
            ))

        tableau = Table(dataTableau, largeursColonnes)
        listeStyles = [
            ('TOPPADDING', (0, 1), (-1, 1), 0),
            ('BOTTOMPADDING', (0, 1), (-1, 1), -1),
            ('FONT', (1, -1), (-1, -1), "Helvetica", 7),
            ('FONT', (0, 0), (0, 0), "Helvetica-Bold", 7),
            ('BOX', (0, 0), (-1, 0), 0.25, colors.black),
            ('GRID', (0, 1), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('BACKGROUND', (0, 0), (-1, 0), couleurFond1),
            ('BACKGROUND', (0, 1), (-1, 1), couleurFond2),
        ]
        tableau.setStyle(TableStyle(listeStyles))
        story.append(tableau)

        story.append(Spacer(0, 10))

        # Texte de conclusion
        conclusion_texte = dictOptions["conclusion_texte"]
        conclusion_texte = conclusion_texte.replace("{NBRE_FACTURES}",
                                                    str(len(self.tracks)))
        conclusion_texte = conclusion_texte.replace(
            "{TOTAL_FACTURES}", u"%.2f %s" % (montantTotal, SYMBOLE))
        conclusion_texte = conclusion_texte.replace("{NBRE_FACT_PRELEV}",
                                                    str(nbrFactPrelev))
        conclusion_texte = conclusion_texte.replace(
            "{TOTAL_FACT_PRELEV}", u"%.2f %s" % (montantTotalPrelev, SYMBOLE))
        story.append(Paragraph(conclusion_texte, styleConclusion))

        # Enregistrement et ouverture du PDF
        try:
            doc.build(story)
        except Exception as 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 False

        FonctionsPerso.LanceFichierExterne(nomDoc)
コード例 #11
0
    def Imprimer(self, event=None):
        # Création du PDF
        from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, PageBreak
        from reportlab.platypus.flowables import ParagraphAndImage, Image
        from reportlab.rl_config import defaultPageSize
        from reportlab.lib.units import inch, cm
        from reportlab.lib.utils import ImageReader
        from reportlab.lib import colors
        from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
        self.hauteur_page = defaultPageSize[1]
        self.largeur_page = defaultPageSize[0]

        # Initialisation du PDF
        PAGE_HEIGHT = defaultPageSize[1]
        PAGE_WIDTH = defaultPageSize[0]
        nomDoc = FonctionsPerso.GenerationNomDoc("LISTE_PRESTATIONS_", "pdf")
        if sys.platform.startswith("win"): nomDoc = nomDoc.replace("/", "\\")
        doc = SimpleDocTemplate(nomDoc,
                                topMargin=30,
                                bottomMargin=30,
                                leftMargin=40,
                                rightMargin=40)
        story = []

        largeurContenu = 520

        # Création du titre du document
        dataTableau = []
        largeursColonnes = ((420, 100))
        dateDuJour = DateEngFr(str(datetime.date.today()))
        dataTableau.append(
            (_(u"Liste des prestations"), _(u"%s\nEdité le %s") %
             (UTILS_Organisateur.GetNom(), dateDuJour)))
        style = TableStyle([
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ('ALIGN', (0, 0), (0, 0), 'LEFT'),
            ('FONT', (0, 0), (0, 0), "Helvetica-Bold", 16),
            ('ALIGN', (1, 0), (1, 0), 'RIGHT'),
            ('FONT', (1, 0), (1, 0), "Helvetica", 6),
        ])
        tableau = Table(dataTableau, largeursColonnes)
        tableau.setStyle(style)
        story.append(tableau)
        story.append(Spacer(0, 10))

        # Intro
        styleA = ParagraphStyle(name="A",
                                fontName="Helvetica",
                                fontSize=6,
                                spaceAfter=20)
        story.append(Paragraph(self.labelParametres, styleA))

        # Famille
        for dictFamille in self.listeImpression["donnees"]:

            # Init tableau
            dataTableau = []
            largeursColonnes = [220, 220, 40, 40]

            dataTableau.append((dictFamille['nom'], dictFamille['adresse'],
                                dictFamille['montant'], dictFamille['nombre']))

            # Individu
            for dictIndividu in dictFamille["individus"]:
                dataTableau.append(
                    (u"     %s (%s)" %
                     (dictIndividu["nom"], dictIndividu["date_naiss"]), "", "",
                     ""))

                # Prestations
                for dictPrestation in dictIndividu["prestations"]:
                    dataTableau.append(
                        (u"                 " + dictPrestation["label"],
                         dictPrestation["nomActivite"],
                         dictPrestation["montant"], dictPrestation["nombre"]))

            couleurFond = (0.8, 0.8, 1)
            listeStyles = [
                ('VALIGN', (0, 0), (-1, -1),
                 'MIDDLE'),  # Centre verticalement toutes les cases
                ('FONT', (0, 0), (-1, -1), "Helvetica",
                 7),  # Donne la police de caract. + taille de police 
                ('BOX', (0, 1), (-1, -1), 0.25,
                 colors.black),  # Crée la bordure noire pour tout le tableau
                ('ALIGN', (2, 0), (-1, -1),
                 'CENTRE'),  # Ligne de labels colonne alignée au centre
                ('BOX', (0, 0), (-1, 0), 0.25,
                 colors.black),  # Crée la bordure noire du nom de famille
                (
                    'FONT', (0, 0), (0, 0), "Helvetica-Bold", 8
                ),  # Donne la police de caract. + taille de police du titre de groupe
                ('BACKGROUND', (0, 0), (-1, 0),
                 couleurFond),  # Donne la couleur de fond du titre de groupe
                ('TOPPADDING', (0, 0), (-1, -1), 1),
                ('BOTTOMPADDING', (0, 0), (-1, -1), 1),
            ]

            # Création du tableau
            tableau = Table(dataTableau, largeursColonnes)
            tableau.setStyle(TableStyle(listeStyles))
            story.append(tableau)
            story.append(Spacer(0, 6))

        # TOTAUX
        dataTableau = []
        largeursColonnes = [220, 220, 40, 40]

        for ligne in self.listeImpression["totaux"]:
            dataTableau.append(ligne)

        couleurFond = (0.8, 0.8, 0.8)
        listeStyles = [
            ('VALIGN', (0, 0), (-1, -1),
             'MIDDLE'),  # Centre verticalement toutes les cases
            ('FONT', (0, 0), (-1, -1), "Helvetica",
             7),  # Donne la police de caract. + taille de police 
            ('BOX', (0, 1), (-1, -1), 0.25,
             colors.black),  # Crée la bordure noire pour tout le tableau
            ('ALIGN', (2, 0), (-1, -1),
             'CENTRE'),  # Ligne de labels colonne alignée au centre
            ('BOX', (0, 0), (-1, 0), 0.25,
             colors.black),  # Crée la bordure noire du nom de famille
            (
                'FONT', (0, 0), (0, 0), "Helvetica-Bold", 8
            ),  # Donne la police de caract. + taille de police du titre de groupe
            ('BACKGROUND', (0, 0), (-1, 0),
             couleurFond),  # Donne la couleur de fond du titre de groupe
            ('TOPPADDING', (0, 0), (-1, -1), 1),
            ('BOTTOMPADDING', (0, 0), (-1, -1), 1),
        ]

        # Création du tableau
        tableau = Table(dataTableau, largeursColonnes)
        tableau.setStyle(TableStyle(listeStyles))
        story.append(tableau)

        # Enregistrement du PDF
        doc.build(story)

        # Affichage du PDF
        FonctionsPerso.LanceFichierExterne(nomDoc)
コード例 #12
0
    def CreationPDF(self,
                    nomDoc=FonctionsPerso.GenerationNomDoc(
                        "COMMANDE_REPAS", "pdf"),
                    afficherDoc=True):
        dictChampsFusion = {}

        # Récupération des données
        nom_commande = self.ctrl_nom.GetValue()
        date_debut = self.ctrl_date_debut.GetDate()
        date_fin = self.ctrl_date_fin.GetDate()
        observations = self.ctrl_observations.GetValue()
        dictDonnees = self.ctrl_repas.GetDonnees()

        # Récupération des options d'impression
        global DICT_INFOS_IMPRESSION
        DICT_INFOS_IMPRESSION = {
            "date_debut": date_debut,
            "date_fin": date_fin
        }
        dlg = DLG_Options_impression_pdf.Dialog(self,
                                                categorie="commande_repas",
                                                ctrl=CTRL_Options_impression)
        if dlg.ShowModal() == wx.ID_OK:
            dictOptions = dlg.GetOptions()
            dlg.Destroy()
        else:
            dlg.Destroy()
            return False

        # Création du PDF
        from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle
        from reportlab.platypus.flowables import ParagraphAndImage, Image
        from reportlab.lib.pagesizes import A4
        from reportlab.lib import colors
        from reportlab.lib.styles import ParagraphStyle

        if dictOptions["orientation"] == "portrait":
            largeur_page, hauteur_page = A4
        else:
            hauteur_page, largeur_page = A4

        # Initialisation du PDF
        if sys.platform.startswith("win"): nomDoc = nomDoc.replace("/", "\\")
        doc = SimpleDocTemplate(nomDoc,
                                pagesize=(largeur_page, hauteur_page),
                                topMargin=30,
                                bottomMargin=30)
        story = []

        largeurContenu = largeur_page - 75

        # Création du titre du document
        def Header():
            dataTableau = []
            largeursColonnes = ((largeurContenu - 100, 100))
            dateDuJour = UTILS_Dates.DateEngFr(str(datetime.date.today()))
            dataTableau.append(
                (_(u"Commande des repas"), _(u"%s\nEdité le %s") %
                 (UTILS_Organisateur.GetNom(), dateDuJour)))
            style = TableStyle([
                ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                ('ALIGN', (0, 0), (0, 0), 'LEFT'),
                ('FONT', (0, 0), (0, 0), "Helvetica-Bold", 16),
                ('ALIGN', (1, 0), (1, 0), 'RIGHT'),
                ('FONT', (1, 0), (1, 0), "Helvetica", 6),
            ])
            tableau = Table(dataTableau, largeursColonnes)
            tableau.setStyle(style)
            story.append(tableau)
            story.append(Spacer(0, 10))

        # Insère un header
        Header()

        # Insère le nom et la période de la commande
        style_titre_commande = ParagraphStyle(
            name="1",
            alignment=1,
            fontName="Helvetica-Bold",
            fontSize=dictOptions["taille_texte_titre"],
            leading=8,
            spaceAfter=14)
        story.append(
            Paragraph(
                _(u"<para>%s - Du %s au %s</para>") %
                (nom_commande, UTILS_Dates.DateDDEnFr(date_debut),
                 UTILS_Dates.DateDDEnFr(date_fin)), style_titre_commande))

        # Styles
        style_entete = ParagraphStyle(name="1",
                                      alignment=1,
                                      fontName="Helvetica-Bold",
                                      fontSize=dictOptions["taille_texte"],
                                      leading=8,
                                      spaceAfter=2)
        style_numerique = ParagraphStyle(name="2",
                                         alignment=2,
                                         fontName="Helvetica",
                                         fontSize=dictOptions["taille_texte"],
                                         leading=8,
                                         spaceAfter=2)
        style_total = ParagraphStyle(name="3",
                                     alignment=2,
                                     fontName="Helvetica-Bold",
                                     fontSize=dictOptions["taille_texte"],
                                     leading=8,
                                     spaceAfter=2)
        style_texte = ParagraphStyle(name="4",
                                     alignment=0,
                                     fontName="Helvetica",
                                     fontSize=dictOptions["taille_texte"],
                                     leading=8,
                                     spaceAfter=2)

        # Calcule des largeurs de colonne
        largeur_colonne_date = dictOptions["largeur_colonne_date"]

        largeur_colonnes = largeurContenu - largeur_colonne_date
        dictLargeurs = {}

        if dictOptions["largeur_colonnes_auto"] == True:
            total_largeurs_colonnes = 0
            for dictColonne in dictDonnees["liste_colonnes"]:
                total_largeurs_colonnes += dictColonne["largeur"]
            for dictColonne in dictDonnees["liste_colonnes"]:
                dictLargeurs[dictColonne["IDcolonne"]] = 1.0 * dictColonne[
                    "largeur"] / total_largeurs_colonnes * largeur_colonnes

        # Dessin du tableau de données
        dataTableau = []
        largeursColonnes = [
            largeur_colonne_date,
        ]

        # Dessin des noms de colonnes
        ligne = [
            Paragraph(_(u"Date"), style_entete),
        ]
        for dictColonne in dictDonnees["liste_colonnes"]:
            valeur = dictColonne["nom_colonne"]
            ligne.append(Paragraph(valeur, style_entete))
            if dictColonne["IDcolonne"] in dictLargeurs:
                largeur = dictLargeurs[dictColonne["IDcolonne"]]
            else:
                largeur = dictColonne["largeur"] / 1.5
            largeursColonnes.append(largeur)
        dataTableau.append(ligne)

        # Dessin des lignes
        dict_totaux_colonnes = {}
        for numLigne in range(0, len(dictDonnees["liste_dates"])):
            ligne = []

            # Ajout de la date à la ligne
            date = dictDonnees["liste_dates"][numLigne]

            afficher_ligne = True
            if dictOptions["masquer_dates_anciennes"] == True and type(
                    date) == datetime.date and date < datetime.date.today():
                afficher_ligne = False

            if afficher_ligne == True:

                if type(date) == datetime.date:
                    valeur = UTILS_Dates.DateComplete(date)
                else:
                    valeur = date
                ligne.append(Paragraph(valeur, style_entete))

                # Ajout des cases à la ligne
                numColonne = 0
                for dictColonne in dictDonnees["liste_colonnes"]:

                    # Recherche la valeur
                    valeur = ""
                    if (numLigne, numColonne) in dictDonnees["cases"]:
                        case = dictDonnees["cases"][(numLigne, numColonne)]
                        valeur = case.GetValeur()

                        # Recherche le style à appliquer
                        if "numerique" in case.categorieColonne:
                            style = style_numerique

                            # Définit le style de la case total
                            if "total" in case.categorieColonne or numLigne == len(
                                    dictDonnees["liste_dates"]) - 1:
                                style = style_total

                            if numLigne == len(dictDonnees["liste_dates"]) - 1:
                                # Récupère la valeur total de la colonne
                                valeur = dict_totaux_colonnes.get(
                                    numColonne, 0)
                            else:
                                # Mémorise total de la colonne numérique
                                if (numColonne
                                        in dict_totaux_colonnes) == False:
                                    dict_totaux_colonnes[numColonne] = 0
                                dict_totaux_colonnes[numColonne] += valeur

                        else:
                            style = style_texte
                            valeur = valeur.replace("\n", "<br/>")
                    ligne.append(Paragraph(six.text_type(valeur), style))
                    numColonne += 1

                # Ajout de la ligne au tableau
                dataTableau.append(ligne)
コード例 #13
0
    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)
コード例 #14
0
    def Imprimer(self):
        dlg = DLG_Options_impression_pdf.Dialog(self, categorie="synthese_ventilation", ctrl=CTRL_Parametres)
        if dlg.ShowModal() == wx.ID_OK:
            dictOptions = dlg.GetOptions()
            dlg.Destroy()
        else :
            dlg.Destroy()
            return

        # Création du PDF
        from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle
        from reportlab.lib.pagesizes import A4
        from reportlab.lib import colors
        from reportlab.lib.styles import ParagraphStyle
        
        hauteur_page = A4[0]
        largeur_page = A4[1]
            
        # Initialisation du PDF
        nomDoc = FonctionsPerso.GenerationNomDoc("STATS_VENTILATION", "pdf")
        if sys.platform.startswith("win") : nomDoc = nomDoc.replace("/", "\\")
        doc = SimpleDocTemplate(nomDoc, pagesize=(largeur_page, hauteur_page), topMargin=30, bottomMargin=30)
        story = []
        
        # Création du titre du document
        def Header():
            dataTableau = []
            largeursColonnes = ( (largeur_page-175, 100) )
            dateDuJour = UTILS_Dates.DateEngFr(str(datetime.date.today()))
            dataTableau.append( (_(u"Analyse croisée ventilation/dépôts"), _(u"%s\nEdité le %s") % (UTILS_Organisateur.GetNom(), dateDuJour)) )
            style = TableStyle([
                    ('BOX', (0,0), (-1,-1), 0.25, colors.black), 
                    ('VALIGN', (0,0), (-1,-1), 'TOP'), 
                    ('ALIGN', (0,0), (0,0), 'LEFT'), 
                    ('FONT',(0,0),(0,0), "Helvetica-Bold", 16), 
                    ('ALIGN', (1,0), (1,0), 'RIGHT'), 
                    ('FONT',(1,0),(1,0), "Helvetica", 6), 
                    ])
            tableau = Table(dataTableau, largeursColonnes)
            tableau.setStyle(style)
            story.append(tableau)
            story.append(Spacer(0,20))       
        
        # Insère un header
        Header() 
        
        # Tableau
        dataTableau = []
        largeursColonnes = [dictOptions["largeur_colonne_labels"],]
        for x in range(0, len(self.dictImpression["entete"])-1):
            largeursColonnes.append(dictOptions["largeur_colonne_valeurs"])
        
        # Entetes labels
        dataTableau.append(self.dictImpression["entete"])

        paraNormal = ParagraphStyle(name="normal", fontName="Helvetica", fontSize=dictOptions["taille_texte"], spaceAfter=0, leading=dictOptions["taille_texte"]+1, spaceBefore=0)
        paraTitre = ParagraphStyle(name="titre", fontName="Helvetica-Bold", fontSize=dictOptions["taille_texte"], spaceAfter=0, leading=dictOptions["taille_texte"]+1, spaceBefore=0)

        # Contenu du tableau
        listeRubriques = ("contenu", "total")
        for rubrique in listeRubriques :
            listeLignes = self.dictImpression[rubrique]

            indexLigne = 0
            for ligne in listeLignes :
                ligneTemp = []
                indexColonne = 0
                for texte in ligne :

                    # Aligne à droite les montants
                    if indexColonne > 0 :
                        texte = _(u"<para align='right'>%s</para>") % texte

                    case = Paragraph(texte, paraNormal)

                    # Ligne de titre
                    if rubrique == "contenu" and indexLigne in self.dictImpression["coloration"] :
                        case = Paragraph(texte, paraTitre)

                    ligneTemp.append(case)
                    indexColonne += 1

                dataTableau.append(ligneTemp)
                indexLigne += 1
コード例 #15
0
    def CreationPDF(self,
                    nomDoc=FonctionsPerso.GenerationNomDoc(
                        "RECUDONAUXOEUVRES", "pdf"),
                    afficherDoc=True):
        dictChampsFusion = {}

        # Vérifie que la cotisation a été payée
        if self.totalVentilation < self.montant:
            dlg = wx.MessageDialog(
                self,
                _(u"Cette cotisation n'a pas été réglée en intégralité.\n\nSouhaitez-vous quand même l'éditer ?"
                  ), _(u"Confirmation"),
                wx.YES_NO | wx.NO_DEFAULT | wx.CANCEL | wx.ICON_EXCLAMATION)
            reponse = dlg.ShowModal()
            dlg.Destroy()
            if reponse != wx.ID_YES:
                return False

        # Récupération des données sur l'organisme
        nom_organisme = self.ctrl_nom_beneficiaire.GetValue()
        adresse_organisme = self.ctrl_adresse_beneficiaire.GetValue()
        objet_organisme = self.ctrl_objet.GetValue()
        type_organisme = self.ctrl_type.GetValue()

        # Mémorisation des données ORGANISME
        if self.ctrl_memoriser_organisme.GetValue() == True:
            UTILS_Parametres.Parametres(mode="set",
                                        categorie="don_oeuvres",
                                        nom="nom_organisme",
                                        valeur=nom_organisme)
            UTILS_Parametres.Parametres(mode="set",
                                        categorie="don_oeuvres",
                                        nom="adresse_organisme",
                                        valeur=adresse_organisme)
            UTILS_Parametres.Parametres(mode="set",
                                        categorie="don_oeuvres",
                                        nom="objet_organisme",
                                        valeur=objet_organisme)
            UTILS_Parametres.Parametres(mode="set",
                                        categorie="don_oeuvres",
                                        nom="type_organisme",
                                        valeur=type_organisme)

        # Donateur
        if self.radio_nom_auto.GetValue() == True:
            nom_donateur = self.ctrl_nom_auto.GetNom()
        else:
            nom_donateur = self.ctrl_nom_autre.GetValue()
        adresse_donateur = self.ctr_adresse_donateur.GetValue()

        # Versement
        date_versement = self.ctrl_date_versement.GetDate(FR=True)
        if date_versement == u"  /  /    " or date_versement == None:
            date_versement = u""
        if self.radio_mode_auto.GetValue() == True:
            mode = self.ctrl_mode_auto.GetNomMode()
        else:
            mode = self.ctrl_mode_autre.GetValue()

        # Date édition
        date_edition = self.ctrl_date_edition.GetDate(FR=True)
        if date_edition == u"  /  /    " or date_edition == None:
            date_edition = u""

        # Montant
        montant_chiffres = u"%.2f ¤" % self.montant
        montant_lettres = UTILS_Conversion.trad(self.montant)

        dictDonnees = {
            "numero": self.numero,
            "nom_organisme": nom_organisme,
            "adresse_organisme": adresse_organisme,
            "objet_organisme": objet_organisme,
            "type_organisme": type_organisme,
            "nom_donateur": nom_donateur,
            "adresse_donateur": adresse_donateur,
            "date_versement": date_versement,
            "montant_chiffres": montant_chiffres,
            "montant_lettres": montant_lettres,
            "mode": mode,
            "date_edition": date_edition,
        }

        dictChampsFusion["{DATE_EDITION}"] = date_edition
        dictChampsFusion["{NUMERO_RECU}"] = self.numero
        dictChampsFusion["{NOM_DONATEUR}"] = nom_donateur
        dictChampsFusion["{ADRESSE_DONATEUR}"] = adresse_donateur
        dictChampsFusion["{DATE_REGLEMENT}"] = date_versement
        dictChampsFusion["{MODE_REGLEMENT}"] = mode
        dictChampsFusion["{MONTANT_CHIFFRES}"] = montant_chiffres
        dictChampsFusion["{MONTANT_LETTRES}"] = montant_lettres

        # Lancement de l'édition du PDF
        Impression(dictDonnees, nomDoc=nomDoc, afficherDoc=afficherDoc)

        return dictChampsFusion
コード例 #16
0
    def Imprimer(self):
        # Création du PDF
        from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, PageBreak
        from reportlab.platypus.flowables import ParagraphAndImage, Image
        from reportlab.rl_config import defaultPageSize
        from reportlab.lib.pagesizes import A4
        from reportlab.lib.units import inch, cm
        from reportlab.lib.utils import ImageReader
        from reportlab.lib import colors
        from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle

        hauteur_page = A4[0]
        largeur_page = A4[1]

        # Initialisation du PDF
        nomDoc = FonctionsPerso.GenerationNomDoc("synthese_modes_reglements",
                                                 "pdf")
        if sys.platform.startswith("win"): nomDoc = nomDoc.replace("/", "\\")
        doc = SimpleDocTemplate(nomDoc,
                                pagesize=(largeur_page, hauteur_page),
                                topMargin=30,
                                bottomMargin=30,
                                leftMargin=40,
                                rightMargin=40)
        story = []

        # Création du titre du document
        dataTableau = []
        largeursColonnes = ((largeur_page - 175, 100))
        dateDuJour = DateEngFr(str(datetime.date.today()))
        dataTableau.append(
            (_(u"Synthèse des modes de règlements"), _(u"%s\nEdité le %s") %
             (UTILS_Organisateur.GetNom(), dateDuJour)))
        style = TableStyle([
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ('ALIGN', (0, 0), (0, 0), 'LEFT'),
            ('FONT', (0, 0), (0, 0), "Helvetica-Bold", 16),
            ('ALIGN', (1, 0), (1, 0), 'RIGHT'),
            ('FONT', (1, 0), (1, 0), "Helvetica", 6),
        ])
        tableau = Table(dataTableau, largeursColonnes)
        tableau.setStyle(style)
        story.append(tableau)
        story.append(Spacer(0, 10))

        # Intro
        styleA = ParagraphStyle(name="A",
                                fontName="Helvetica",
                                fontSize=6,
                                spaceAfter=20)
        story.append(Paragraph(self.labelParametres, styleA))

        # Tableau
        dataTableau = []
        largeursColonnes = [
            160,
        ]
        for x in range(0, len(self.dictImpression["entete"]) - 1):
            largeursColonnes.append(45)

        # Entetes labels
        dataTableau.append(self.dictImpression["entete"])

        # Contenu du tableau
        listeRubriques = ("contenu", "total")
        for rubrique in listeRubriques:
            listeLignes = self.dictImpression[rubrique]

            for ligne in listeLignes:
                dataTableau.append(ligne)

        positionLigneTotal = len(self.dictImpression["contenu"]) + 1
        listeStyles = [
            ('VALIGN', (0, 0), (-1, -1),
             'MIDDLE'),  # Centre verticalement toutes les cases
            ('FONT', (0, 0), (-1, -1), "Helvetica",
             7),  # Donne la police de caract. + taille de police 
            ('GRID', (0, 0), (-1, -1), 0.25,
             colors.black),  # Crée la bordure noire pour tout le tableau
            ('ALIGN', (0, 0), (-1, -1), 'CENTRE'),  # Centre les cases
            ('BACKGROUND', (0, 0), (-1, 0),
             (0.6, 0.6, 0.6)),  # Donne la couleur de fond du label
            ('BACKGROUND', (0, positionLigneTotal), (-1, positionLigneTotal),
             (0.6, 0.6, 0.6)),  # Donne la couleur de fond du label
        ]

        # Formatage des lignes "Activités"
        for indexColoration in self.dictImpression["coloration"]:
            listeStyles.append(
                ('FONT', (0, indexColoration + 1), (-1, indexColoration + 1),
                 "Helvetica-Bold", 7))
            listeStyles.append(('BACKGROUND', (0, indexColoration + 1),
                                (-1, indexColoration + 1), (0.8, 0.8, 0.8)))

        # Création du tableau
        tableau = Table(dataTableau, largeursColonnes)
        tableau.setStyle(TableStyle(listeStyles))
        story.append(tableau)
        story.append(Spacer(0, 20))

        # Enregistrement du PDF
        doc.build(story)

        # Affichage du PDF
        FonctionsPerso.LanceFichierExterne(nomDoc)
コード例 #17
0
    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)
コード例 #18
0
    def CreationPDF(self,
                    nomDoc=FonctionsPerso.GenerationNomDoc(
                        "INSCRIPTION", "pdf"),
                    afficherDoc=True):
        dictChampsFusion = {}

        # Récupération des valeurs de base
        dictDonnees = DICT_DONNEES

        # Récupération des infos sur l'organisme
        DB = GestionDB.DB()
        req = """SELECT nom, rue, cp, ville, tel, fax, mail, site, num_agrement, num_siret, code_ape
        FROM organisateur
        WHERE IDorganisateur=1;"""
        DB.ExecuterReq(req)
        listeDonnees = DB.ResultatReq()
        dictOrganisme = {}
        for nom, rue, cp, ville, tel, fax, mail, site, num_agrement, num_siret, code_ape in listeDonnees:
            dictOrganisme["nom"] = nom
            dictOrganisme["rue"] = rue
            dictOrganisme["cp"] = cp
            if ville != None: ville = ville.capitalize()
            dictOrganisme["ville"] = ville
            dictOrganisme["tel"] = tel
            dictOrganisme["fax"] = fax
            dictOrganisme["mail"] = mail
            dictOrganisme["site"] = site
            dictOrganisme["num_agrement"] = num_agrement
            dictOrganisme["num_siret"] = num_siret
            dictOrganisme["code_ape"] = code_ape
        DB.Close()

        date_editionDD = datetime.date.today()

        # Adresse
        self.IDindividu = self.dictInscription["IDINDIVIDU"]
        individus = UTILS_Titulaires.GetIndividus()
        self.dictInscription["INDIVIDU_RUE"] = individus[
            self.IDindividu]["rue"]
        self.dictInscription["INDIVIDU_CP"] = individus[self.IDindividu]["cp"]
        self.dictInscription["INDIVIDU_VILLE"] = individus[
            self.IDindividu]["ville"]

        # Nom Titulaires
        dictTitulaires = UTILS_Titulaires.GetTitulaires(listeIDfamille=[
            self.IDfamille,
        ])
        self.dictInscription["FAMILLE_NOM"] = dictTitulaires[
            self.IDfamille]["titulairesSansCivilite"]

        # Civilité
        dictCivilites = Civilites.GetDictCivilites()
        if self.dictInscription["IDCIVILITE"] == None or self.dictInscription[
                "IDCIVILITE"] == "":
            IDcivilite = 1
        else:
            IDcivilite = self.dictInscription["IDCIVILITE"]
        self.dictInscription["INDIVIDU_GENRE"] = dictCivilites[IDcivilite][
            "sexe"]
        self.dictInscription["INDIVIDU_CIVILITE_LONG"] = dictCivilites[
            IDcivilite]["civiliteLong"]
        self.dictInscription["INDIVIDU_CIVILITE_COURT"] = dictCivilites[
            IDcivilite]["civiliteAbrege"]

        # Date de naissance
        if self.dictInscription["INDIVIDU_DATE_NAISS"] == None:
            self.dictInscription["INDIVIDU_AGE"] = None
        else:
            datenaissDD = datetime.date(
                year=int(self.dictInscription["INDIVIDU_DATE_NAISS"][:4]),
                month=int(self.dictInscription["INDIVIDU_DATE_NAISS"][5:7]),
                day=int(self.dictInscription["INDIVIDU_DATE_NAISS"][8:10]))
            datedujour = datetime.date.today()
            age = (datedujour.year - datenaissDD.year) - int(
                (datedujour.month, datedujour.day) <
                (datenaissDD.month, datenaissDD.day))
            self.dictInscription["INDIVIDU_AGE"] = age

        # Insertion des données de base dans le dictValeurs
        IDfamille = self.IDfamille
        dictValeurs = {
            "IDfamille":
            self.IDfamille,
            "{IDFAMILLE}":
            str(self.IDfamille),
            "{DATE_EDITION}":
            DateEngFr(str(date_editionDD)),
            "{DATE_EDITION_LONG}":
            DateComplete(date_editionDD),
            "{DATE_EDITION_COURT}":
            DateEngFr(str(date_editionDD)),
            "{ORGANISATEUR_NOM}":
            dictOrganisme["nom"],
            "{ORGANISATEUR_RUE}":
            dictOrganisme["rue"],
            "{ORGANISATEUR_CP}":
            dictOrganisme["cp"],
            "{ORGANISATEUR_VILLE}":
            dictOrganisme["ville"],
            "{ORGANISATEUR_TEL}":
            dictOrganisme["tel"],
            "{ORGANISATEUR_FAX}":
            dictOrganisme["fax"],
            "{ORGANISATEUR_MAIL}":
            dictOrganisme["mail"],
            "{ORGANISATEUR_SITE}":
            dictOrganisme["site"],
            "{ORGANISATEUR_AGREMENT}":
            dictOrganisme["num_agrement"],
            "{ORGANISATEUR_SIRET}":
            dictOrganisme["num_siret"],
            "{ORGANISATEUR_APE}":
            dictOrganisme["code_ape"],
            "{IDINSCRIPTION}":
            FormateStr(self.dictInscription["IDINSCRIPTION"]),
            "{DATE_INSCRIPTION}":
            FormateDate(self.dictInscription["DATE_INSCRIPTION"]),
            "{EST_PARTI}":
            FormateBool(self.dictInscription["EST_PARTI"]),
            "{IDACTIVITE}":
            FormateStr(self.dictInscription["IDACTIVITE"]),
            "{ACTIVITE_NOM_LONG}":
            FormateStr(self.dictInscription["ACTIVITE_NOM_LONG"]),
            "{ACTIVITE_NOM_COURT}":
            FormateStr(self.dictInscription["ACTIVITE_NOM_COURT"]),
            "{IDGROUPE}":
            FormateStr(self.dictInscription["IDGROUPE"]),
            "{GROUPE_NOM_LONG}":
            FormateStr(self.dictInscription["GROUPE_NOM_LONG"]),
            "{GROUPE_NOM_COURT}":
            FormateStr(self.dictInscription["GROUPE_NOM_COURT"]),
            "{IDCATEGORIETARIF}":
            FormateStr(self.dictInscription["IDCATEGORIETARIF"]),
            "{NOM_CATEGORIE_TARIF}":
            FormateStr(self.dictInscription["NOM_CATEGORIE_TARIF"]),
            "{IDINDIVIDU}":
            FormateStr(self.dictInscription["IDINDIVIDU"]),
            "{INDIVIDU_CIVILITE_LONG}":
            FormateStr(self.dictInscription["INDIVIDU_CIVILITE_LONG"]),
            "{INDIVIDU_CIVILITE_COURT}":
            FormateStr(self.dictInscription["INDIVIDU_CIVILITE_COURT"]),
            "{INDIVIDU_GENRE}":
            FormateStr(self.dictInscription["INDIVIDU_GENRE"]),
            "{INDIVIDU_NOM}":
            FormateStr(self.dictInscription["INDIVIDU_NOM"]),
            "{INDIVIDU_PRENOM}":
            FormateStr(self.dictInscription["INDIVIDU_PRENOM"]),
            "{INDIVIDU_DATE_NAISS}":
            FormateDate(self.dictInscription["INDIVIDU_DATE_NAISS"]),
            "{INDIVIDU_AGE}":
            FormateStr(self.dictInscription["INDIVIDU_AGE"]),
            "{INDIVIDU_CP_NAISS}":
            FormateStr(self.dictInscription["INDIVIDU_CP_NAISS"]),
            "{INDIVIDU_VILLE_NAISS}":
            FormateStr(self.dictInscription["INDIVIDU_VILLE_NAISS"]),
            "{INDIVIDU_RUE}":
            FormateStr(self.dictInscription["INDIVIDU_RUE"]),
            "{INDIVIDU_CP}":
            FormateStr(self.dictInscription["INDIVIDU_CP"]),
            "{INDIVIDU_VILLE}":
            FormateStr(self.dictInscription["INDIVIDU_VILLE"]),
            "{INDIVIDU_PROFESSION}":
            FormateStr(self.dictInscription["INDIVIDU_PROFESSION"]),
            "{INDIVIDU_EMPLOYEUR}":
            FormateStr(self.dictInscription["INDIVIDU_EMPLOYEUR"]),
            "{INDIVIDU_TEL_DOMICILE}":
            FormateStr(self.dictInscription["INDIVIDU_TEL_DOMICILE"]),
            "{INDIVIDU_TEL_MOBILE}":
            FormateStr(self.dictInscription["INDIVIDU_TEL_MOBILE"]),
            "{INDIVIDU_FAX}":
            FormateStr(self.dictInscription["INDIVIDU_FAX"]),
            "{INDIVIDU_EMAIL}":
            FormateStr(self.dictInscription["INDIVIDU_EMAIL"]),
            "{INDIVIDU_TEL_PRO}":
            FormateStr(self.dictInscription["INDIVIDU_TEL_PRO"]),
            "{INDIVIDU_FAX_PRO}":
            FormateStr(self.dictInscription["INDIVIDU_FAX_PRO"]),
            "{INDIVIDU_EMAIL_PRO}":
            FormateStr(self.dictInscription["INDIVIDU_EMAIL_PRO"]),
            "{FAMILLE_NOM}":
            FormateStr(self.dictInscription["FAMILLE_NOM"]),
            "{FAMILLE_CAISSE}":
            FormateStr(self.dictInscription["FAMILLE_CAISSE"]),
            "{FAMILLE_REGIME}":
            FormateStr(self.dictInscription["FAMILLE_REGIME"]),
            "{FAMILLE_NUMALLOC}":
            FormateStr(self.dictInscription["FAMILLE_NUMALLOC"]),
        }

        # Récupération des infos de base individus et familles
        self.infosIndividus = UTILS_Infos_individus.Informations()
        dictValeurs.update(
            self.infosIndividus.GetDictValeurs(mode="famille",
                                               ID=IDfamille,
                                               formatChamp=True))
        dictValeurs.update(
            self.infosIndividus.GetDictValeurs(
                mode="individu",
                ID=self.dictInscription["IDINDIVIDU"],
                formatChamp=True))

        # Récupération des questionnaires
        Questionnaires = UTILS_Questionnaires.ChampsEtReponses(type="famille")
        for dictReponse in Questionnaires.GetDonnees(IDfamille):
            dictValeurs[dictReponse["champ"]] = dictReponse["reponse"]
            if dictReponse["controle"] == "codebarres":
                dictValeurs["{CODEBARRES_QUESTION_%d}" %
                            dictReponse["IDquestion"]] = dictReponse["reponse"]

        # Récupération du signataire
        infosSignataire = self.ctrl_signataire.GetInfos()
        if infosSignataire == None:
            dlg = wx.MessageDialog(
                self, _(u"Vous n'avez sélectionné aucun signataire !"),
                _(u"Annulation"), wx.OK | wx.ICON_EXCLAMATION)
            dlg.ShowModal()
            dlg.Destroy()
            return False

        nomSignataire = infosSignataire["nom"]
        fonctionSignataire = infosSignataire["fonction"]
        sexeSignataire = infosSignataire["sexe"]
        if sexeSignataire == "H":
            genreSignataire = u""
        else:
            genreSignataire = u"e"

        # Récupération et transformation du texte d'intro
        if self.ctrl_intro.GetValue() == True:
            textIntro = self.ctrl_texte_intro.GetValue()
            textIntro = textIntro.replace("{SIGNATAIRE_GENRE}",
                                          genreSignataire)
            textIntro = textIntro.replace("{SIGNATAIRE_NOM}", nomSignataire)
            textIntro = textIntro.replace("{SIGNATAIRE_FONCTION}",
                                          fonctionSignataire)
            for key, valeur in dictValeurs.items():
                if key.startswith("{"):
                    if valeur == None: valeur = ""
                    if type(valeur) == int: valeur = str(valeur)
                    textIntro = textIntro.replace(key, valeur)
            dictValeurs["intro"] = textIntro
        else:
            dictValeurs["intro"] = None

        # Tableau
        dictValeurs["tableau"] = self.ctrl_tableau.GetValue()

        for key, valeur in dictValeurs.items():
            if valeur == None: valeur = ""
            dictChampsFusion[key] = valeur

        # Préparation des données pour une sauvegarde dans l'historique
        self.dictSave = {}
        self.dictSave["activite"] = self.dictInscription["ACTIVITE_NOM_LONG"]
        self.dictSave["groupe"] = self.dictInscription["GROUPE_NOM_LONG"]

        # Récupération du modèle
        IDmodele = self.ctrl_modele.GetID()
        if IDmodele == None:
            dlg = wx.MessageDialog(
                self,
                _(u"Vous devez obligatoirement sélectionner un modèle !"),
                _(u"Erreur"), wx.OK | wx.ICON_EXCLAMATION)
            dlg.ShowModal()
            dlg.Destroy()
            return

        # Fabrication du PDF
        from Utils import UTILS_Impression_inscription
        UTILS_Impression_inscription.Impression(dictValeurs,
                                                IDmodele=IDmodele,
                                                nomDoc=nomDoc,
                                                afficherDoc=afficherDoc)

        return dictChampsFusion
コード例 #19
0
    def __init__(self, dictDonnees={}, nomDoc=FonctionsPerso.GenerationNomDoc("MANDAT_SEPA", "pdf"), afficherDoc=True):
        """ Imprime un mandat SEPA """
        styleSheet = getSampleStyleSheet()
        self.hauteur_page = defaultPageSize[1]
        self.largeur_page = defaultPageSize[0]
        self.inch = inch
        
        # Initialisation du PDF
        PAGE_HEIGHT=defaultPageSize[1]
        PAGE_WIDTH=defaultPageSize[0]
        doc = SimpleDocTemplate(nomDoc)
        story = []
        
        largeurContenu = 500
        dataTableau = []

        # ---------------- Titre du document ----------------------------------------------------------------
        
        largeursColonnes = (100, largeurContenu-100-100, 100)

        titre = Paragraph(u"""<para align=center fontSize=16><b>Mandat de prélèvement SEPA</b></para>""", styleSheet['BodyText'])
        dataTableau.append([titre,])

        # Nom de l'organisateur
        ligne1 = Paragraph(u"""<para align=center fontSize=10>%s - ICS n°%s</para>""" % (dictDonnees["organisateur"]["nom"], dictDonnees["ics"]), styleSheet['BodyText'])
        ligne2 = Paragraph(u"""<para align=center fontSize=8>%s %s %s</para>""" % (dictDonnees["organisateur"]["rue"], dictDonnees["organisateur"]["cp"], dictDonnees["organisateur"]["ville"]), styleSheet['BodyText'])
        dataTableau.append([ [ligne1, ligne2],])

        # Mention légale obligatoire sur le SEPA
        mention_sepa = Paragraph(u"""
        <para align=left leading=10 fontSize=7>En signant ce mandat, vous autorisez %s à envoyer des instructions à votre banque pour débiter votre compte, et votre banque à débiter votre compte conformément aux instructions de %s.
        Vous bénéficiez du droit d'être remboursé par votre banque selon les conditions décrites dans la convention que vous avez passée avec elle.
        Une demande de remboursement doit être présentée dans les 8 semaines suivant la date de début de votre compte pour un prélèvement autorisé.
        Vos droits concernant le prélèvement sont expliqués dans un document que vous pouvez obtenir auprès de votre banque.
        </para>""" % (dictDonnees["organisateur"]["nom"], dictDonnees["organisateur"]["nom"]), styleSheet['BodyText'])
        dataTableau.append([mention_sepa,])
        
        # RUM
        dataTableau.append([Paragraph(_(u"<para align=center fontSize=8><b>Référence unique du mandat</b></para>"), styleSheet['BodyText']),])
        dataTableauTemp = [
            [Paragraph(_(u"<para align=right fontSize=10>RUM :</para>"), styleSheet['BodyText']), self.Cases(modele=[1 for x in range(38)], texte=dictDonnees["rum"])],
            ]
        style = TableStyle([
                            ('VALIGN', (0, 0), (-1, -1), "MIDDLE"), 
                            ])
        tableauTemp = Table(dataTableauTemp, [100, 400])
        tableauTemp.setStyle(style)
        dataTableau.append([tableauTemp,])

        # Nom et coordonnées et débiteur
        dataTableau.append([Paragraph(_(u"<para align=center fontSize=8><b>Identité et coordonnées du débiteur</b></para>"), styleSheet['BodyText']),])
        dataTableauTemp = [
            [Paragraph(_(u"<para align=right fontSize=10>Nom et prénom :</para>"), styleSheet['BodyText']), self.Cases(modele=[1 for x in range(38)], texte=dictDonnees["titulaire_nom"])],
            [Paragraph(_(u"<para align=right fontSize=10>Adresse :</para>"), styleSheet['BodyText']), self.Cases(modele=[1 for x in range(38)], texte=dictDonnees["titulaire_rue"])],
            [Paragraph(_(u"<para align=right fontSize=10>Code postal :</para>"), styleSheet['BodyText']), self.Cases(modele=[1 for x in range(38)], texte=dictDonnees["titulaire_cp"])],
            [Paragraph(_(u"<para align=right fontSize=10>Ville :</para>"), styleSheet['BodyText']), self.Cases(modele=[1 for x in range(38)], texte=dictDonnees["titulaire_ville"])],
            ]
        style = TableStyle([
                            ('VALIGN', (0, 0), (-1, -1), "MIDDLE"), 
                            ])
        tableauTemp = Table(dataTableauTemp, [100, 400])
        tableauTemp.setStyle(style)
        dataTableau.append([tableauTemp,])

        # Compte à débiter
        dataTableau.append([Paragraph(_(u"<para align=center fontSize=8><b>Compte à débiter</b></para>"), styleSheet['BodyText']),])
        
        iban = self.Cases(modele=[1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1], texte=dictDonnees["iban"])
        bic = self.Cases(modele=[1 for x in range(11)], texte=dictDonnees["bic"])
        dataTableauTemp = [
            [Paragraph(_(u"<para align=right fontSize=10>IBAN :</para>"), styleSheet['BodyText']), iban],
            [Paragraph(_(u"<para align=right fontSize=10>BIC :</para>"), styleSheet['BodyText']), bic],
            ]
        style = TableStyle([
                            ('VALIGN', (0, 0), (-1, -1), "MIDDLE"), 
                            ])
        tableauTemp = Table(dataTableauTemp, [100, 400])
        tableauTemp.setStyle(style)
        dataTableau.append([tableauTemp,])
        
        # Type de paiement
        dataTableau.append([Paragraph(_(u"<para align=center fontSize=8><b>Type de paiement</b></para>"), styleSheet['BodyText']),])
        
        if dictDonnees["typeMandat"] == "recurrent" : 
            recurrent = "X"
            ponctuel = ""
        else :
            recurrent = ""
            ponctuel = "X"
        dataTableauTemp = [
            "", 
            Paragraph(_(u"<para align=left fontSize=10>Paiement récurrent :</para>"), styleSheet['BodyText']), 
            self.Cases(modele=[1,], texte=recurrent),
            "",
            Paragraph(_(u"<para align=left fontSize=10>Paiement ponctuel :</para>"), styleSheet['BodyText']), 
            self.Cases(modele=[1,], texte=ponctuel),
            ]
        style = TableStyle([
                            ('VALIGN', (0, 0), (-1, -1), "MIDDLE"), 
                            ('ALIGN', (0, 0), (-1, -1), "CENTER"), 
                            ])
        tableauTemp = Table([dataTableauTemp,], [100, 105, 10, 50, 105, 10])
        tableauTemp.setStyle(style)
        dataTableau.append([tableauTemp,])
        
        # Signature
        dataTableau.append([Paragraph(_(u"<para align=center fontSize=8><b>Signature</b></para>"), styleSheet['BodyText']),])
        dataTableauTemp = [
            [Paragraph(_(u"<para align=right fontSize=10>Fait à :</para>"), styleSheet['BodyText']), self.Cases(modele=[1 for x in range(38)])],
            [Paragraph(_(u"<para align=right fontSize=10>Le :</para>"), styleSheet['BodyText']), self.Cases(modele=[1, 1, 2, 1, 1, 2, 1, 1, 1, 1], texte="  /  /    ")],
            [Paragraph(_(u"<para align=right fontSize=10>Signature :</para>"), styleSheet['BodyText']), ""],
            ["", ""],
            ["", ""],
            ["", ""],
            ["", ""],
            ["", ""],
            ]
        style = TableStyle([
                            ('VALIGN', (0, 0), (-1, -1), "MIDDLE"), 
                            ])
        tableauTemp = Table(dataTableauTemp, [100, 400])
        tableauTemp.setStyle(style)
        dataTableau.append([tableauTemp,])

        # Mention CNIL
        mention_cnil = Paragraph(u"""
        <para align=left leading=10 fontSize=7>Les informations contenus dans le présent mandat, qui doit être complété, sont destinés à n'être utilisées par le créancier que pour la gestion
        de sa relation avec son client. Elles pourront donner lieu à l'exercice, par ce dernier, de ses droits d'oppositions, d'accès et de rectifications tels 
        que prévus aux articles 38 et suivants de la loi n°78-17 du 6 janvier 1978 relative à l'informatique, aux fichiers et aux libertés.
        </para>""", styleSheet['BodyText'])
        dataTableau.append([mention_cnil,])
        
        
        
        
        # Formatage du tableau principal
        listeStyles = [
            ('GRID', (0, 0), (-1, -1), 0.25, colors.black), 
            ('VALIGN', (0, 0), (-1, -1), "MIDDLE"), 
            ('TOPPADDING', (0, 0), (0, 0), 20), 
            ('BOTTOMPADDING', (0, 0), (0, 0), 25), 
            ]
        for ligne in (0, 3, 5, 7, 9, 11) :
            listeStyles.append(('BACKGROUND', (0, ligne), (-1, ligne), (0.8, 0.8, 0.8) ))
        style = TableStyle(listeStyles)
        tableau = Table(dataTableau, [largeurContenu,])
        tableau.setStyle(style)
        dataTableau.append(tableau)
        story.append(tableau)
            
        # Enregistrement 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
コード例 #20
0
    def Apercu(self):
        """ Impression tableau de données """
        if self.GetNumberRows() == 0 or self.GetNumberCols() == 0:
            dlg = wx.MessageDialog(self, _(u"Il n'y a rien à imprimer !"),
                                   "Erreur", wx.OK | wx.ICON_EXCLAMATION)
            dlg.ShowModal()
            dlg.Destroy()
            return None

        avecCouleurs = True

        from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle
        from reportlab.lib.pagesizes import A4
        from reportlab.lib import colors
        from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle

        def ConvertCouleur(couleur):
            r, g, b = couleur
            return r / 255.0, g / 255.0, b / 255.0

        # Récupération des données du tableau
        tableau = self
        nbreColonnes = tableau.GetNumberCols()
        nbreLignes = tableau.GetNumberRows()

        # Initialisation du tableau
        story = []
        dataTableau = []
        listeCouleurs = []

        # Création des colonnes
        largeursColonnes = []
        largeurColonne = 33
        largeurColonneLabel = 90
        for col in range(0, nbreColonnes + 1):
            if col == 0: largeursColonnes.append(largeurColonneLabel)
            else: largeursColonnes.append(largeurColonne)

        listeStyles = [
            ('GRID', (0, 0), (-1, -1), 0.25,
             colors.black),  # Crée la bordure noire pour tout le tableau
            ('VALIGN', (0, 0), (-1, -1),
             'MIDDLE'),  # Centre verticalement toutes les cases
            ('ALIGN', (0, 0), (-1, 0),
             'CENTRE'),  # Centre les labels de colonne
            ('ALIGN', (1, 1), (-1, -1), 'CENTRE'),  # Valeurs à gauche
            ('ALIGN', (0, 1), (0, -1),
             'CENTRE'),  # Colonne Label Ligne centrée
            (
                'FONT', (0, 0), (-1, -1), "Helvetica", 6
            ),  # Donne la police de caract. + taille de police de la ligne de total
            (
                'FONT', (0, 0), (-1, 0), "Helvetica-Bold", 6
            ),  # Donne la police de caract. + taille de police de la ligne de total
        ]

        # Création de l'entete
        valeursLigne = [
            "",
        ]
        for numColonne in range(0, nbreColonnes):
            labelColonne = tableau.GetColLabelValue(numColonne)
            valeursLigne.append(labelColonne)
        dataTableau.append(valeursLigne)

        # Création des lignes
        for numLigne in range(0, nbreLignes):
            labelLigne = tableau.GetRowLabelValue(numLigne)
            valeursLigne = [
                labelLigne,
            ]
            for numCol in range(0, nbreColonnes):
                valeurCase = tableau.GetCellValue(numLigne, numCol)
                couleurCase = tableau.GetCellBackgroundColour(numLigne, numCol)
                if couleurCase != (255, 255, 255,
                                   255) and avecCouleurs == True:
                    r, g, b = ConvertCouleur(couleurCase)
                    listeStyles.append(
                        ('BACKGROUND', (numCol + 1, numLigne + 1),
                         (numCol + 1, numLigne + 1), (r, g, b)))
                if numLigne == 0:
                    valeurCase = valeurCase.replace(" ", "\n")
                valeursLigne.append(valeurCase)
            dataTableau.append(valeursLigne)

        # Style du tableau
        style = TableStyle(listeStyles)

        # Création du tableau
        tableau = Table(dataTableau, largeursColonnes, hAlign='LEFT')
        tableau.setStyle(style)
        story.append(tableau)
        story.append(Spacer(0, 20))

        # Calcul du format de la page
        tailleMarge = 20
        if sum(largeursColonnes) > A4[0] - (tailleMarge * 2):
            hauteur, largeur = A4
        else:
            largeur, hauteur = A4

        # Création du titre du document
        dataTableau = []
        largeurContenu = largeur - (tailleMarge * 2)
        largeursColonnes = ((largeurContenu - 100, 100))
        dateDuJour = DateEngFr(str(datetime.date.today()))
        dataTableau.append(
            (_(u"Synthèse des consommations"), _(u"%s\nEdité le %s") %
             (UTILS_Organisateur.GetNom(), dateDuJour)))
        style = TableStyle([
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ('ALIGN', (0, 0), (0, 0), 'LEFT'),
            ('FONT', (0, 0), (0, 0), "Helvetica-Bold", 16),
            ('ALIGN', (1, 0), (1, 0), 'RIGHT'),
            ('FONT', (1, 0), (1, 0), "Helvetica", 6),
        ])
        tableau = Table(dataTableau, largeursColonnes)
        tableau.setStyle(style)
        story.insert(0, tableau)
        story.insert(1, Spacer(0, 10))

        # Insertion du label Paramètres
        styleA = ParagraphStyle(name="A",
                                fontName="Helvetica",
                                fontSize=6,
                                spaceAfter=20)
        story.insert(2, Paragraph(self.labelParametres, styleA))

        # Enregistrement du PDF
        nomDoc = FonctionsPerso.GenerationNomDoc("SYNTHESE_CONSO", "pdf")
        if sys.platform.startswith("win"): nomDoc = nomDoc.replace("/", "\\")
        doc = SimpleDocTemplate(nomDoc,
                                pagesize=(largeur, hauteur),
                                leftMargin=tailleMarge,
                                rightMargin=tailleMarge,
                                topMargin=tailleMarge,
                                bottomMargin=tailleMarge)
        doc.build(story)

        # Affichage du PDF
        FonctionsPerso.LanceFichierExterne(nomDoc)
コード例 #21
0
    def Imprimer(self, event=None):
        # Création du PDF
        from reportlab.platypus import SimpleDocTemplate, Spacer, Table, TableStyle
        from reportlab.rl_config import defaultPageSize
        from reportlab.lib import colors
        self.hauteur_page = defaultPageSize[1]
        self.largeur_page = defaultPageSize[0]

        # Initialisation du PDF
        nomDoc = FonctionsPerso.GenerationNomDoc("LISTE_ATTENTE", "pdf")
        if sys.platform.startswith("win"): nomDoc = nomDoc.replace("/", "\\")
        doc = SimpleDocTemplate(nomDoc, topMargin=30, bottomMargin=30)
        story = []

        largeurContenu = 520

        # Création du titre du document
        def Header():
            dataTableau = []
            largeursColonnes = ((420, 100))
            dateDuJour = UTILS_Dates.DateEngFr(str(datetime.date.today()))
            if self.mode == "attente":
                titre = _(u"Inscriptions en attente")
            else:
                titre = _(u"Inscriptions refusées")
            dataTableau.append((titre, _(u"%s\nEdité le %s") %
                                (UTILS_Organisateur.GetNom(), dateDuJour)))
            style = TableStyle([
                ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                ('ALIGN', (0, 0), (0, 0), 'LEFT'),
                ('FONT', (0, 0), (0, 0), "Helvetica-Bold", 16),
                ('ALIGN', (1, 0), (1, 0), 'RIGHT'),
                ('FONT', (1, 0), (1, 0), "Helvetica", 6),
            ])
            tableau = Table(dataTableau, largeursColonnes)
            tableau.setStyle(style)
            story.append(tableau)
            story.append(Spacer(0, 20))

        # Insère un header
        Header()

        # Un tableau par date
        for nom_activite, listeGroupes in self.listeImpression:

            dataTableau = []
            largeursColonnes = [180, 180, 160]

            dataTableau.append((nom_activite, "", ""))

            # Groupes
            listeIndexGroupes = []
            indexLigne = 0
            for nomGroupe, listeIndividus in listeGroupes:
                indexLigne += 1
                listeIndexGroupes.append(indexLigne)

                dataTableau.append((nomGroupe, "", ""))

                # Individus
                for dictIndividu in listeIndividus:
                    placeDispo = dictIndividu["placeDispo"]
                    texteIndividu = dictIndividu["texteIndividu"]
                    texteDateSaisie = _(
                        u"Saisie le %s") % dictIndividu["texteDateSaisie"]
                    nomCategorie = dictIndividu["nomCategorie"]
                    dataTableau.append(
                        (texteIndividu, texteDateSaisie, nomCategorie))
                    indexLigne += 1

            couleurFond = (0.8, 0.8, 1)  # Vert -> (0.5, 1, 0.2)

            listeStyles = [
                ('VALIGN', (0, 0), (-1, -1),
                 'MIDDLE'),  # Centre verticalement toutes les cases
                ('FONT', (0, 0), (-1, -1), "Helvetica",
                 7),  # Donne la police de caract. + taille de police 
                ('GRID', (0, 0), (-1, -1), 0.25,
                 colors.black),  # Crée la bordure noire pour tout le tableau
                ('ALIGN', (0, 1), (-1, -1), 'CENTRE'),  # Centre les cases
                ('ALIGN', (0, 1), (-1, 1),
                 'CENTRE'),  # Ligne de labels colonne alignée au centre
                ('FONT', (0, 1), (-1, 1), "Helvetica", 6
                 ),  # Donne la police de caract. + taille de police des labels
                (
                    'SPAN', (0, 0), (-1, 0)
                ),  # Fusionne les lignes du haut pour faire le titre du groupe
                (
                    'FONT', (0, 0), (0, 0), "Helvetica-Bold", 10
                ),  # Donne la police de caract. + taille de police du titre de groupe
                ('BACKGROUND', (0, 0), (-1, 0),
                 couleurFond),  # Donne la couleur de fond du titre de groupe
            ]

            # Formatage des lignes "Activités"
            for indexGroupe in listeIndexGroupes:
                listeStyles.append(
                    ('SPAN', (0, indexGroupe), (-1, indexGroupe)))
                listeStyles.append(('FONT', (0, indexGroupe),
                                    (-1, indexGroupe), "Helvetica-Bold", 7))
                listeStyles.append(
                    ('ALIGN', (0, indexGroupe), (-1, indexGroupe), 'LEFT'))

            # Création du tableau
            tableau = Table(dataTableau, largeursColonnes)
            tableau.setStyle(TableStyle(listeStyles))
            story.append(tableau)
            story.append(Spacer(0, 20))

        # Enregistrement du PDF
        doc.build(story)

        # Affichage du PDF
        FonctionsPerso.LanceFichierExterne(nomDoc)
コード例 #22
0
    def ImpressionListe(self):
        """ Imprime la liste des comptes sélectionnés """
        # Récupère les noms des colonnes
        listeColonnes = []
        for numColonne in range(0, self.GetColumnCount()):
            labelColonne = self.GetColumnText(numColonne)
            largeurColonne = self.GetColumnWidth(numColonne)
            listeColonnes.append((labelColonne, largeurColonne / 1.3))
        # Récupère les lignes du tableau
        listeLignes = []
        item = self.root
        for index in range(0, self.GetChildrenCount(self.root)):
            ligne = []
            item = self.GetNext(item)
            if self.GetPyData(item)["type"] == "compte" and self.IsItemChecked(
                    item):
                for numColonne in range(0, self.GetColumnCount()):
                    texte = item.GetText(numColonne)
                    ligne.append(texte)
                listeLignes.append(ligne)

        # Création du PDF
        from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, PageBreak
        from reportlab.platypus.flowables import ParagraphAndImage, Image
        from reportlab.rl_config import defaultPageSize
        from reportlab.lib.units import inch, cm
        from reportlab.lib.utils import ImageReader
        from reportlab.lib import colors
        from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
        self.hauteur_page = defaultPageSize[1]
        self.largeur_page = defaultPageSize[0]

        # Initialisation du PDF
        PAGE_HEIGHT = defaultPageSize[1]
        PAGE_WIDTH = defaultPageSize[0]
        nomDoc = FonctionsPerso.GenerationNomDoc("LISTE_ATTESTATIONS", "pdf")
        if sys.platform.startswith("win"): nomDoc = nomDoc.replace("/", "\\")
        doc = SimpleDocTemplate(nomDoc, topMargin=30, bottomMargin=30)
        story = []

        largeurContenu = 520

        # Création du titre du document
        def Header():
            dataTableau = []
            largeursColonnes = ((420, 100))
            dateDuJour = DateEngFr(str(datetime.date.today()))
            dataTableau.append(
                (_(u"Liste des attestations"), _(u"%s\nEdité le %s") %
                 (UTILS_Organisateur.GetNom(), dateDuJour)))
            style = TableStyle([
                ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                ('ALIGN', (0, 0), (0, 0), 'LEFT'),
                ('FONT', (0, 0), (0, 0), "Helvetica-Bold", 16),
                ('ALIGN', (1, 0), (1, 0), 'RIGHT'),
                ('FONT', (1, 0), (1, 0), "Helvetica", 6),
            ])
            tableau = Table(dataTableau, largeursColonnes)
            tableau.setStyle(style)
            story.append(tableau)
            story.append(Spacer(0, 20))

        # Insère un header
        Header()

        # Noms de colonnes
        dataTableau = []
        largeursColonnes = []

        ligne = []
        for labelColonne, largeurColonne in listeColonnes:
            ligne.append(labelColonne)
            largeursColonnes.append(largeurColonne)
        dataTableau.append(ligne)

        # Création des lignes
        for ligne in listeLignes:
            dataTableau.append(ligne)

        couleurFond = (0.9, 0.9, 0.9)
        listeStyles = [
            ('VALIGN', (0, 0), (-1, -1),
             'MIDDLE'),  # Centre verticalement toutes les cases
            ('FONT', (0, 0), (-1, -1), "Helvetica",
             7),  # Donne la police de caract. + taille de police 
            ('GRID', (0, 0), (-1, -1), 0.25,
             colors.black),  # Crée la bordure noire pour tout le tableau
            ('ALIGN', (0, 0), (-1, -1), 'CENTRE'),  # Centre les cases
            ('BACKGROUND', (0, 0), (-1, 0),
             couleurFond),  # Donne la couleur de fond du titre de groupe
        ]

        # Création du tableau
        tableau = Table(dataTableau, largeursColonnes)
        tableau.setStyle(TableStyle(listeStyles))
        story.append(tableau)

        # Enregistrement du PDF
        doc.build(story)

        # Affichage du PDF
        FonctionsPerso.LanceFichierExterne(nomDoc)
コード例 #23
0
    def Imprimer(self, event=None):
        # Création du PDF
        from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle
        from reportlab.lib.pagesizes import A4
        from reportlab.lib import colors
        from reportlab.lib.styles import ParagraphStyle

        hauteur_page = A4[1]
        largeur_page = A4[0]

        # Initialisation du PDF
        nomDoc = FonctionsPerso.GenerationNomDoc("EVENEMENTS", "pdf")
        if sys.platform.startswith("win"): nomDoc = nomDoc.replace("/", "\\")
        doc = SimpleDocTemplate(nomDoc,
                                pagesize=(largeur_page, hauteur_page),
                                topMargin=30,
                                bottomMargin=30,
                                leftMargin=40,
                                rightMargin=40)
        story = []

        # Création du titre du document
        dataTableau = []
        largeursColonnes = ((largeur_page - 175, 100))
        dateDuJour = UTILS_Dates.DateEngFr(str(datetime.date.today()))
        dataTableau.append((_(u"Evènements"), _(u"%s\nEdité le %s") %
                            (UTILS_Organisateur.GetNom(), dateDuJour)))
        style = TableStyle([
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ('ALIGN', (0, 0), (0, 0), 'LEFT'),
            ('FONT', (0, 0), (0, 0), "Helvetica-Bold", 16),
            ('ALIGN', (1, 0), (1, 0), 'RIGHT'),
            ('FONT', (1, 0), (1, 0), "Helvetica", 6),
        ])
        tableau = Table(dataTableau, largeursColonnes)
        tableau.setStyle(style)
        story.append(tableau)
        story.append(Spacer(0, 10))

        # Intro
        styleA = ParagraphStyle(name="A",
                                fontName="Helvetica",
                                fontSize=6,
                                spaceAfter=20)
        #story.append(Paragraph(self.labelParametres, styleA))

        # Tableau
        dataTableau = []
        largeurColonnesSuivantes = 70
        largeurColonne1 = largeur_page - 80 - 1.0 * (
            len(self.dictImpression["entete"]) - 1) * largeurColonnesSuivantes
        largeursColonnes = [
            largeurColonne1,
        ]
        for x in range(0, len(self.dictImpression["entete"]) - 1):
            largeursColonnes.append(largeurColonnesSuivantes)

        # Entetes labels
        dataTableau.append(self.dictImpression["entete"])

        # Contenu du tableau
        listeRubriques = ("contenu", "total")
        for rubrique in listeRubriques:
            listeLignes = self.dictImpression[rubrique]

            for ligne in listeLignes:
                dataTableau.append(ligne)

        positionLigneTotal = len(self.dictImpression["contenu"]) + 1
        listeStyles = [
            ('VALIGN', (0, 0), (-1, -1),
             'MIDDLE'),  # Centre verticalement toutes les cases
            ('FONT', (0, 0), (-1, -1), "Helvetica",
             7),  # Donne la police de caract. + taille de police
            ('GRID', (0, 0), (-1, -1), 0.25,
             colors.black),  # Crée la bordure noire pour tout le tableau
            ('ALIGN', (1, 0), (-1, -1), 'CENTRE'),  # Centre les cases
            ('BACKGROUND', (0, 0), (-1, 0),
             (0.6, 0.6, 0.6)),  # Donne la couleur de fond du label
            ('BACKGROUND', (0, positionLigneTotal), (-1, positionLigneTotal),
             (0.8, 0.8, 0.8)),  # Donne la couleur de fond du total
        ]

        # Formatage des lignes "Activités"
        for indexColoration, typeColoration in self.dictImpression[
                "coloration"]:

            if typeColoration == "activite":
                listeStyles.append(
                    ('FONT', (0, indexColoration + 1),
                     (-1, indexColoration + 1), "Helvetica-Bold", 7))
                listeStyles.append(
                    ('BACKGROUND', (0, indexColoration + 1),
                     (-1, indexColoration + 1), (0.91, 0.91, 0.91)))

            if typeColoration == "regroup":
                listeStyles.append(
                    ('FONT', (0, indexColoration + 1),
                     (-1, indexColoration + 1), "Helvetica-Bold", 7))
                listeStyles.append(('TEXTCOLOR', (0, indexColoration + 1),
                                    (-1, indexColoration + 1), (1, 1, 1)))
                listeStyles.append(('BACKGROUND', (0, indexColoration + 1),
                                    (-1, indexColoration + 1), (0, 0, 0)))

        # Création du tableau
        tableau = Table(dataTableau, largeursColonnes, repeatRows=1)
        tableau.setStyle(TableStyle(listeStyles))
        story.append(tableau)
        story.append(Spacer(0, 20))

        # Enregistrement du PDF
        doc.build(story)

        # Affichage du PDF
        FonctionsPerso.LanceFichierExterne(nomDoc)
コード例 #24
0
    def __init__(self,
                 dictDonnees={},
                 nomDoc=FonctionsPerso.GenerationNomDoc(
                     "RECUDONAUXOEUVRES", "pdf"),
                 afficherDoc=True):
        """ Imprime un reçu Dons aux Oeuvres """

        from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle
        from reportlab.rl_config import defaultPageSize
        from reportlab.lib.units import inch, cm
        from reportlab.lib import colors
        from reportlab.lib.styles import getSampleStyleSheet
        styleSheet = getSampleStyleSheet()
        self.hauteur_page = defaultPageSize[1]
        self.largeur_page = defaultPageSize[0]
        self.inch = inch

        # Initialisation du PDF
        PAGE_HEIGHT = defaultPageSize[1]
        PAGE_WIDTH = defaultPageSize[0]
        doc = SimpleDocTemplate(nomDoc)
        story = []

        # ---------------- Titre du document ----------------------------------------------------------------

        largeursColonnes = ((300, 150))

        txt1 = Paragraph(
            u"""
        <para align=center fontSize=16><b>Reçu Dons Aux Oeuvres</b></para>
        """, styleSheet['BodyText'])

        txt2 = Paragraph(
            u"""
        <para align=center fontSize=8>Numéro d'ordre du reçu</para>
        """, styleSheet['BodyText'])

        txt3 = Paragraph(
            u"""
        <para align=center fontSize=9>(Article 200-5 du Code Général des Impôts)</para>
        """, styleSheet['BodyText'])

        txt4 = Paragraph(
            u"""
        <para align=center fontsize=16>%s</para>
        """ % dictDonnees["numero"], styleSheet['BodyText'])

        # Valeurs du tableau
        dataTableau = [
            ["", txt2],
            [[txt1, txt3], txt4],
        ]

        # Style du tableau
        style = TableStyle([
            ('GRID', (1, 1), (1, 1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), "MIDDLE"),
        ])
        tableau = Table(dataTableau, largeursColonnes)
        tableau.setStyle(style)
        story.append(tableau)
        story.append(Spacer(0, 20))

        # ------------ Corps du document -----------------------------------------------------
        largeursColonnes = ((450, ))

        # Texte du tableau
        txt10 = Paragraph(
            u"""
        <para align=center><b>Bénéficiaire des versements</b></para>
        """, styleSheet['BodyText'])

        txt20 = Paragraph(
            u"""
        <br/>
        Nom ou dénomination : %s<br/>
        <br/>
        Adresse : %s<br/>
        <br/>
        Objet : %s<br/>
        <br/>
        %s<br/>   
        <br/>     
        """ % (dictDonnees["nom_organisme"], dictDonnees["adresse_organisme"],
               dictDonnees["objet_organisme"], dictDonnees["type_organisme"]),
            styleSheet['BodyText'])

        # Donateur
        txt30 = Paragraph(
            u"""
        <para align=center><b>Donateur</b></para>
        """, styleSheet['BodyText'])

        txt40 = Paragraph(
            u"""
        <br/>
        Nom : %s<br/>
        <br/>
        Adresse : %s
        <br/>
        <br/>
        """ % (dictDonnees["nom_donateur"], dictDonnees["adresse_donateur"]),
            styleSheet['BodyText'])

        # Montant
        txt50 = Paragraph(
            u"""
        <para align=center><b>Versement</b></para>
        """, styleSheet['BodyText'])

        txt60 = Paragraph(
            u"""
        <br/>
        Le bénéficiaire reconnaît avoir reçu au titre des versements ouvrant droit à réduction d'impôt la somme de : <br/>
        <br/>
        """, styleSheet['BodyText'])

        txt70 = Paragraph(
            u"""
        <para align=center fontSize=12>
        <b>%s</b><br/>
        <br/>
        <b>Soit %s</b>
        </para>
        """ %
            (dictDonnees["montant_chiffres"], dictDonnees["montant_lettres"]),
            styleSheet['BodyText'])

        txt80 = Paragraph(
            u"""
        <br/>
        Date du paiement : %s<br/>
        <br/>
        Mode de versement : %s
        <br/>
        <br/>
        """ % (dictDonnees["date_versement"], dictDonnees["mode"]),
            styleSheet['BodyText'])

        txt100 = Paragraph(
            u"""
        Fait en double exemplaire<br/>
        (Un pour le donateur - un pour l'association)<br/>
        <br/>
        """, styleSheet['BodyText'])

        if dictDonnees["date_edition"] != u"":
            date_edition = _(u"Le %s") % dictDonnees["date_edition"]
        else:
            dictDonnees["date_edition"] = u""

        txt110 = Paragraph(
            u"""
        <para align=right rightIndent=50>
        Date et signature
        <br/>
        <br/>
        %s
        <br/>
        <br/>
        <br/>
        <br/>
        <br/>
        <br/>
        </para>
        """ % date_edition, styleSheet['BodyText'])

        # Valeurs du tableau
        dataTableau = [
            [
                txt10,
            ],
            [
                txt20,
            ],
            [
                "",
            ],
            [
                txt30,
            ],
            [
                txt40,
            ],
            [
                "",
            ],
            [
                txt50,
            ],
            [
                [txt60, txt70, txt80, txt100, txt110],
            ],
        ]

        # Style du tableau
        style = TableStyle([
            ('GRID', (0, 0), (0, 1), 0.25, colors.black),
            ('GRID', (0, 3), (0, 4), 0.25, colors.black),
            ('GRID', (0, 6), (0, 7), 0.25, colors.black),
        ])
        tableau = Table(dataTableau, largeursColonnes)
        tableau.setStyle(style)
        story.append(tableau)
        story.append(Spacer(0, 20))

        # Enregistrement 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
コード例 #25
0
    def __init__(self,
                 titre="",
                 annee=2009,
                 afficher_we=True,
                 afficher_vacances=True,
                 afficher_feries=True,
                 afficher_heures=True,
                 afficher_couleurs_categories=True,
                 afficher_legende=True,
                 afficher_heures_mois=True):

        self.titre = titre
        self.annee = annee

        global AFFICHER_WE, AFFICHER_VACANCES, AFFICHER_FERIES, AFFICHER_HEURES, AFFICHER_COULEUR_CATEGORIES, AFFICHER_LEGENDE, AFFICHER_HEURES_MOIS
        AFFICHER_WE = afficher_we
        AFFICHER_VACANCES = afficher_vacances
        AFFICHER_FERIES = afficher_feries
        AFFICHER_HEURES = afficher_heures
        AFFICHER_COULEUR_CATEGORIES = afficher_couleurs_categories
        AFFICHER_LEGENDE = afficher_legende
        AFFICHER_HEURES_MOIS = afficher_heures_mois

        largeurMois = 55
        espaceMois = 5

        # Paramètres du PDF
        nomDoc = FonctionsPerso.GenerationNomDoc("CALENDRIER_ANNUEL", "pdf")
        if "win" in sys.platform: nomDoc = nomDoc.replace("/", "\\")
        taillePage = landscape(A4)
        HAUTEUR_PAGE = defaultPageSize[0]
        LARGEUR_PAGE = defaultPageSize[1]

        doc = SimpleDocTemplate(nomDoc,
                                pagesize=taillePage,
                                topMargin=50,
                                bottomMargin=50)
        story = []

        # Création du titre du document
        largeursColonnesTitre = ((615, 100))
        dateDuJour = DatetimeDateEnStr(datetime.date.today())
        dataTableauTitre = [
            (_(u"Planning %d de %s") % (self.annee, self.titre),
             _(u"Edité le %s") % dateDuJour),
        ]
        styleTitre = TableStyle([
            ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'TOP'),
            ('ALIGN', (0, 0), (0, 0), 'LEFT'),
            ('FONT', (0, 0), (0, 0), "Helvetica-Bold", 16),
            ('ALIGN', (1, 0), (1, 0), 'RIGHT'),
            ('FONT', (1, 0), (1, 0), "Helvetica", 6),
        ])
        tableauTitre = Table(dataTableauTitre, largeursColonnesTitre)
        tableauTitre.setStyle(styleTitre)
        story.append(tableauTitre)
        story.append(Spacer(0, 20))

        # Récupération des données
        self.dictPresences, self.dictTotauxCategories = {}, {
        }  #self.ImportPresences(self.IDpersonne, self.annee)

        global DICT_CATEGORIES, LISTE_VACANCES, LISTE_FERIES
        DICT_CATEGORIES = self.ImportCategories()
        LISTE_VACANCES = self.Importation_Vacances()
        LISTE_FERIES = self.Importation_Feries()

        # Création du tableau
        dataTableau = []
        enteteTableau = []
        largeursColonnes = []
        styleTableau = []

        listeMois = (_(u"Janvier"), _(u"Février"), _(u"Mars"), _(u"Avril"),
                     _(u"Mai"), _(u"Juin"), _(u"Juillet"), _(u"Août"),
                     _(u"Septembre"), _(u"Octobre"), _(u"Novembre"),
                     _(u"Décembre"))
        listeJours = (u"L", u"M", u"M", u"J", u"V", u"S", u"D")

        # Création de l'entete du tableau
        index = 1
        for nomMois in listeMois:
            largeursColonnes.append(largeurMois)
            if index != 12: largeursColonnes.append(espaceMois)
            enteteTableau.append(nomMois)
            if index != 12: enteteTableau.append("")
            index += 1
        dataTableau.append(enteteTableau)
        styleTableau.append(('ALIGN', (0, 0), (-1, 0), 'CENTRE'))
        styleTableau.append(('FONT', (0, 0), (-1, 0), "Helvetica-Bold", 8))

        # Création des lignes vides
        for x in range(1, 33):
            ligne = []
            for case in range(0, 23):
                ligne.append(None)
            dataTableau.append(ligne)

        # Style général du tableau
        styleTableau.append(('FONT', (0, 1), (-1, -1), "Helvetica", 7))
        styleTableau.append(('LEFTPADDING', (0, 1), (-1, -1), 0))
        styleTableau.append(('RIGHTPADDING', (0, 1), (-1, -1), 0))
        styleTableau.append(('TOPPADDING', (0, 1), (-1, -1), 0))
        styleTableau.append(('BOTTOMPADDING', (0, 1), (-1, -1), 0))

        # Remplissage du tableau
        numMois = 1
        for nomMois in listeMois:
            # Création d'un mois
            totalMinutesMois = 0
            numWeekDay, nbreJoursMois = calendar.monthrange(
                self.annee, numMois)
            numCol = (numMois * 2) - 2

            for numJour in range(1, nbreJoursMois + 1):
                # Création des labels des dates
                dateDD = datetime.date(year=self.annee,
                                       month=numMois,
                                       day=numJour)
                nomJour = listeJours[dateDD.weekday()]
                labelDate = u"%s %d" % (nomJour, numJour)

                # Création du contenu de chaque case
                if dateDD in self.dictPresences:
                    dictBarres = self.dictPresences[dateDD]
                else:
                    dictBarres = {}
                case = CaseDate(xoffset=0,
                                hauteurCase=10,
                                largeurCase=largeurMois,
                                dateDD=dateDD,
                                labelDate=labelDate,
                                dictBarres=dictBarres)
                dataTableau[numJour][numCol] = case

                # Calcule le nbre d'heures du mois
                if dateDD in self.dictPresences:
                    totalMinutesMois += self.dictPresences[dateDD]["totalJour"]

            # Ecrit le nombre d'heures du mois
            if AFFICHER_HEURES_MOIS == True and totalMinutesMois != 0:
                numJour += 1
                dataTableau[numJour][numCol] = minutesEnHeures(
                    totalMinutesMois)
                styleTableau.append(('FONT', (numCol, numJour),
                                     (numCol, numJour), "Helvetica", 5))
                styleTableau.append(
                    ('ALIGN', (numCol, numJour), (numCol, numJour), "RIGHT"))
                styleTableau.append(
                    ('VALIGN', (numCol, numJour), (numCol, numJour), "TOP"))

            # Définit le style du tableau
            styleTableau.append(('GRID', (numCol, 0), (numCol, nbreJoursMois),
                                 0.25, colors.black))

            numMois += 1

        tableau = Table(dataTableau, largeursColonnes)
        tableau.setStyle(TableStyle(styleTableau))
        story.append(tableau)
        story.append(Spacer(0, 25))

        # Légendes des catégories
        dataTableauLegende = []
        largeursColonnesLegende = []
        styleTableauLegende = []

        # Création des lignes vides du tableau des légendes
        nbreLignesLegendes = 5
        nbreColonnesLegendes = 4
        largeurColonneLegende = 178.75

        for numLigne in range(0, nbreLignesLegendes):
            ligne = []
            for numCol in range(0, nbreColonnesLegendes):
                ligne.append(None)
            dataTableauLegende.append(ligne)

        # Création de la liste des largeurs des colonnes
        for x in range(0, nbreColonnesLegendes):
            largeursColonnesLegende.append(largeurColonneLegende)

        # Remplissage du tableau des légendes
        nbre_legendes = 0
        total_heures = 0
        numLigne = 0
        numCol = 0

        if AFFICHER_VACANCES == True:
            dataTableauLegende[numLigne][numCol] = CaseLegende(
                0, 10, _(u"Vacances"), COULEUR_VACANCES, None)
            numLigne += 1
        if AFFICHER_WE == True:
            dataTableauLegende[numLigne][numCol] = CaseLegende(
                0, 10, _(u"Week-ends"), COULEUR_WE, None)
            numLigne += 1
        if AFFICHER_FERIES == True:
            dataTableauLegende[numLigne][numCol] = CaseLegende(
                0, 10, _(u"Jours fériés"), COULEUR_FERIES, None)
            numLigne += 1

        for IDcategorie, nbreHeures in self.dictTotauxCategories.items():
            if IDcategorie != "totalAnnee":
                nom_categorie, ordre, couleur = DICT_CATEGORIES[IDcategorie]
                legende = CaseLegende(0, 10, nom_categorie, couleur,
                                      nbreHeures)
                dataTableauLegende[numLigne][numCol] = legende
                nbre_legendes += 1
                total_heures += nbreHeures

                numLigne += 1
                if numLigne == nbreLignesLegendes:
                    numLigne = 0
                    numCol += 1

        if nbre_legendes > 1:
            # Ajoute un total d'heures pour l'année
            legende = CaseLegende(0, 10, _(u"Total pour l'année"), None,
                                  total_heures)
            dataTableauLegende[numLigne][numCol] = legende

        styleTableauLegende.append(('FONT', (0, 1), (-1, -1), "Helvetica", 6))
        styleTableauLegende.append(('LEFTPADDING', (0, 0), (-1, -1), 0))
        styleTableauLegende.append(('RIGHTPADDING', (0, 0), (-1, -1), 0))
        styleTableauLegende.append(('TOPPADDING', (0, 0), (-1, -1), 0))
        styleTableauLegende.append(('BOTTOMPADDING', (0, 0), (-1, -1), 0))

        tableauLegende = Table(dataTableauLegende, largeursColonnesLegende)
        tableauLegende.setStyle(TableStyle(styleTableauLegende))
        if AFFICHER_LEGENDE == True:
            story.append(tableauLegende)

        # Enregistrement du PDF
        doc.build(story)
        # Affichage du PDF
        FonctionsPerso.LanceFichierExterne(nomDoc)
コード例 #26
0
    def CreationPDF(self,
                    nomDoc=FonctionsPerso.GenerationNomDoc(
                        "RECU_REGLEMENT", "pdf"),
                    afficherDoc=True):
        dictChampsFusion = {}

        # Récupération des valeurs de base
        dictDonnees = DICT_DONNEES

        # Récupération des infos sur l'organisme
        DB = GestionDB.DB()
        req = """SELECT nom, rue, cp, ville, tel, fax, mail, site, num_agrement, num_siret, code_ape
        FROM organisateur
        WHERE IDorganisateur=1;"""
        DB.ExecuterReq(req)
        listeDonnees = DB.ResultatReq()
        dictOrganisme = {}
        for nom, rue, cp, ville, tel, fax, mail, site, num_agrement, num_siret, code_ape in listeDonnees:
            dictOrganisme["nom"] = nom
            dictOrganisme["rue"] = rue
            dictOrganisme["cp"] = cp
            if ville != None: ville = ville.capitalize()
            dictOrganisme["ville"] = ville
            dictOrganisme["tel"] = tel
            dictOrganisme["fax"] = fax
            dictOrganisme["mail"] = mail
            dictOrganisme["site"] = site
            dictOrganisme["num_agrement"] = num_agrement
            dictOrganisme["num_siret"] = num_siret
            dictOrganisme["code_ape"] = code_ape
        DB.Close()

        date_edition = dictDonnees["date"]
        try:
            date_editionDD = DateEngEnDateDD(DateFrEng(date_edition))
        except:
            date_editionDD = ""

        # Insertion des données de base dans le dictValeurs
        IDfamille = self.IDfamille
        dictValeurs = {
            "IDfamille": self.IDfamille,
            "{IDFAMILLE}": str(self.IDfamille),
            "num_recu": dictDonnees["numero"],
            "{DATE_EDITION}": dictDonnees["date"],
            "{LIEU_EDITION}": dictDonnees["lieu"],
            "{DESTINATAIRE_NOM}": dictDonnees["nom"],
            "{DESTINATAIRE_RUE}": dictDonnees["rue"],
            "{DESTINATAIRE_VILLE}": dictDonnees["ville"],
            "{NUM_RECU}": dictDonnees["numero"],
            "{DATE_EDITION}": date_edition,
            "{DATE_EDITION_LONG}": DateComplete(date_editionDD),
            "{DATE_EDITION_COURT}": date_edition,
            "{ORGANISATEUR_NOM}": dictOrganisme["nom"],
            "{ORGANISATEUR_RUE}": dictOrganisme["rue"],
            "{ORGANISATEUR_CP}": dictOrganisme["cp"],
            "{ORGANISATEUR_VILLE}": dictOrganisme["ville"],
            "{ORGANISATEUR_TEL}": dictOrganisme["tel"],
            "{ORGANISATEUR_FAX}": dictOrganisme["fax"],
            "{ORGANISATEUR_MAIL}": dictOrganisme["mail"],
            "{ORGANISATEUR_SITE}": dictOrganisme["site"],
            "{ORGANISATEUR_AGREMENT}": dictOrganisme["num_agrement"],
            "{ORGANISATEUR_SIRET}": dictOrganisme["num_siret"],
            "{ORGANISATEUR_APE}": dictOrganisme["code_ape"],
        }

        # Récupération des infos de base individus et familles
        self.infosIndividus = UTILS_Infos_individus.Informations()
        dictValeurs.update(
            self.infosIndividus.GetDictValeurs(mode="famille",
                                               ID=IDfamille,
                                               formatChamp=True))

        # Récupération des questionnaires
        Questionnaires = UTILS_Questionnaires.ChampsEtReponses(type="famille")
        for dictReponse in Questionnaires.GetDonnees(IDfamille):
            dictValeurs[dictReponse["champ"]] = dictReponse["reponse"]
            if dictReponse["controle"] == "codebarres":
                dictValeurs["{CODEBARRES_QUESTION_%d}" %
                            dictReponse["IDquestion"]] = dictReponse["reponse"]

        # Récupération du signataire
        infosSignataire = self.ctrl_signataire.GetInfos()
        if infosSignataire == None:
            dlg = wx.MessageDialog(
                self, _(u"Vous n'avez sélectionné aucun signataire !"),
                _(u"Annulation"), wx.OK | wx.ICON_EXCLAMATION)
            dlg.ShowModal()
            dlg.Destroy()
            return False

        nomSignataire = infosSignataire["nom"]
        fonctionSignataire = infosSignataire["fonction"]
        sexeSignataire = infosSignataire["sexe"]
        if sexeSignataire == "H":
            genreSignataire = u""
        else:
            genreSignataire = u"e"

        # Récupération et transformation du texte d'intro
        if self.ctrl_intro.GetValue() == True:
            textIntro = self.ctrl_texte_intro.GetValue()
            textIntro = textIntro.replace("{GENRE}", genreSignataire)
            textIntro = textIntro.replace("{NOM}", nomSignataire)
            textIntro = textIntro.replace("{FONCTION}", fonctionSignataire)
            textIntro = textIntro.replace("{FAMILLE}", dictDonnees["nom"])
            textIntro = textIntro.replace(
                "{MONTANT}",
                u"<b>%.2f %s</b>" % (self.dictReglement["montant"], SYMBOLE))
            dictValeurs["intro"] = textIntro
        else:
            dictValeurs["intro"] = None

        # Envoi des informations sur le règlement
        for key, valeur in self.dictReglement.iteritems():
            dictValeurs[key] = valeur

        dictValeurs["{IDREGLEMENT}"] = str(dictValeurs["IDreglement"])
        dictValeurs["{DATE_REGLEMENT}"] = DateEngFr(
            dictValeurs["dateReglement"])
        dictValeurs["{MODE_REGLEMENT}"] = dictValeurs["nomMode"]
        if dictValeurs["nomEmetteur"] != None:
            dictValeurs["{NOM_EMETTEUR}"] = dictValeurs["nomEmetteur"]
        else:
            dictValeurs["{NOM_EMETTEUR}"] = ""
        dictValeurs["{NUM_PIECE}"] = dictValeurs["numPiece"]
        dictValeurs["{MONTANT_REGLEMENT}"] = u"%.2f %s" % (
            dictValeurs["montant"], SYMBOLE)
        dictValeurs["{NOM_PAYEUR}"] = dictValeurs["nomPayeur"]
        dictValeurs["{NUM_QUITTANCIER}"] = str(dictValeurs["numQuittancier"])
        dictValeurs["{DATE_SAISIE}"] = DateEngFr(dictValeurs["date_saisie"])
        dictValeurs["{OBSERVATIONS}"] = u"%s" % dictValeurs["observations"]

        # Récupération liste des prestations
        if self.ctrl_prestations.GetValue() == True:
            dictValeurs["prestations"] = self.GetPrestations()
        else:
            dictValeurs["prestations"] = []

        # Préparation des données pour une sauvegarde de l'attestation
        self.dictSave = {}
        self.dictSave["numero"] = dictDonnees["numero"]
        self.dictSave["IDfamille"] = self.IDfamille
        self.dictSave["date_edition"] = DateFrEng(dictDonnees["date"])
        self.dictSave["IDutilisateur"] = UTILS_Identification.GetIDutilisateur(
        )
        self.dictSave["IDreglement"] = self.IDreglement

        # Récupération du modèle
        IDmodele = self.ctrl_modele.GetID()
        if IDmodele == None:
            dlg = wx.MessageDialog(
                self,
                _(u"Vous devez obligatoirement sélectionner un modèle !"),
                _(u"Erreur"), wx.OK | wx.ICON_EXCLAMATION)
            dlg.ShowModal()
            dlg.Destroy()
            return

        dictChampsFusion["{DATE_EDITION_RECU}"] = DateFrEng(
            dictDonnees["date"])
        dictChampsFusion["{NUMERO_RECU}"] = dictDonnees["numero"]
        dictChampsFusion["{ID_REGLEMENT}"] = str(dictValeurs["{IDREGLEMENT}"])
        dictChampsFusion["{DATE_REGLEMENT}"] = dictValeurs["{DATE_REGLEMENT}"]
        dictChampsFusion["{MODE_REGLEMENT}"] = dictValeurs["{MODE_REGLEMENT}"]
        dictChampsFusion["{NOM_EMETTEUR}"] = dictValeurs["{NOM_EMETTEUR}"]
        dictChampsFusion["{NUM_PIECE}"] = dictValeurs["{NUM_PIECE}"]
        dictChampsFusion["{MONTANT_REGLEMENT}"] = dictValeurs[
            "{MONTANT_REGLEMENT}"]
        dictChampsFusion["{NOM_PAYEUR}"] = dictValeurs["{NOM_PAYEUR}"]
        dictChampsFusion["{NUM_QUITTANCIER}"] = dictValeurs[
            "{NUM_QUITTANCIER}"]
        dictChampsFusion["{DATE_SAISIE}"] = dictValeurs["{DATE_SAISIE}"]

        # Fabrication du PDF
        from Utils import UTILS_Impression_recu
        UTILS_Impression_recu.Impression(dictValeurs,
                                         IDmodele=IDmodele,
                                         nomDoc=nomDoc,
                                         afficherDoc=afficherDoc)

        return dictChampsFusion
コード例 #27
0
    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"") 
コード例 #28
0
ファイル: DLG_Export_helios.py プロジェクト: neoclust/Noethys
    def OnBoutonApercu(self, event):
        if self.ValidationSaisie() == False:
            return

        typeImpression = self.ctrl_type.GetType()

        # Récupération des paramètres
        tracks = self.ctrl_factures.GetTracksCoches()
        date_emission = self.ctrl_date.GetDate()
        code_col = self.ctrl_code_coll.GetValue()
        code_nat = self.ctrl_code_nat.GetValue()
        code_rec = self.ctrl_code_rec.GetValue()
        exercice = self.ctrl_exercice.GetValue()
        num_role = self.ctrl_num_role.GetValue()

        listeIDfactures = []
        montantTotal = 0.0
        for track in tracks:
            listeIDfactures.append(track.IDfacture)
            montantTotal += -track.solde

        if len(listeIDfactures) == 0: conditionFactures = "()"
        elif len(listeIDfactures) == 1:
            conditionFactures = "(%d)" % listeIDfactures[0]
        else:
            conditionFactures = str(tuple(listeIDfactures))

        DB = GestionDB.DB()
        req = """
        SELECT prestations.IDprestation, prestations.IDfacture, prestations.label, prestations.montant, 
        prestations.IDindividu, individus.nom, individus.prenom,
        prestations.IDactivite, activites.nom
        FROM prestations
        LEFT JOIN individus ON prestations.IDindividu = individus.IDindividu
        LEFT JOIN activites ON activites.IDactivite = prestations.IDactivite
        WHERE prestations.IDfacture IN %s
        GROUP BY prestations.IDprestation
        ORDER BY prestations.date
        ;""" % conditionFactures
        DB.ExecuterReq(req)
        listePrestations = DB.ResultatReq()
        DB.Close()
        dictPrestations = {}
        dictIndividus = {}
        dictActivites = {}
        dictTotaux = {}
        for IDprestation, IDfacture, label, montant, IDindividu, nom, prenom, IDactivite, nomActivite in listePrestations:

            if dictActivites != None and (IDactivite
                                          in dictActivites) == False:
                dictActivites[IDactivite] = nomActivite

            if IDindividu != None and (
                    IDindividu in dictIndividus) == False and prenom != None:
                dictIndividus[IDindividu] = u"%s %s" % (nom, prenom)

            if (IDfacture in dictPrestations) == False:
                dictPrestations[IDfacture] = {}
            if (IDindividu in dictPrestations[IDfacture]) == False:
                dictPrestations[IDfacture][IDindividu] = {}
            if (label in dictPrestations[IDfacture][IDindividu]) == False:
                dictPrestations[IDfacture][IDindividu][label] = {
                    "quantite": 0,
                    "montant": 0.0,
                    "IDactivite": IDactivite
                }

            if (IDactivite in dictTotaux) == False:
                dictTotaux[IDactivite] = {}
            if (label in dictTotaux[IDactivite]) == False:
                dictTotaux[IDactivite][label] = {"quantite": 0, "montant": 0.0}

            dictTotaux[IDactivite][label]["quantite"] += 1
            dictTotaux[IDactivite][label]["montant"] += montant

            dictPrestations[IDfacture][IDindividu][label]["quantite"] += 1
            dictPrestations[IDfacture][IDindividu][label]["montant"] += montant

        # Création du PDF
        from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, PageBreak
        from reportlab.platypus.flowables import ParagraphAndImage, Image
        from reportlab.rl_config import defaultPageSize
        from reportlab.lib.units import inch, cm
        from reportlab.lib.utils import ImageReader
        from reportlab.lib import colors
        from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
        self.hauteur_page = defaultPageSize[1]
        self.largeur_page = defaultPageSize[0]

        # Initialisation du PDF
        PAGE_WIDTH, PAGE_HEIGHT = defaultPageSize
        nomDoc = FonctionsPerso.GenerationNomDoc("ROLMRE", "pdf")
        if sys.platform.startswith("win"): nomDoc = nomDoc.replace("/", "\\")
        doc = SimpleDocTemplate(nomDoc, topMargin=30, bottomMargin=30)
        story = []

        largeurContenu = 520

        # Création du titre du document
        def Header():
            dataTableau = []
            largeursColonnes = ((420, 100))
            dateDuJour = UTILS_Dates.DateEngFr(str(datetime.date.today()))
            dataTableau.append((_(u"Rôle n°%s-%s") % (exercice, num_role),
                                _(u"%s\nEdité le %s") %
                                (UTILS_Organisateur.GetNom(), dateDuJour)))
            style = TableStyle([
                ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                ('VALIGN', (0, 0), (-1, -1), 'TOP'),
                ('ALIGN', (0, 0), (0, 0), 'LEFT'),
                ('FONT', (0, 0), (0, 0), "Helvetica-Bold", 16),
                ('ALIGN', (1, 0), (1, 0), 'RIGHT'),
                ('FONT', (1, 0), (1, 0), "Helvetica", 6),
            ])
            tableau = Table(dataTableau, largeursColonnes)
            tableau.setStyle(style)
            story.append(tableau)
            story.append(Spacer(0, 20))

        # Insère un header
        Header()

        couleurFond1 = (0.8, 0.8, 1)  # Vert -> (0.5, 1, 0.2)
        couleurFond2 = (0.9, 0.9, 1)  # Vert -> (0.5, 1, 0.2)
        styleLabel = ParagraphStyle(name="label",
                                    fontName="Helvetica",
                                    alignment=1,
                                    fontSize=5,
                                    spaceAfter=0,
                                    leading=8,
                                    spaceBefore=0)
        styleTexte = ParagraphStyle(name="label",
                                    fontName="Helvetica",
                                    alignment=0,
                                    fontSize=7,
                                    spaceAfter=0,
                                    leading=8,
                                    spaceBefore=0)
        styleTexte2 = ParagraphStyle(name="label",
                                     fontName="Helvetica",
                                     alignment=1,
                                     fontSize=7,
                                     spaceAfter=0,
                                     leading=8,
                                     spaceBefore=0)
        styleMontant = ParagraphStyle(name="label",
                                      fontName="Helvetica",
                                      alignment=2,
                                      fontSize=7,
                                      spaceAfter=0,
                                      leading=8,
                                      spaceBefore=0)

        # Intro
        story.append(
            Paragraph(
                _(u"Date d'émission : %s | Code Collectivité : %s | Code Nature : %s | Code Recette : %s"
                  ) % (UTILS_Dates.DateDDEnFr(date_emission), code_col,
                       code_nat, code_rec), styleTexte))
        story.append(Spacer(0, 20))

        # Factures
        if typeImpression in ("detail", "simple"):

            for track in tracks:

                # Numéro de facture
                dataTableau = []
                largeursColonnes = [100, 100, largeurContenu - 100 - 100]
                dataTableau.append((
                    _(u"Facture n°%s") % track.numero,
                    u"%.2f %s" % (-track.solde, SYMBOLE),
                    _(u"Edité le %s | Echéance le %s | Période du %s au %s")
                    % (UTILS_Dates.DateDDEnFr(track.date_edition),
                       UTILS_Dates.DateDDEnFr(track.date_echeance),
                       UTILS_Dates.DateDDEnFr(track.date_debut),
                       UTILS_Dates.DateDDEnFr(track.date_fin)),
                ))
                tableau = Table(dataTableau, largeursColonnes)
                listeStyles = [
                    ('FONT', (0, 0), (1, -1), "Helvetica-Bold", 7),
                    ('FONT', (2, -1), (2, -1), "Helvetica", 6),
                    ('BACKGROUND', (0, 0), (-1, -1), couleurFond1),
                    ('ALIGN', (2, -1), (2, -1), 'RIGHT'),
                    ('BOX', (0, 0), (-1, -1), 0.25, colors.black),
                ]
                tableau.setStyle(TableStyle(listeStyles))
                story.append(tableau)

                # Famille
                if track.prelevement == True:
                    textePrelevement = _(
                        u"N° Compte : %s | Etab : %s | Guichet : %s | Clé : %s | Titulaire : %s"
                    ) % (track.prelevement_numero, track.prelevement_etab,
                         track.prelevement_guichet, track.prelevement_cle,
                         track.prelevement_payeur)
                else:
                    textePrelevement = u""

                if track.adresse_famille["rue"] != None:
                    rue = track.adresse_famille["rue"]
                else:
                    rue = u""
                if track.adresse_famille["cp"] != None:
                    cp = track.adresse_famille["cp"]
                else:
                    cp = u""
                if track.adresse_famille["ville"] != None:
                    ville = track.adresse_famille["ville"]
                else:
                    ville = u""

                dataTableau = [
                    (Paragraph(_(u"Famille"),
                               styleLabel), Paragraph(_(u"Adresse"),
                                                      styleLabel),
                     Paragraph(_(u"Prélèvement bancaire"), styleLabel)),
                ]
                largeursColonnes = [180, 140, largeurContenu - 320]
                dataTableau.append((
                    Paragraph(track.nomsTitulaires, styleTexte),
                    (Paragraph(rue, styleTexte),
                     Paragraph(u"%s %s" % (cp, ville), styleTexte)),
                    Paragraph(textePrelevement, styleTexte),
                ))
                tableau = Table(dataTableau, largeursColonnes)
                listeStyles = [
                    ('TOPPADDING', (0, 0), (-1, 0), 0),
                    ('BOTTOMPADDING', (0, 0), (-1, 0), -1),
                    ('FONT', (0, -1), (-1, -1), "Helvetica", 7),
                    ('GRID', (0, 0), (-1, 0), 0.25, colors.black),
                    ('BOX', (0, 1), (-1, 1), 0.25, colors.black),
                    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                    ('BACKGROUND', (0, 0), (-1, 0), couleurFond2),
                ]
                tableau.setStyle(TableStyle(listeStyles))
                story.append(tableau)

                # Détail des prestations
                if typeImpression == "detail" and track.IDfacture in dictPrestations:

                    dataTableau = [
                        (Paragraph(_(u"Individu"), styleLabel),
                         Paragraph(_(u"Activité"), styleLabel),
                         Paragraph(_(u"Prestation"), styleLabel),
                         Paragraph(_(u"Quantité"), styleLabel),
                         Paragraph(_(u"Montant total"), styleLabel)),
                    ]
                    largeursColonnes = [130, 120, 185, 35, 50]

                    for IDindividu, dictLabels in dictPrestations[
                            track.IDfacture].items():

                        if IDindividu in dictIndividus:
                            labelIndividu = dictIndividus[IDindividu]
                        else:
                            labelIndividu = u""

                        listeActivites = []
                        listeLabels = []
                        listeQuantites = []
                        listeMontants = []
                        for labelPrestation, dictTemp in dictLabels.items():

                            if dictTemp["IDactivite"] != None and dictTemp[
                                    "IDactivite"] in dictActivites:
                                labelActivite = dictActivites[
                                    dictTemp["IDactivite"]]
                            else:
                                labelActivite = u""

                            listeActivites.append(
                                Paragraph(labelActivite[:35], styleTexte2))
                            listeLabels.append(
                                Paragraph(labelPrestation[:40], styleTexte2))
                            listeQuantites.append(
                                Paragraph(str(dictTemp["quantite"]),
                                          styleTexte2))
                            listeMontants.append(
                                Paragraph(
                                    u"%.2f %s" %
                                    (dictTemp["montant"], SYMBOLE),
                                    styleMontant))

                        dataTableau.append((
                            Paragraph(labelIndividu, styleTexte2),
                            listeActivites,
                            listeLabels,
                            listeQuantites,
                            listeMontants,
                        ))

                    tableau = Table(dataTableau, largeursColonnes)
                    listeStyles = [
                        ('TOPPADDING', (0, 0), (-1, 0), 0),
                        ('BOTTOMPADDING', (0, 0), (-1, 0), -1),
                        ('FONT', (0, -1), (-1, -1), "Helvetica", 7),
                        ('GRID', (0, 0), (-1, -1), 0.25, colors.black),
                        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                        ('BACKGROUND', (0, 0), (-1, 0), couleurFond2),
                    ]
                    tableau.setStyle(TableStyle(listeStyles))
                    story.append(tableau)

                story.append(Spacer(0, 10))

        # Totaux
        dictTotaux[IDactivite][label]["montant"]

        dataTableau = [
            (_(u"Totaux par activités et prestations"), "", "", ""),
            (Paragraph(_(u"Activités"),
                       styleLabel), Paragraph(_(u"Prestations"), styleLabel),
             Paragraph(_(u"Quantité"),
                       styleLabel), Paragraph(_(u"Montant"), styleLabel)),
        ]
        largeursColonnes = [200, 240, 30, 50]

        for IDactivite, dictLabels in dictTotaux.items():

            if IDactivite == None:
                nomActivite = _(u"Prestations diverses")
            else:
                nomActivite = dictActivites[IDactivite]

            listeLabels = []
            listeQuantites = []
            listeMontants = []
            quantiteActivite = 0
            totalActivite = 0.0
            for label, dictTemp in dictLabels.items():
                listeLabels.append(Paragraph(label, styleTexte2))
                listeQuantites.append(
                    Paragraph(str(dictTemp["quantite"]), styleTexte2))
                listeMontants.append(
                    Paragraph(u"%.2f %s" % (dictTemp["montant"], SYMBOLE),
                              styleMontant))
                quantiteActivite += dictTemp["quantite"]
                totalActivite += dictTemp["montant"]

            listeLabels.append(
                Paragraph(_(u"<b><i>Total de l'activité</i></b>"),
                          styleTexte2))
            listeQuantites.append(
                Paragraph("<b><i>%d</i></b>" % quantiteActivite, styleTexte2))
            listeMontants.append(
                Paragraph(u"<b><i>%.2f %s</i></b>" % (totalActivite, SYMBOLE),
                          styleMontant))

            dataTableau.append((
                Paragraph(nomActivite, styleTexte2),
                listeLabels,
                listeQuantites,
                listeMontants,
            ))

        tableau = Table(dataTableau, largeursColonnes)
        listeStyles = [
            ('TOPPADDING', (0, 1), (-1, 1), 0),
            ('BOTTOMPADDING', (0, 1), (-1, 1), -1),
            ('FONT', (1, -1), (-1, -1), "Helvetica", 7),
            ('FONT', (0, 0), (0, 0), "Helvetica-Bold", 7),
            ('BOX', (0, 0), (-1, 0), 0.25, colors.black),
            ('GRID', (0, 1), (-1, -1), 0.25, colors.black),
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('BACKGROUND', (0, 0), (-1, 0), couleurFond1),
            ('BACKGROUND', (0, 1), (-1, 1), couleurFond2),
        ]
        tableau.setStyle(TableStyle(listeStyles))
        story.append(tableau)

        story.append(Spacer(0, 10))

        story.append(
            Paragraph(
                _(u"%d factures | Montant total : %.2f %s") %
                (len(tracks), montantTotal, SYMBOLE), styleTexte))

        # Enregistrement et ouverture du PDF
        try:
            doc.build(story)
        except Exception as 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 False

        FonctionsPerso.LanceFichierExterne(nomDoc)
コード例 #29
0
    def Imprimer(self, event=None):
        listeDates = self.dictImpression["dates"]
        if len(listeDates) > 26 :
            dlg = wx.MessageDialog(self, _(u"Désolé mais vous ne pouvez pas imprimer plus de 26 jours sur une feuille !"), _(u"Information"), wx.OK | wx.ICON_EXCLAMATION)
            dlg.ShowModal()
            dlg.Destroy()
            return False
        
        # Création du PDF
        from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, PageBreak
        from reportlab.platypus.flowables import ParagraphAndImage, Image
        from reportlab.rl_config import defaultPageSize
        from reportlab.lib.units import inch, cm
        from reportlab.lib.utils import ImageReader
        from reportlab.lib import colors
        from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
        self.hauteur_page = defaultPageSize[1]
        self.largeur_page = defaultPageSize[0]
        
        # Recherche le format de la page à appliquer
        largeurPremiereColonne = 140
        largeurColonnesDates = 24
        largeurMax = largeurPremiereColonne + (largeurColonnesDates*len(listeDates))
        
        if largeurMax <= 520 :
            # Format Portrait
            largeurPage, hauteurPage = defaultPageSize
            largeurContenu = 520
        else :
            # Format Paysage
            hauteurPage, largeurPage = defaultPageSize
            largeurContenu = 770

        # Initialisation du PDF
        nomDoc = FonctionsPerso.GenerationNomDoc("LISTE_TRANSPORTS", "pdf")
        if sys.platform.startswith("win") : nomDoc = nomDoc.replace("/", "\\")
        doc = SimpleDocTemplate(nomDoc, pagesize=(largeurPage, hauteurPage), topMargin=30, bottomMargin=30)
        story = []
        
        # Création du titre du document
        def Header():
            dataTableau = []
            largeursColonnes = ( (largeurContenu-100, 100) )
            dateDuJour = DateEngFr(str(datetime.date.today()))
            dataTableau.append( (_(u"Liste des transports"), _(u"%s\nEdité le %s") % (UTILS_Organisateur.GetNom(), dateDuJour)) )
            style = TableStyle([
                    ('BOX', (0,0), (-1,-1), 0.25, colors.black), 
                    ('VALIGN', (0,0), (-1,-1), 'TOP'), 
                    ('ALIGN', (0,0), (0,0), 'LEFT'), 
                    ('FONT',(0,0),(0,0), "Helvetica-Bold", 16), 
                    ('ALIGN', (1,0), (1,0), 'RIGHT'), 
                    ('FONT',(1,0),(1,0), "Helvetica", 6), 
                    ])
            tableau = Table(dataTableau, largeursColonnes)
            tableau.setStyle(style)
            story.append(tableau)
            story.append(Spacer(0,20))       
        
        # Insère un header
        Header() 
        
        # Contenu
        for dictCategorie in self.dictImpression["donnees"] :
            label = dictCategorie["texte"]
            img = dictCategorie["img"]
            elements = dictCategorie["elements"]
            
            dataTableau = []
            largeursColonnes = [largeurPremiereColonne,]
            
            # Création de la ligne de date
            paraStyle = ParagraphStyle(name="categorie",
                      fontName="Helvetica-Bold",
                      fontSize=9,
                      leading=8,
                      spaceAfter=2,)

            ligne = [ParagraphAndImage(Paragraph(label, paraStyle), Image(Chemins.GetStaticPath("Images/32x32/%s.png" % img), width=8, height=8), xpad=1, ypad=0, side="left"),]
            for date in listeDates :
                ligne.append(u"%02d/%02d\n%04d" % (date.day, date.month, date.year))
                largeursColonnes.append(largeurColonnesDates)
            dataTableau.append(ligne)
        
            # Création des lignes
            listeExtraStyles = []
            index = 1
            for element in elements :
                
                # Décoration de la ligne
                if element["type"] in ("lieux", "lignes", "localisations") :
                    listeExtraStyles.append(('BACKGROUND', (0, index), (-1, index), (0.8, 0.8, 1) ))

                if element["type"] == "arrets" :
                    listeExtraStyles.append(('BACKGROUND', (0, index), (-1, index), (0.9, 0.9, 1) ))

                if element["type"] == "heures" :
                    listeExtraStyles.append(('FONT',(0, index), (0, index), "Helvetica-Bold", 6),)
                    listeExtraStyles.append(('FONT',(1, index), (-1, index), "Helvetica", 5),)
                    listeExtraStyles.append(('TEXTCOLOR',(1, index), (-1, index), (0.6, 0.6, 0.6)),)

                if element["type"] == "individus" :
                    listeExtraStyles.append(('ALIGN', (0, index), (0, index), 'RIGHT'))
                    listeExtraStyles.append(('GRID', (1, index), (-1, index), 0.25, colors.black))
                    listeExtraStyles.append(('FONT',(1, index), (-1, index), "Helvetica", 6),)

                # Ajout d'une marge
                label = element["texte"]
                if "marge" in element :
                    label = u"%s%s" % ((element["marge"]-1) * "      ", label)
                ligne = [label,]
                
                # Ajout des colonnes
                for indexColonne in range(1, len(largeursColonnes)) :
                    label = u""
                    if "colonnes" in element:
                        if indexColonne in element["colonnes"] :
                            label = element["colonnes"][indexColonne]
                    ligne.append(label)
                
                dataTableau.append(ligne)
                index += 1
        
            # Style du tableau
            listeStyles = [
                    ('VALIGN', (0, 0), (-1,-1), 'MIDDLE'), 
                    ('ALIGN', (1, 0), (-1, -1), 'CENTRE'),
                    ('FONT',(0, 0), (-1,-1), "Helvetica", 7), 
                    ('FONT',(0, 0), (0, 0), "Helvetica-Bold", 8),
                    ('BOX', (0, 1), (-1, -1), 0.25, colors.black), 
                    ('GRID', (1, 0), (-1, 0), 0.25, colors.black), 
                    ]
            
            for extraStyle in listeExtraStyles :
                listeStyles.append(extraStyle)
                
            # Création du tableau
            tableau = Table(dataTableau, largeursColonnes)
            tableau.setStyle(TableStyle(listeStyles))
            story.append(tableau)
            story.append(Spacer(0, 15))
        
##        # TOTAUX
##        dataTableau = []
##        largeursColonnes = [220, 220, 40, 40]
##
##        for ligne in self.listeImpression["totaux"] :
##            dataTableau.append(ligne) 
##
##        couleurFond = (0.8, 0.8, 0.8)
##        listeStyles = [
##                ('VALIGN', (0,0), (-1,-1), 'MIDDLE'), # Centre verticalement toutes les cases
##                ('FONT',(0,0),(-1,-1), "Helvetica", 7), # Donne la police de caract. + taille de police 
##                ('BOX', (0, 1), (-1,-1), 0.25, colors.black), # Crée la bordure noire pour tout le tableau
##                ('ALIGN', (2, 0), (-1, -1), 'CENTRE'), # Ligne de labels colonne alignée au centre
##                ('BOX', (0, 0), (-1,0), 0.25, colors.black), # Crée la bordure noire du nom de famille
##                ('FONT',(0,0),(0,0), "Helvetica-Bold", 8), # Donne la police de caract. + taille de police du titre de groupe
##                ('BACKGROUND', (0,0), (-1,0), couleurFond), # Donne la couleur de fond du titre de groupe
##                ('TOPPADDING',(0,0),(-1,-1), 1), 
##                ('BOTTOMPADDING',(0,0),(-1,-1), 1), 
##                ]
##            
##        # Création du tableau
##        tableau = Table(dataTableau, largeursColonnes)
##        tableau.setStyle(TableStyle(listeStyles))
##        story.append(tableau)

        # Enregistrement du PDF
        doc.build(story)
        
        # Affichage du PDF
        FonctionsPerso.LanceFichierExterne(nomDoc)
コード例 #30
0
    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