def __init__(self,
                 dictValeurs={},
                 dictOptions={},
                 IDmodele=None,
                 ouverture=True,
                 nomFichier=None):
        """ Impression """
        global DICT_VALEURS, DICT_OPTIONS
        DICT_VALEURS = dictValeurs
        DICT_OPTIONS = dictOptions

        # Initialisation du document
        if nomFichier == None:
            nomDoc = FonctionsPerso.GenerationNomDoc("LOCATIONS", "pdf")
        else:
            nomDoc = nomFichier
        doc = BaseDocTemplate(nomDoc, pagesize=TAILLE_PAGE, showBoundary=False)

        # Mémorise le ID du modèle
        modeleDoc = DLG_Noedoc.ModeleDoc(IDmodele=IDmodele)
        doc.modeleDoc = modeleDoc

        # Importe le template de la première page
        doc.addPageTemplates(MyPageTemplate(pageSize=TAILLE_PAGE, doc=doc))

        story = []
        styleSheet = getSampleStyleSheet()
        h3 = styleSheet['Heading3']
        styleTexte = styleSheet['BodyText']
        styleTexte.fontName = "Helvetica"
        styleTexte.fontSize = 9
        styleTexte.borderPadding = 9
        styleTexte.leading = 12

        # ----------- Insertion du contenu des frames --------------
        listeLabels = []
        for IDlocation, dictValeur in dictValeurs.iteritems():
            listeLabels.append((dictValeur["{FAMILLE_NOM}"], IDlocation))
        listeLabels.sort()

        for labelDoc, IDlocation in listeLabels:
            dictValeur = dictValeurs[IDlocation]
            if dictValeur["select"] == True:

                story.append(DocAssign("IDlocation", IDlocation))
                nomSansCivilite = dictValeur["{FAMILLE_NOM}"]
                story.append(Bookmark(nomSansCivilite, str(IDlocation)))

                # Saut de page
                story.append(PageBreak())

        # Finalisation du PDF
        doc.build(story)

        # Ouverture du PDF
        if ouverture == True:
            FonctionsPerso.LanceFichierExterne(nomDoc)
    def __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)
示例#3
0
def renderElements(elements, filesuffix=None, tmpdir=None):
    """ takes a list of reportlab flowables and renders them to a test.pdf file"""
    margin = 2 * cm
    if filesuffix:
        fn = 'test_' + filesuffix + '.pdf'
    else:
        fn = 'test.pdf'
    fn = os.path.join(tmpdir, fn)
    doc = BaseDocTemplate(fn, topMargin=margin, leftMargin=margin, rightMargin=margin, bottomMargin=margin)
    pt = WikiPage("Title")
    doc.addPageTemplates(pt)
    elements.insert(0, NextPageTemplate('Title'))   
    doc.build(elements)
示例#4
0
def pdf_basic_page( objects, title='', preferences=None ): # used by gen_table.make_page()
    """Simple convenience fonction: build a page from a list of platypus objects,
    adding a title if specified.
    """
    StyleSheet = styles.getSampleStyleSheet()
    report = cStringIO.StringIO() # in-memory document, no disk file
    document = BaseDocTemplate(report)
    document.addPageTemplates(
        ScolarsPageTemplate(document,
                            title=title,
                            author='%s %s (E. Viennet)' % (SCONAME, SCOVERSION),
                            footer_template="Edité par %(scodoc_name)s le %(day)s/%(month)s/%(year)s à %(hour)sh%(minute)s",
                            preferences=preferences
                            ))
    if title:
        head = Paragraph(SU(title), StyleSheet["Heading3"])
        objects = [ head ] + objects
    document.build(objects)
    data = report.getvalue()
    return data
示例#5
0
def pagecat2(request):
    doc = BaseDocTemplate('test.pdf')
    frame_title = Frame(doc.leftMargin, doc.bottomMargin, doc.width/2-6, doc.height, id='title')
    frame_back = Frame(doc.leftMargin, doc.bottomMargin, doc.width/2-6, doc.height, id='back')
    frame_1col = Frame(doc.leftMargin, doc.bottomMargin, doc.width/2-6, doc.height, id='col12')
    frame1_2col = Frame(doc.leftMargin, doc.bottomMargin, doc.width/2-6, doc.height, id='col1')
    frame2_2col = Frame(doc.leftMargin+doc.width/2+6, doc.bottomMargin, doc.width/2-6, doc.height, id='col2')

    doc.addPageTemplates([
        PageTemplate(id='Title', frames=frame_title, onPage=static_title),
        PageTemplate(id='Back', frames=frame_back, onPage=static_back),
        PageTemplate(id='OneCol', frames=frame_1col, onPage=static_1col),
        PageTemplate(id='TwoCol', frames=[frame1_2col, frame2_2col], onPage=static_2col),
    ])
    story = [Paragraph('<b>Table of contents</b>', ParagraphStyle('normal')),
             NextPageTemplate('TwoCol'),
             PageBreak(),
             '<includePdfPages filename="pdf1.pdf" pages="1,2,3"/>',
             NextPageTemplate('TwoCol')]

    doc.build(story)
    return render(request, "test.html")
示例#6
0
文件: pdf.py 项目: firesalp/aemanager
class ProposalTemplate(object):

    styleH = ParagraphStyle({})
    styleH.fontSize = 14
    styleH.leading = 16
    styleH.borderPadding = (5,) * 4

    styleH2 = ParagraphStyle({})
    styleH2.fontSize = 14
    styleH2.leading = 16

    styleCustomer = ParagraphStyle({})
    styleCustomer.fontSize = 12
    styleCustomer.leading = 14
    styleCustomer.borderPadding = (5,) * 4

    styleN = ParagraphStyle({})
    styleN.fontSize = 12
    styleN.leading = 14

    styleTotal = ParagraphStyle({})
    styleTotal.fontSize = 14
    styleTotal.leading = 16
    styleTotal.borderColor = colors.black
    styleTotal.borderWidth = 0.5
    styleTotal.borderPadding = (5,) * 4

    styleTitle = ParagraphStyle({})
    styleTitle.fontSize = 14
    styleTitle.fontName = "Helvetica-Bold"

    styleF = ParagraphStyle({})
    styleF.fontSize = 10
    styleF.alignment = TA_CENTER

    styleLabel = ParagraphStyle({})

    styleDetail = ParagraphStyle({})
    styleDetail.fontName = 'Helvetica-Oblique'
    styleDetail.textColor = colors.gray

    styleNSmall = ParagraphStyle({})
    styleNSmall.fontSize = 8
    styleNSmall.leading = 14

    def __init__(self, response, user):
        self.response = response
        self.user = user
        self.doc = None
        self.story = []
        self.space_before_footer = 0.55 * inch

    def append_to_story(self, data):
        self.story.append(data)

    def build(self):
        self.doc.build(self.story, canvasmaker=NumberedCanvas)

    def init_doc(self, title):

        def proposal_footer(canvas, doc):
            canvas.saveState()
            canvas.setFont('Helvetica', 10)
            PAGE_WIDTH = defaultPageSize[0]
            footer_text = "%s %s - %s, %s %s" % (self.user.first_name,
                                                 self.user.last_name,
                                                 self.user.get_profile().address.street.replace("\n", ", ").replace("\r", ""),
                                                 self.user.get_profile().address.zipcode,
                                                 self.user.get_profile().address.city)
            if self.user.get_profile().address.country:
                footer_text = footer_text + u", %s" % (self.user.get_profile().address.country)

            canvas.drawCentredString(PAGE_WIDTH / 2.0, 0.5 * inch, footer_text)
            extra_info = u"SIRET : %s" % (self.user.get_profile().company_id)
            if self.user.get_profile().vat_number:
                extra_info = u"%s - N° TVA : %s" % (extra_info, self.user.get_profile().vat_number)
            canvas.drawCentredString(PAGE_WIDTH / 2.0, 0.35 * inch, extra_info)
            canvas.restoreState()

        self.doc = BaseDocTemplate(self.response, title=title, leftMargin=0.5 * inch, rightMargin=0.5 * inch)
        frameT = Frame(self.doc.leftMargin, self.doc.bottomMargin, self.doc.width, self.doc.height + 0.5 * inch, id='normal')
        self.doc.addPageTemplates([PageTemplate(id='all', frames=frameT, onPage=proposal_footer), ])

    def add_headers(self, proposal, customer, document_date):

        data = []
        user_header_content = u"""
        %s %s<br/>
        %s<br/>
        %s %s<br/>
        %s<br/>
        SIRET : %s<br/>
        """
        user_header_content = user_header_content % (self.user.first_name,
                                                     self.user.last_name,
                                                     self.user.get_profile().address.street.replace("\n", "<br/>"),
                                                     self.user.get_profile().address.zipcode,
                                                     self.user.get_profile().address.city,
                                                     self.user.get_profile().address.country or '',
                                                     self.user.get_profile().company_id)

        if self.user.get_profile().phonenumber:
            user_header_content = "%s%s<br/>" % (user_header_content, self.user.get_profile().phonenumber)
        if self.user.get_profile().professional_email:
            user_header_content = "%s%s<br/>" % (user_header_content, self.user.get_profile().professional_email)

        customer_header_content = u"""
        <br/><br/><br/><br/>
        %s<br/>
        %s<br/>
        %s %s<br/>
        %s<br/>
        """

        if self.user.get_profile().logo_file:
            user_header = Image("%s%s" % (settings.FILE_UPLOAD_DIR, self.user.get_profile().logo_file))
        else:
            user_header = Paragraph(user_header_content, self.styleH)

        data.append([user_header,
                    '',
                    Paragraph(customer_header_content % (customer,
                                                         customer.address.street.replace("\n", "<br/>"),
                                                         customer.address.zipcode,
                                                         customer.address.city,
                                                         customer.address.country or ''), self.styleCustomer)])

        t1 = Table(data, [3.5 * inch, 0.7 * inch, 3.1 * inch], [1.9 * inch])

        table_style = [('VALIGN', (0, 0), (-1, -1), 'TOP'), ]

        if self.user.get_profile().logo_file:
            table_style.append(('TOPPADDING', (0, 0), (0, 0), 0))
            table_style.append(('LEFTPADDING', (0, 0), (0, 0), 0))

        t1.setStyle(TableStyle(table_style))

        self.story.append(t1)

        self.story.append(Spacer(self.doc.width, 0.25 * inch))

        data = []
        if self.user.get_profile().register:
            msg = u'%s %s %s' % (self.user.get_profile().get_register_display(),
                                 self.user.get_profile().registration_city,
                                 self.user.get_profile().company_id[:9])
        else:
            msg = u"Dispensé d'immatriculation au registre du commerce et des sociétés (RCS) et au répertoire des métiers (RM)"
        data.append([Paragraph(msg, self.styleN),
                    '',
                    Paragraph("<br/>" + _("Date : %s") % (localize(document_date)), self.styleH2)])

        t2 = Table(data, [3.5 * inch, 0.3 * inch, 3.5 * inch], [0.7 * inch])
        t2.setStyle(TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP'), ]))

        self.story.append(t2)

        self.story.append(Spacer(self.doc.width, 0.25 * inch))

    def add_title(self, title):
        self.story.append(Paragraph(title, self.styleTitle))

        spacer = Spacer(self.doc.width, 0.1 * inch)
        self.story.append(spacer)

    def add_row_detail(self, data, row, label_width):
        extra_rows = 0
        if row.detail:
            for line in row.detail.split("\n"):
                para = Paragraph(force_escape(line), self.styleDetail)
                para.width = label_width
                splitted_para = para.breakLines(label_width)
                for detail_row in splitted_para.lines:
                    detail = self.get_splitted_content(detail_row)
                    data.append((detail,))
                    extra_rows += 1
        return extra_rows

    def add_row_table(self, data, row_count, extra_style=[]):
        if row_count <= 16:
            max_row_count = 16
        else:
            first_page_count = 21
            normal_page_count = 33
            last_page_count = 27
            max_row_count = first_page_count + ((row_count - first_page_count) // normal_page_count * normal_page_count) + last_page_count
            if row_count - first_page_count - ((row_count - first_page_count) // normal_page_count * normal_page_count) > last_page_count:
                max_row_count = max_row_count + normal_page_count

        for i in range(max_row_count - row_count):
            if self.user.get_profile().vat_number:
                data.append(['', '', '', '', ''])
            else:
                data.append(['', '', '', ''])

        if self.user.get_profile().vat_number:
            row_table = Table(data, [4.2 * inch, 0.8 * inch, 0.9 * inch, 0.8 * inch, 0.5 * inch], (max_row_count + 1) * [0.3 * inch])
        else:
            row_table = Table(data, [4.7 * inch, 0.8 * inch, 0.9 * inch, 0.8 * inch], (max_row_count + 1) * [0.3 * inch])
        row_style = [('ALIGN', (0, 0), (-1, 0), 'CENTER'),
                     ('ALIGN', (1, 0), (-1, -1), 'CENTER'),
                     ('FONT', (0, 0), (-1, 0), 'Helvetica-Bold'),
                     ('BOX', (0, 0), (-1, 0), 0.25, colors.black),
                     ('INNERGRID', (0, 0), (-1, 0), 0.25, colors.black),
                     ('BOX', (0, 1), (0, -1), 0.25, colors.black),
                     ('BOX', (1, 1), (1, -1), 0.25, colors.black),
                     ('BOX', (2, 1), (2, -1), 0.25, colors.black),
                     ('BOX', (3, 1), (3, -1), 0.25, colors.black)]

        row_style += extra_style

        if self.user.get_profile().vat_number:
            row_style.append(('BOX', (4, 1), (4, -1), 0.25, colors.black))

        row_table.setStyle(TableStyle(row_style))

        self.story.append(row_table)

    def get_label(self, row):
        return row.label

    def get_splitted_content(self, splitted):
        if isinstance(splitted, ParaLines)\
           or isinstance(splitted, FragLine):
            label = " ".join(["%s" % (frag.text) for frag in splitted.words])
        else:
            label = " ".join(splitted[1])
        return label

    def add_rows(self, rows):
        row_count = 0
        extra_rows = 0
        extra_style = []
        data = []
        data.append([ugettext('Label'), ugettext('Quantity'), ugettext('Unit price'), ugettext('Total excl tax')])
        if self.user.get_profile().vat_number:
            data[0].append(ugettext('VAT'))
            label_width = 4.0 * inch
        else:
            label_width = 4.5 * inch
        for row in rows:
            row_count += 1
            label = self.get_label(row)
            #label = label.replace('&', '[et]')
            para = Paragraph(force_escape(label), ProposalTemplate.styleLabel)
            para.width = label_width
            splitted_para = para.breakLines(label_width)
            label = self.get_splitted_content(splitted_para.lines[0])
            quantity = row.quantity
            quantity = quantity.quantize(Decimal(1)) if quantity == quantity.to_integral() else quantity.normalize()
            unit_price = row.unit_price
            unit_price = unit_price.quantize(Decimal(1)) if unit_price == unit_price.to_integral() else unit_price.normalize()
            total = row.quantity * row.unit_price
            total = total.quantize(Decimal(1)) if total == total.to_integral() else total.normalize()
            data_row = [label, localize(quantity), "%s %s" % (localize(unit_price), "€".decode('utf-8')), "%s %s" % (localize(total), "€".decode('utf-8'))]
            if self.user.get_profile().vat_number:
                if row.vat_rate:
                    data_row.append("%s%%" % (localize(row.vat_rate)))
                else:
                    data_row.append('-')
            data.append(data_row)

            for extra_row in splitted_para.lines[1:]:
                label = self.get_splitted_content(extra_row)
                if self.user.get_profile().vat_number:
                    data.append([label, '', '', '', ''])
                else:
                    data.append([label, '', '', ''])
                extra_rows += 1

            extra_detail_rows = self.add_row_detail(data, row, label_width)
            if extra_detail_rows:
                extra_style.append(('FONT',
                                    (0, row_count + extra_rows + 1),
                                    (0, row_count + extra_rows + extra_detail_rows),
                                     self.styleDetail.fontName))
                extra_style.append(('TEXTCOLOR',
                                    (0, row_count + extra_rows + 1),
                                    (0, row_count + extra_rows + extra_detail_rows),
                                     self.styleDetail.textColor))
            extra_rows += extra_detail_rows

        self.add_row_table(data, row_count + extra_rows, extra_style)
        self.story.append(Spacer(self.doc.width, self.space_before_footer))

    def get_total_amount(self, amount, rows):
        amount = amount.quantize(Decimal(1)) if amount == amount.to_integral() else amount.normalize()

        if self.user.get_profile().vat_number:
            total_amount = [Paragraph(_("Total excl tax : %(amount)s %(currency)s") % {'amount': localize(amount), 'currency' : "€".decode('utf-8')}, ProposalTemplate.styleN)]
            vat_amounts = {}
            for row in rows:
                vat_rate = row.vat_rate or 0
                vat_amount = row.amount * vat_rate / 100
                if vat_rate:
                    if vat_rate in vat_amounts:
                        vat_amounts[vat_rate] = vat_amounts[vat_rate] + vat_amount
                    else:
                        vat_amounts[vat_rate] = vat_amount
            for vat_rate, vat_amount in vat_amounts.items():
                vat_amount = round(vat_amount, 2)
                #vat_amount = vat_amount.quantize(Decimal(1)) if vat_amount == vat_amount.to_integral() else vat_amount.normalize()
                total_amount.append(Paragraph(_("VAT %(vat_rate)s%% : %(vat_amount)s %(currency)s") % {'vat_rate': localize(vat_rate),
                                                                                                       'vat_amount': localize(vat_amount),
                                                                                                       'currency' : "€".decode('utf-8')},
                                              ProposalTemplate.styleN))

            incl_tax_amount = amount + sum(vat_amounts.values())
            #incl_tax_amount = incl_tax_amount.quantize(Decimal(1)) if incl_tax_amount == incl_tax_amount.to_integral() else incl_tax_amount.normalize()
            incl_tax_amount = round(incl_tax_amount, 2)
            total_amount.append(Spacer(1, 0.25 * inch))
            total_amount.append(Paragraph(_("TOTAL incl tax : %(amount)s %(currency)s") % {'amount': localize(incl_tax_amount), 'currency' : "€".decode('utf-8')}, ProposalTemplate.styleTotal))
        else:
            total_amount = [Paragraph(_("TOTAL excl tax : %(amount)s %(currency)s") % {'amount': localize(amount), 'currency' : "€".decode('utf-8')}, ProposalTemplate.styleTotal),
                            Spacer(1, 0.25 * inch),
                            Paragraph(u"TVA non applicable, art. 293 B du CGI", ProposalTemplate.styleN)]

        return total_amount
    def __init__(self, dictValeurs={}, dictOptions={}, IDmodele=None, ouverture=True, nomFichier=None):
        """ Impression """
        global DICT_VALEURS, DICT_OPTIONS
        DICT_VALEURS = dictValeurs
        DICT_OPTIONS = dictOptions
        
        # Initialisation du document
        if nomFichier == None :
            nomDoc = FonctionsPerso.GenerationNomDoc("COTISATIONS", "pdf")
        else :
            nomDoc = nomFichier
        doc = BaseDocTemplate(nomDoc, pagesize=TAILLE_PAGE, showBoundary=False)
        
        # Mémorise le ID du modèle
        modeleDoc = DLG_Noedoc.ModeleDoc(IDmodele=IDmodele)
        doc.modeleDoc = modeleDoc
        
        # Importe le template de la première page
        doc.addPageTemplates(MyPageTemplate(pageSize=TAILLE_PAGE, doc=doc))
        
        story = []
        styleSheet = getSampleStyleSheet()
        h3 = styleSheet['Heading3']
        styleTexte = styleSheet['BodyText'] 
        styleTexte.fontName = "Helvetica"
        styleTexte.fontSize = 9
        styleTexte.borderPadding = 9
        styleTexte.leading = 12
        
        # ----------- Insertion du contenu des frames --------------
        listeLabels = []
        for IDcotisation, dictValeur in dictValeurs.iteritems() :
            listeLabels.append((dictValeur["{FAMILLE_NOM}"], IDcotisation))
        listeLabels.sort() 
        
        for labelDoc, IDcotisation in listeLabels :
            dictValeur = dictValeurs[IDcotisation]
            if dictValeur["select"] == True :
                
                story.append(DocAssign("IDcotisation", IDcotisation))
                nomSansCivilite = dictValeur["{FAMILLE_NOM}"]
                story.append(Bookmark(nomSansCivilite, str(IDcotisation)))
                
##                # ------------------- TITRE -----------------
##                dataTableau = []
##                largeursColonnes = [ TAILLE_CADRE_CONTENU[2], ]
##                dataTableau.append((dictCompte["titre"],))
##                texteDateReference = UTILS_Dates.DateEngFr(str(datetime.date.today()))
##                dataTableau.append((_(u"Situation au %s") % texteDateReference,))
##                style = TableStyle([
##                        ('VALIGN', (0,0), (-1,-1), 'MIDDLE'), 
##                        ('FONT',(0,0),(0,0), "Helvetica-Bold", 19), 
##                        ('FONT',(0,1),(0,1), "Helvetica", 8), 
##                        ('LINEBELOW', (0,0), (0,0), 0.25, colors.black), 
##                        ('ALIGN', (0,0), (-1,-1), 'LEFT'), 
##                        ])
##                tableau = Table(dataTableau, largeursColonnes)
##                tableau.setStyle(style)
##                story.append(tableau)
##                story.append(Spacer(0,30))
##                
##                    
##                couleurFond = (0.8, 0.8, 1)
##                couleurFondActivite = (0.92, 0.92, 1)
##                        
##                # TEXTE CONTENU
##                paraStyle = ParagraphStyle(name="contenu",
##                              fontName="Helvetica",
##                              fontSize=11,
##                              #leading=7,
##                              spaceBefore=0,
##                              spaceafter=0,
##                              leftIndent=6,
##                              rightIndent=6,
##                            )
##                
##                texte = dictCompte["texte"]
##                listeParagraphes = texte.split("</para>")
##                for paragraphe in listeParagraphes :
##                    textePara = Paragraph(u"%s</para>" % paragraphe, paraStyle)
##                    story.append(textePara)
                
                # Saut de page
                story.append(PageBreak())
        
        # Finalisation du PDF
        doc.build(story)
        
        # Ouverture du PDF
        if ouverture == True :
            FonctionsPerso.LanceFichierExterne(nomDoc)
    def __init__(self,
                 dictValeurs={},
                 dictOptions={},
                 IDmodele=None,
                 ouverture=True,
                 nomFichier=None):
        """ Impression """
        global DICT_VALEURS, DICT_OPTIONS
        DICT_VALEURS = dictValeurs
        DICT_OPTIONS = dictOptions

        # Initialisation du document
        if nomFichier == None:
            nomDoc = FonctionsPerso.GenerationNomDoc("INSCRIPTIONS", "pdf")
        else:
            nomDoc = nomFichier
        doc = BaseDocTemplate(nomDoc, pagesize=TAILLE_PAGE, showBoundary=False)

        # Mémorise le ID du modèle
        modeleDoc = DLG_Noedoc.ModeleDoc(IDmodele=IDmodele)
        doc.modeleDoc = modeleDoc

        # Importe le template de la première page
        doc.addPageTemplates(MyPageTemplate(pageSize=TAILLE_PAGE, doc=doc))

        story = []
        styleSheet = getSampleStyleSheet()
        h3 = styleSheet['Heading3']
        styleTexte = styleSheet['BodyText']
        styleTexte.fontName = "Helvetica"
        styleTexte.fontSize = 9
        styleTexte.borderPadding = 9
        styleTexte.leading = 12

        # ----------- Insertion du contenu des frames --------------
        listeLabels = []
        for IDinscription, dictValeur in dictValeurs.items():
            listeLabels.append((dictValeur["{FAMILLE_NOM}"], IDinscription))
        listeLabels.sort()

        for labelDoc, IDinscription in listeLabels:
            dictValeur = dictValeurs[IDinscription]
            if dictValeur["select"] == True:
                story.append(DocAssign("IDinscription", IDinscription))
                nomSansCivilite = dictValeur["{FAMILLE_NOM}"]
                story.append(Bookmark(nomSansCivilite, str(IDinscription)))

                # ----------- Insertion du cadre principal --------------
                cadre_principal = doc.modeleDoc.FindObjet("cadre_principal")
                if cadre_principal != None:

                    if "intro" in DICT_OPTIONS and DICT_OPTIONS[
                            "intro"] != None or "tableau" in DICT_OPTIONS and DICT_VALEURS[
                                "tableau"] == True:
                        # ------------------- TITRE -----------------
                        dataTableau = []
                        largeursColonnes = [
                            TAILLE_CADRE_CONTENU[2],
                        ]
                        dataTableau.append(
                            (_(u"Confirmation d'inscription"), ))
                        dataTableau.append((u"", ))
                        style = TableStyle([
                            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                            ('FONT', (0, 0), (0, 0), "Helvetica-Bold", 19),
                            ('FONT', (0, 1), (0, 1), "Helvetica", 8),
                            ('LINEBELOW', (0, 0), (0, 0), 0.25, colors.black),
                            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
                        ])
                        tableau = Table(dataTableau, largeursColonnes)
                        tableau.setStyle(style)
                        story.append(tableau)
                        story.append(Spacer(0, 10))

                        # TEXTE D'INTRODUCTION
                        paraStyleIntro = ParagraphStyle(
                            name="intro",
                            fontName="Helvetica",
                            fontSize=11,
                            leading=14,
                            spaceBefore=0,
                            spaceafter=0,
                            leftIndent=0,
                            rightIndent=0,
                            alignment=0,
                        )

                    if "intro" in DICT_OPTIONS and DICT_OPTIONS[
                            "intro"] != None:
                        texteIntro = DICT_VALEURS["intro"]
                        story.append(
                            Paragraph(u"<i>%s</i>" % texteIntro,
                                      paraStyleIntro))
                        story.append(Spacer(0, 20))

                    if "tableau" in DICT_OPTIONS and DICT_OPTIONS[
                            "tableau"] == True:
                        # ------------------- TABLEAU CONTENU -----------------
                        dataTableau = []
                        largeursColonnes = [80, 280]
                        paraStyle = ParagraphStyle(
                            name="detail",
                            fontName="Helvetica-Bold",
                            fontSize=9,
                        )
                        dataTableau.append(
                            (_(u"Nom"),
                             Paragraph(DICT_VALEURS["{INDIVIDU_NOM}"],
                                       paraStyle)))
                        dataTableau.append(
                            (_(u"Prénom"),
                             Paragraph(DICT_VALEURS["{INDIVIDU_PRENOM}"],
                                       paraStyle)))
                        dataTableau.append(
                            (_(u"Activité"),
                             Paragraph(DICT_VALEURS["{ACTIVITE_NOM_LONG}"],
                                       paraStyle)))
                        dataTableau.append(
                            (_(u"Groupe"),
                             Paragraph(DICT_VALEURS["{GROUPE_NOM_LONG}"],
                                       paraStyle)))
                        dataTableau.append(
                            (_(u"Catégorie"),
                             Paragraph(DICT_VALEURS["{NOM_CATEGORIE_TARIF}"],
                                       paraStyle)))

                        style = TableStyle([
                            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                            ('FONT', (0, 0), (0, -1), "Helvetica", 9),
                            ('GRID', (0, 0), (-1, -1), 0.25, colors.black),
                            ('ALIGN', (0, 0), (0, -1), 'RIGHT'),
                        ])
                        tableau = Table(dataTableau, largeursColonnes)
                        tableau.setStyle(style)
                        story.append(tableau)

                # Saut de page
                story.append(PageBreak())

        # Finalisation du PDF
        doc.build(story)

        # Ouverture du PDF
        if ouverture == True:
            FonctionsPerso.LanceFichierExterne(nomDoc)
    def __init__(self, dictValeurs={}, IDmodele=None, nomDoc=FonctionsPerso.GenerationNomDoc("INSCRIPTION", "pdf"), afficherDoc=True):
        """ Impression """
        global DICT_VALEURS
        DICT_VALEURS = dictValeurs
        
        # Initialisation du document
        doc = BaseDocTemplate(nomDoc, pagesize=TAILLE_PAGE, showBoundary=False)
        
        # Mémorise le ID du modèle
        modeleDoc = DLG_Noedoc.ModeleDoc(IDmodele=IDmodele)
        doc.modeleDoc = modeleDoc
        
        doc.addPageTemplates(MyPageTemplate(pageSize=TAILLE_PAGE, doc=doc))
        
        story = []
        styleSheet = getSampleStyleSheet()
        h3 = styleSheet['Heading3']
        styleTexte = styleSheet['BodyText'] 
        styleTexte.fontName = "Helvetica"
        styleTexte.fontSize = 9
        styleTexte.borderPadding = 9
        styleTexte.leading = 12
        couleurFond = (0.8, 0.8, 1)
        
        # ----------- Insertion du contenu des frames --------------
        cadre_principal = doc.modeleDoc.FindObjet("cadre_principal")
        if cadre_principal != None :
            
            if DICT_VALEURS["intro"] != None or DICT_VALEURS["tableau"] == True :
            
                # ------------------- TITRE -----------------
                dataTableau = []
                largeursColonnes = [ TAILLE_CADRE_CONTENU[2], ]
                dataTableau.append((_(u"Confirmation d'inscription"),))
                dataTableau.append((u"",))
                style = TableStyle([
                        ('VALIGN', (0,0), (-1,-1), 'MIDDLE'), 
                        ('FONT',(0,0),(0,0), "Helvetica-Bold", 19), 
                        ('FONT',(0,1),(0,1), "Helvetica", 8), 
                        ('LINEBELOW', (0,0), (0,0), 0.25, colors.black), 
                        ('ALIGN', (0,0), (-1,-1), 'LEFT'), 
                        ])
                tableau = Table(dataTableau, largeursColonnes)
                tableau.setStyle(style)
                story.append(tableau)
                story.append(Spacer(0, 10))
                
                # TEXTE D'INTRODUCTION
                paraStyleIntro = ParagraphStyle(name="intro",
                                      fontName="Helvetica",
                                      fontSize=11,
                                      leading=14,
                                      spaceBefore=0,
                                      spaceafter=0,
                                      leftIndent=0,
                                      rightIndent=0,
                                      alignment=0,
                                    )

            if DICT_VALEURS["intro"] != None :
                texteIntro = DICT_VALEURS["intro"]
                story.append(Paragraph(u"<i>%s</i>" % texteIntro, paraStyleIntro))
                story.append(Spacer(0,20))
                
            
            if DICT_VALEURS["tableau"] == True :
                
                # ------------------- TABLEAU CONTENU -----------------
                dataTableau = []
                largeursColonnes = [ 80, 280]
                paraStyle = ParagraphStyle(name="detail",
                                          fontName="Helvetica-Bold",
                                          fontSize=9,
                                        )
                dataTableau.append( (_(u"Nom"), Paragraph(DICT_VALEURS["{INDIVIDU_NOM}"], paraStyle)) )
                dataTableau.append( (_(u"Prénom"), Paragraph(DICT_VALEURS["{INDIVIDU_PRENOM}"], paraStyle)) )
                dataTableau.append( (_(u"Activité"), Paragraph(DICT_VALEURS["{ACTIVITE_NOM_LONG}"], paraStyle)) )
                dataTableau.append( (_(u"Groupe"), Paragraph(DICT_VALEURS["{GROUPE_NOM_LONG}"], paraStyle)) )
                dataTableau.append( (_(u"Catégorie"), Paragraph(DICT_VALEURS["{NOM_CATEGORIE_TARIF}"], paraStyle)) )

                
                style = TableStyle([
                        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), 
                        ('FONT', (0, 0), (0, -1), "Helvetica", 9), 
                        ('GRID', (0, 0), (-1, -1), 0.25, colors.black),
                        ('ALIGN', (0, 0), (0, -1), 'RIGHT'),
                        ])
                tableau = Table(dataTableau, largeursColonnes)
                tableau.setStyle(style)
                story.append(tableau)
        
        # Si aucune frame principale
        if len(story) == 0 :
            story.append(Spacer(0,20))
        
        # Enregistrement et ouverture du PDF
        try :
            doc.build(story)
        except Exception, err :
            print "Erreur dans ouverture PDF :", err
            if "Permission denied" in err :
                dlg = wx.MessageDialog(None, _(u"Noethys ne peut pas créer le PDF.\n\nVeuillez vérifier qu'un autre PDF n'est pas déjà ouvert en arrière-plan..."), _(u"Erreur d'édition"), wx.OK | wx.ICON_ERROR)
                dlg.ShowModal()
                dlg.Destroy()
                return
    def __init__(self,
                 dictValeurs={},
                 IDmodele=None,
                 nomDoc=FonctionsPerso.GenerationNomDoc(
                     "RECU_REGLEMENT", "pdf"),
                 afficherDoc=True):
        """ Impression """
        global DICT_VALEURS
        DICT_VALEURS = dictValeurs

        # Initialisation du document
        doc = BaseDocTemplate(nomDoc, pagesize=TAILLE_PAGE, showBoundary=False)

        # Mémorise le ID du modèle
        modeleDoc = DLG_Noedoc.ModeleDoc(IDmodele=IDmodele)
        doc.modeleDoc = modeleDoc

        # Vérifie qu'un cadre principal existe bien dans le document
        if doc.modeleDoc.FindObjet("cadre_principal") == None:
            raise Exception(
                "Votre modele de document doit obligatoirement comporter un cadre principal. Retournez dans l'editeur de document et utilisez pour votre modele la commande 'Inserer un objet special > Inserer le cadre principal'."
            )

        # Mémorise le ID du modèle
        modeleDoc = DLG_Noedoc.ModeleDoc(IDmodele=IDmodele)
        doc.modeleDoc = modeleDoc

        doc.addPageTemplates(MyPageTemplate(pageSize=TAILLE_PAGE, doc=doc))

        story = []
        styleSheet = getSampleStyleSheet()
        h3 = styleSheet['Heading3']
        styleTexte = styleSheet['BodyText']
        styleTexte.fontName = "Helvetica"
        styleTexte.fontSize = 9
        styleTexte.borderPadding = 9
        styleTexte.leading = 12

        ##        # Définit le template des pages suivantes
        ##        story.append(NextPageTemplate("suivante"))

        # ----------- Insertion du contenu des frames --------------

        # ------------------- TITRE -----------------
        dataTableau = []
        largeursColonnes = [
            TAILLE_CADRE_CONTENU[2],
        ]
        dataTableau.append((_(u"Reçu de règlement"), ))
        dataTableau.append((u"", ))
        style = TableStyle([
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('FONT', (0, 0), (0, 0), "Helvetica-Bold", 19),
            ('FONT', (0, 1), (0, 1), "Helvetica", 8),
            ('LINEBELOW', (0, 0), (0, 0), 0.25, colors.black),
            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
        ])
        tableau = Table(dataTableau, largeursColonnes)
        tableau.setStyle(style)
        story.append(tableau)
        story.append(Spacer(0, 10))

        # TEXTE D'INTRODUCTION
        paraStyleIntro = ParagraphStyle(
            name="intro",
            fontName="Helvetica",
            fontSize=11,
            leading=14,
            spaceBefore=0,
            spaceafter=0,
            leftIndent=0,
            rightIndent=0,
            alignment=0,
        )

        if DICT_VALEURS["intro"] != None:
            texteIntro = DICT_VALEURS["intro"]
            story.append(Paragraph(u"<i>%s</i>" % texteIntro, paraStyleIntro))
            story.append(Spacer(0, 20))

        couleurFond = (0.8, 0.8, 1)

        # ------------------- TABLEAU CONTENU -----------------

        dataTableau = []
        largeursColonnes = [120, 280]

        paraStyle = ParagraphStyle(
            name="detail",
            fontName="Helvetica-Bold",
            fontSize=9,
        )
        dataTableau.append((_(u"Caractéristiques du règlement"), ""))
        montantEnLettres = UTILS_Conversion.trad(DICT_VALEURS["montant"],
                                                 MONNAIE_SINGULIER,
                                                 MONNAIE_DIVISION).strip()
        dataTableau.append((_(u"Montant du règlement :"),
                            Paragraph(montantEnLettres.capitalize(),
                                      paraStyle)))
        dataTableau.append((_(u"Mode de règlement :"),
                            Paragraph(DICT_VALEURS["nomMode"], paraStyle)))
        dataTableau.append((_(u"Nom du payeur :"),
                            Paragraph(DICT_VALEURS["nomPayeur"], paraStyle)))
        if DICT_VALEURS["nomEmetteur"] != None:
            dataTableau.append((_(u"Nom de l'émetteur :"),
                                Paragraph(DICT_VALEURS["nomEmetteur"],
                                          paraStyle)))
        if DICT_VALEURS["numPiece"] not in ("", None):
            dataTableau.append((_(u"Numéro de pièce :"),
                                Paragraph(DICT_VALEURS["numPiece"],
                                          paraStyle)))

        style = TableStyle([
            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
            ('FONT', (0, 0), (0, -1), "Helvetica", 9),
            ('FONT', (1, 0), (1, -1), "Helvetica-Bold", 9),
            ('GRID', (0, 0), (-1, -1), 0.25, colors.black),
            ('ALIGN', (0, 1), (0, -1), 'RIGHT'),
            ('ALIGN', (1, 1), (1, -1), 'LEFT'),
            ('FONT', (0, 0), (0, 0), "Helvetica", 7),
            ('SPAN', (0, 0), (-1, 0)),
            ('BACKGROUND', (0, 0), (-1, 0), couleurFond),
        ])
        tableau = Table(dataTableau, largeursColonnes)
        tableau.setStyle(style)
        story.append(tableau)

        # --------------------- LISTE DES PRESTATIONS ----------------
        listePrestations = dictValeurs["prestations"]
        if len(listePrestations) > 0:

            story.append(Spacer(0, 20))
            textePrestations = _(u"En paiement des prestations suivantes :")
            story.append(
                Paragraph(u"<i>%s</i>" % textePrestations, paraStyleIntro))
            story.append(Spacer(0, 20))

            dataTableau = [
                (_(u"Date"), _(u"Activité"), _(u"Individu"), _(u"Intitulé"),
                 _(u"Part utilisée")),
            ]
            largeursColonnes = [50, 95, 70, 135, 50]

            paraStyle = ParagraphStyle(
                name="detail",
                fontName="Helvetica",
                fontSize=7,
                leading=7,
                spaceBefore=0,
                spaceAfter=0,
            )

            for dictPrestation in listePrestations:
                date = UTILS_Dates.DateDDEnFr(dictPrestation["date"])
                activite = dictPrestation["nomActivite"]
                individu = dictPrestation["prenomIndividu"]
                label = dictPrestation["label"]
                montant = dictPrestation["montant"]
                ventilation = dictPrestation["ventilation"]

                dataTableau.append((
                    Paragraph(u"<para align='center'>%s</para>" % date,
                              paraStyle),
                    Paragraph(activite, paraStyle),
                    Paragraph(individu, paraStyle),
                    Paragraph(label, paraStyle),
                    Paragraph(
                        u"<para align='right'>%.2f %s</para>" %
                        (ventilation, SYMBOLE), paraStyle),
                ))

            style = TableStyle([
                ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                ('GRID', (0, 0), (-1, -1), 0.25, colors.black),
                ('FONT', (0, 0), (-1, -1), "Helvetica", 7),
                ('TOPPADDING', (0, 1), (-1, -1), 1),
                ('BOTTOMPADDING', (0, 1), (-1, -1), 3),

                # Ligne Entetes
                ('FONT', (0, 0), (-1, 0), "Helvetica", 7),
                ('BACKGROUND', (0, 0), (-1, 0), couleurFond),
                ('ALIGN', (0, 0), (-1, 0), 'CENTER'),
            ])
            tableau = Table(dataTableau, largeursColonnes)
            tableau.setStyle(style)
            story.append(tableau)

        # Enregistrement et ouverture du PDF
        try:
            doc.build(story)
        except Exception, err:
            print "Erreur dans ouverture PDF :", err
            if "Permission denied" in err:
                dlg = wx.MessageDialog(
                    None,
                    _(u"Noethys ne peut pas créer le PDF.\n\nVeuillez vérifier qu'un autre PDF n'est pas déjà ouvert en arrière-plan..."
                      ), _(u"Erreur d'édition"), wx.OK | wx.ICON_ERROR)
                dlg.ShowModal()
                dlg.Destroy()
                return
    def __init__(self,
                 dictValeurs={},
                 dictOptions={},
                 IDmodele=None,
                 ouverture=True,
                 nomFichier=None):
        """ Impression """
        global DICT_VALEURS, DICT_OPTIONS
        DICT_VALEURS = dictValeurs
        DICT_OPTIONS = dictOptions

        # Initialisation du document
        if nomFichier == None:
            nomDoc = FonctionsPerso.GenerationNomDoc("COTISATIONS", "pdf")
        else:
            nomDoc = nomFichier
        doc = BaseDocTemplate(nomDoc, pagesize=TAILLE_PAGE, showBoundary=False)

        # Mémorise le ID du modèle
        modeleDoc = DLG_Noedoc.ModeleDoc(IDmodele=IDmodele)
        doc.modeleDoc = modeleDoc

        # Importe le template de la première page
        doc.addPageTemplates(MyPageTemplate(pageSize=TAILLE_PAGE, doc=doc))

        story = []
        styleSheet = getSampleStyleSheet()
        h3 = styleSheet['Heading3']
        styleTexte = styleSheet['BodyText']
        styleTexte.fontName = "Helvetica"
        styleTexte.fontSize = 9
        styleTexte.borderPadding = 9
        styleTexte.leading = 12

        # ----------- Insertion du contenu des frames --------------
        listeLabels = []
        for IDcotisation, dictValeur in dictValeurs.iteritems():
            listeLabels.append((dictValeur["{FAMILLE_NOM}"], IDcotisation))
        listeLabels.sort()

        for labelDoc, IDcotisation in listeLabels:
            dictValeur = dictValeurs[IDcotisation]
            if dictValeur["select"] == True:

                story.append(DocAssign("IDcotisation", IDcotisation))
                nomSansCivilite = dictValeur["{FAMILLE_NOM}"]
                story.append(Bookmark(nomSansCivilite, str(IDcotisation)))

                ##                # ------------------- TITRE -----------------
                ##                dataTableau = []
                ##                largeursColonnes = [ TAILLE_CADRE_CONTENU[2], ]
                ##                dataTableau.append((dictCompte["titre"],))
                ##                texteDateReference = UTILS_Dates.DateEngFr(str(datetime.date.today()))
                ##                dataTableau.append((_(u"Situation au %s") % texteDateReference,))
                ##                style = TableStyle([
                ##                        ('VALIGN', (0,0), (-1,-1), 'MIDDLE'),
                ##                        ('FONT',(0,0),(0,0), "Helvetica-Bold", 19),
                ##                        ('FONT',(0,1),(0,1), "Helvetica", 8),
                ##                        ('LINEBELOW', (0,0), (0,0), 0.25, colors.black),
                ##                        ('ALIGN', (0,0), (-1,-1), 'LEFT'),
                ##                        ])
                ##                tableau = Table(dataTableau, largeursColonnes)
                ##                tableau.setStyle(style)
                ##                story.append(tableau)
                ##                story.append(Spacer(0,30))
                ##
                ##
                ##                couleurFond = (0.8, 0.8, 1)
                ##                couleurFondActivite = (0.92, 0.92, 1)
                ##
                ##                # TEXTE CONTENU
                ##                paraStyle = ParagraphStyle(name="contenu",
                ##                              fontName="Helvetica",
                ##                              fontSize=11,
                ##                              #leading=7,
                ##                              spaceBefore=0,
                ##                              spaceafter=0,
                ##                              leftIndent=6,
                ##                              rightIndent=6,
                ##                            )
                ##
                ##                texte = dictCompte["texte"]
                ##                listeParagraphes = texte.split("</para>")
                ##                for paragraphe in listeParagraphes :
                ##                    textePara = Paragraph(u"%s</para>" % paragraphe, paraStyle)
                ##                    story.append(textePara)

                # Saut de page
                story.append(PageBreak())

        # Finalisation du PDF
        doc.build(story)

        # Ouverture du PDF
        if ouverture == True:
            FonctionsPerso.LanceFichierExterne(nomDoc)
    def __init__(self, dictComptes={}, dictOptions={}, IDmodele=None, ouverture=True, nomFichier=None):
        """ Impression """
        global DICT_COMPTES, DICT_OPTIONS
        DICT_COMPTES = dictComptes
        DICT_OPTIONS = dictOptions
        
        # Initialisation du document
        if nomFichier == None :
            nomDoc = "Temp/RAPPELS%s.pdf" % FonctionsPerso.GenerationIDdoc() 
        else :
            nomDoc = nomFichier
        doc = BaseDocTemplate(nomDoc, pagesize=TAILLE_PAGE, showBoundary=False)
        
        # Mémorise le ID du modèle
        modeleDoc = DLG_Noedoc.ModeleDoc(IDmodele=IDmodele)
        doc.modeleDoc = modeleDoc

        # Vérifie qu'un cadre principal existe bien dans le document
        if doc.modeleDoc.FindObjet("cadre_principal") == None :
            raise Exception("Votre modèle de document doit obligatoirement comporter un cadre principal. Retournez dans l'éditeur de document et utilisez pour votre modèle la commande 'Insérer un objet spécial > Insérer le cadre principal'.")

        # Importe le template de la première page
        doc.addPageTemplates(MyPageTemplate(pageSize=TAILLE_PAGE, doc=doc))
        
        story = []
        styleSheet = getSampleStyleSheet()
        h3 = styleSheet['Heading3']
        styleTexte = styleSheet['BodyText'] 
        styleTexte.fontName = "Helvetica"
        styleTexte.fontSize = 9
        styleTexte.borderPadding = 9
        styleTexte.leading = 12
        
##        # Définit le template des pages suivantes
##        story.append(NextPageTemplate("suivante"))
        
        
        # ----------- Insertion du contenu des frames --------------
        listeNomsSansCivilite = []
        for IDcompte_payeur, dictCompte in dictComptes.iteritems() :
            listeNomsSansCivilite.append((dictCompte["nomSansCivilite"], IDcompte_payeur))
        listeNomsSansCivilite.sort() 
        
        for nomSansCivilite, IDcompte_payeur in listeNomsSansCivilite :
            dictCompte = dictComptes[IDcompte_payeur]
            if dictCompte["select"] == True :
                
                story.append(DocAssign("IDcompte_payeur", IDcompte_payeur))
                nomSansCivilite = dictCompte["nomSansCivilite"]
                story.append(Bookmark(nomSansCivilite, str(IDcompte_payeur)))
                
                # ------------------- TITRE -----------------
                dataTableau = []
                largeursColonnes = [ TAILLE_CADRE_CONTENU[2], ]
                dataTableau.append((dictCompte["titre"],))
                texteDateReference = DateEngFr(str(datetime.date.today()))
                dataTableau.append((_(u"Situation au %s") % texteDateReference,))
                style = TableStyle([
                        ('VALIGN', (0,0), (-1,-1), 'MIDDLE'), 
                        ('FONT',(0,0),(0,0), "Helvetica-Bold", 19), 
                        ('FONT',(0,1),(0,1), "Helvetica", 8), 
                        ('LINEBELOW', (0,0), (0,0), 0.25, colors.black), 
                        ('ALIGN', (0,0), (-1,-1), 'LEFT'), 
                        ])
                tableau = Table(dataTableau, largeursColonnes)
                tableau.setStyle(style)
                story.append(tableau)
                story.append(Spacer(0,30))
                
                couleurFond = (0.8, 0.8, 1)
                couleurFondActivite = (0.92, 0.92, 1)
                        
                # TEXTE CONTENU
                paraStyle = ParagraphStyle(name="contenu",
                              fontName="Helvetica",
                              fontSize=11,
                              #leading=7,
                              spaceBefore=0,
                              spaceafter=0,
                              leftIndent=6,
                              rightIndent=6,
                            )
                
                texte = dictCompte["texte"]
                listeParagraphes = texte.split("</para>")
                for paragraphe in listeParagraphes :
                    paragraphe = u"%s</para>" % paragraphe
                    textePara = Paragraph(paragraphe, paraStyle)
                    story.append(textePara)
                    if "> </para" in paragraphe :
                        story.append(Spacer(0, 13))
                
                # Saut de page
                story.append(PageBreak())
        
        # Finalisation du PDF
        doc.build(story)
        
        # Ouverture du PDF
        if ouverture == True :
            FonctionsPerso.LanceFichierExterne(nomDoc)
示例#13
0
class ValuationPrint():

    def __init__(self, filename):

        self.width, self.height = pagesizes.A4
        self.lmargin = 1*units.cm
        self.rmargin = self.width - self.lmargin
        #styles = getSampleStyleSheet()
        #self.styleH = styles['Heading1']
        #self.styleN = styles['Normal']
        self.doc = BaseDocTemplate(filename)
        self.val_template = PageTemplate(id='valuation',
                                         frames=[Frame(self.lmargin, 5*units.cm,
                                                       19*units.cm, 15.5*units.cm, id='table',
                                                       showBoundary=0)],
                                         onPage=self.setup_page)
        self.doc.addPageTemplates(self.val_template)

    def setup_page(self, canvas, doc):
        canvas.saveState()
        self.do_title(canvas)
        self.do_client_name(canvas)
        self.do_date(canvas)
        self.do_person_bg(canvas)
        canvas.restoreState()

    def do_person_bg(self, canvas):
        canvas.saveState()
        ref = self.data.person_code + '/' + self.data.business_getter
        canvas.setFont('Times-Roman', 12)
        canvas.drawRightString(self.rmargin, 22*units.cm, ref)
        canvas.restoreState()

    def do_date(self, canvas):
        canvas.saveState()
        canvas.setFont('Times-Roman', 12)
        dt = time.strptime(self.data.valuation_date, '%Y%m%d')
        canvas.drawString(self.lmargin, 22*units.cm, datetime.date(*dt[0: 3]).strftime('%dth %B %Y'))
        canvas.restoreState()

    def do_title(self, canvas):
        canvas.saveState()
        canvas.setFont('Times-Bold', 14)
        canvas.drawString(self.lmargin, 25*units.cm, 'Portfolio Valuation')
        canvas.restoreState()

    def do_client_name(self, canvas):
        canvas.saveState()
        canvas.setFont('Times-Bold', 14)
        canvas.drawString(self.lmargin, 23*units.cm, self.data.name_and_address["client_name"])
        canvas.restoreState()

    def create_pdf(self, data):
        self.data = data
        story = []
        dta = [[ValuationTable.heading_line(['Description', 'Book Cost', 'Holding',
                                            'Price', 'Value', 'Est. Income', 'Yield (%)'])]]
        dta.extend(ValuationTable.format_data(self.data.holdings))
        dta.extend(ValuationTable.format_cash_lines(self.data.valuation_cash, self.data.name_and_address))
        dta.extend(ValuationTable.format_total_lines(self.data.totals))
        story.append(ValuationTable(dta))
        self.doc.build(story)
示例#14
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("ATTESTATIONS_FISCALES",
                                                     "pdf")
        else:
            nomDoc = nomFichier
        doc = BaseDocTemplate(nomDoc, pagesize=TAILLE_PAGE, showBoundary=False)

        # Mémorise le ID du modèle
        modeleDoc = DLG_Noedoc.ModeleDoc(IDmodele=IDmodele)
        doc.modeleDoc = modeleDoc

        # Vérifie qu'un cadre principal existe bien dans le document
        if doc.modeleDoc.FindObjet("cadre_principal") == None:
            raise Exception(
                "Votre modele de document doit obligatoirement comporter un cadre principal. Retournez dans l'editeur de document et utilisez pour votre modele la commande 'Inserer un objet special > Inserer le cadre principal'."
            )

        # Mémorise le ID du modèle
        modeleDoc = DLG_Noedoc.ModeleDoc(IDmodele=IDmodele)
        doc.modeleDoc = modeleDoc

        # Importe le template de la première page
        doc.addPageTemplates(MyPageTemplate(pageSize=TAILLE_PAGE, doc=doc))

        story = []
        styleSheet = getSampleStyleSheet()
        h3 = styleSheet['Heading3']
        styleTexte = styleSheet['BodyText']
        styleTexte.fontName = "Helvetica"
        styleTexte.fontSize = 9
        styleTexte.borderPadding = 9
        styleTexte.leading = 12

        ##        # Définit le template des pages suivantes
        ##        story.append(NextPageTemplate("suivante"))

        # ----------- Insertion du contenu des frames --------------
        listeNomsSansCivilite = []
        for IDcompte_payeur, dictCompte in dictComptes.items():
            listeNomsSansCivilite.append(
                (dictCompte["{FAMILLE_NOM}"], IDcompte_payeur))
        listeNomsSansCivilite.sort()

        for nomSansCivilite, IDcompte_payeur in listeNomsSansCivilite:
            dictCompte = dictComptes[IDcompte_payeur]

            story.append(DocAssign("IDcompte_payeur", IDcompte_payeur))
            nomSansCivilite = dictCompte["{FAMILLE_NOM}"]
            story.append(Bookmark(nomSansCivilite, str(IDcompte_payeur)))

            # ------------------- TITRE -----------------
            dataTableau = []
            largeursColonnes = [
                TAILLE_CADRE_CONTENU[2],
            ]
            dataTableau.append((dictOptions["titre"], ))
            texteDateReference = UTILS_Dates.DateEngFr(
                str(datetime.date.today()))
            dataTableau.append(
                (_(u"Période du %s au %s") %
                 (UTILS_Dates.DateDDEnFr(dictOptions["date_debut"]),
                  UTILS_Dates.DateDDEnFr(dictOptions["date_fin"])), ))
            style = TableStyle([
                ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                ('FONT', (0, 0), (0, 0), "Helvetica-Bold", 19),
                ('FONT', (0, 1), (0, 1), "Helvetica", 8),
                ('LINEBELOW', (0, 0), (0, 0), 0.25, colors.black),
                ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
            ])
            tableau = Table(dataTableau, largeursColonnes)
            tableau.setStyle(style)
            story.append(tableau)
            story.append(Spacer(0, 30))

            couleurFond = (0.8, 0.8, 1)
            couleurFondActivite = (0.92, 0.92, 1)

            # TEXTE CONTENU
            paraStyle = ParagraphStyle(
                name="contenu",
                fontName="Helvetica",
                fontSize=11,
                leading=16,
                spaceBefore=0,
                spaceafter=0,
                leftIndent=6,
                rightIndent=6,
            )

            # INTRO
            texte = dictCompte["{INTRO}"]
            if texte != "":
                listeParagraphes = texte.split("</para>")
                for paragraphe in listeParagraphes:
                    textePara = Paragraph(u"%s" % paragraphe, paraStyle)
                    story.append(textePara)

                story.append(Spacer(0, 25))

            # DETAIL par enfant
            dataTableau = [
                (_(u"Nom et prénom"), _(u"Date de naissance"), _(u"Montant")),
            ]
            largeursColonnes = [220, 80, 80]

            paraStyle = ParagraphStyle(
                name="detail",
                fontName="Helvetica-Bold",
                fontSize=9,
            )

            for nomCompletIndividu, dictIndividu in dictCompte["individus"]:
                dataTableau.append(
                    (nomCompletIndividu, dictIndividu["date_naiss"],
                     u"%.2f %s" % (dictIndividu["regle"], SYMBOLE)))

            dataTableau.append(("", "Total :", dictCompte["{MONTANT_REGLE}"]))

            style = TableStyle([
                ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                ('GRID', (0, 0), (-1, -2), 0.25, colors.black),
                ('FONT', (0, 0), (-1, 0), "Helvetica", 6),
                ('FONT', (0, 1), (-1, -1), "Helvetica", 10),
                ('TOPPADDING', (0, 1), (-1, -2), 10),
                ('BOTTOMPADDING', (0, 1), (-1, -2), 10),
                ('GRID', (-1, -1), (-1, -1), 0.25, colors.black),
                ('FONT', (-1, -1), (-1, -1), "Helvetica-Bold", 10),
                ('ALIGN', (-2, -1), (-2, -1), 'RIGHT'),
                ('FONT', (-2, -1), (-2, -1), "Helvetica", 6),
            ])
            tableau = Table(dataTableau, largeursColonnes)
            tableau.setStyle(style)
            story.append(tableau)

            # Saut de page
            story.append(PageBreak())

        # Finalisation du PDF
        doc.build(story)

        # Ouverture du PDF
        if ouverture == True:
            FonctionsPerso.LanceFichierExterne(nomDoc)
示例#15
0
class DFsignaturePDF(object):
    def __init__(self, name, study_name):
        self.doc = BaseDocTemplate(name,
                                   title=name,
                                   showBoundary=0,
                                   pagesize=letter)
        template = PageTemplate('normal',
                                [Frame(inch, inch, 6.5 * inch, 8.4 * inch)],
                                onPageEnd=self.pageHeader)
        self.doc.addPageTemplates(template)
        #self.doc.setProgressCallBack(self.progressCB)
        self.styles = stylesheet()
        self.jobsize = 1
        self.headerId = 0
        self.headerVisitLabel = ''
        self.headerPlateLabel = ''
        self.studyName = study_name
        self.outlines = []
        self.outlineDesc = None
        self.outlineVisitLabel = None
        self.outlineID = 0
        self.content = [DFOutlines(self.outlines)]

    def close(self):
        self.doc.build(self.content)

    def setPageHeader(self, pid, visit_label, signature_label):
        self.headerId = pid
        self.headerVisitLabel = visit_label
        self.headerPlateLabel = signature_label

    def pageHeader(self, canvas, doc):
        if not self.headerId:
            return

        canvas.saveState()
        #canvas.rect(inch, 9.4*inch, 6.5*inch, 0.6*inch)

        canvas.setFillColor(black)
        canvas.setFont('Helvetica-Bold', 10)
        canvas.drawCentredString(4.25 * inch, 9.5 * inch + 24,
                                 'eSignature Report')
        canvas.drawCentredString(4.25 * inch, 9.5 * inch + 12, self.studyName)
        canvas.drawString(inch + 6, 9.5 * inch,
                          'Patient: {0}'.format(self.headerId))
        page_number = 'Page %s' % canvas.getPageNumber()

        canvas.setFont('Helvetica', 10)
        canvas.drawCentredString(4.25 * inch, 0.75 * inch, page_number)

        canvas.restoreState()

    def progressCB(self, typ, value):
        if typ == 'SIZE_EST':
            self.jobsize = value
            self.lastjobdone = 0
        if typ == 'PROGRESS':
            jobdone = 50 * value // self.jobsize
            if self.lastjobdone < jobdone:
                print('Progress: [{0}{1}]'.format('*' * jobdone,
                                                  ' ' * (50 - jobdone)))
                self.lastjobdone = jobdone

    def outputTable(self, label, values):
        styleH = self.styles['title']
        styleN = self.styles['default']
        self.content.append(CondPageBreak(2 * inch))
        self.content.append(Paragraph(label, styleH))

        if not values:
            self.content.append(Paragraph('No New or Changed Fields.', styleN))
            return

        fieldValueList = [[
            Paragraph('<para alignment="right"><b>Plate</b></para>', styleN),
            Paragraph('<para alignment="right"><b>Field</b></para>', styleN),
            Paragraph('<b>Description</b>', styleN),
            Paragraph('<b>Value</b>', styleN)
        ]]

        for (plate, field, fdesc, fvalue) in values or []:
            list_value = self.escape_string(fvalue)
            if field < 0:
                field = '-'
            else:
                field = str(field)

            fieldValueList.append([
                Paragraph('<para alignment="right">{0}.</para>'.format(plate),
                          styleN),
                Paragraph('<para alignment="right">{0}.</para>'.format(field),
                          styleN),
                Paragraph(fdesc, styleN),
                Paragraph('<para>{0}</para>'.format(list_value), styleN)
            ])

        table = Table(fieldValueList,
                      colWidths=[
                          0.1 * 6.3 * inch, 0.1 * 6.3 * inch, 0.3 * 6.3 * inch,
                          0.5 * 6.3 * inch
                      ],
                      splitByRow=1,
                      repeatRows=1,
                      hAlign='LEFT')
        tablestyle = TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP'),
                                 ('LINEBEFORE', (3, 0), (3, -1), 1, lightgrey),
                                 ('LINEABOVE', (0, 0), (-1, -1), 1, lightgrey)
                                 ])
        table.setStyle(tablestyle)
        self.content.append(table)

    def outputSignatureData(self, visit, plate, desc, who, sdate, stime,
                            fieldchanges, signaturevalues):
        styleH = self.styles['title']
        styleN = self.styles['default']
        styleR = self.styles['rightheader']
        styleB = self.styles['bold']
        sdate = sdate[0:4] + '/' + sdate[4:6] + '/' + sdate[6:8]
        stime = stime[0:2] + ':' + stime[2:4] + ':' + stime[4:6]

        if desc != self.outlineDesc:
            self.outlines.append(
                [desc, 'o{0}'.format(self.outlineID), 0, True])
            self.outlineDesc = desc
            self.outlineVisitLabel = None

        if self.headerVisitLabel != self.outlineVisitLabel:
            self.outlines.append([
                self.headerVisitLabel, 'o{0}'.format(self.outlineID + 1), 1,
                True
            ])
            self.outlineVisitLabel = self.headerVisitLabel

        bookmark = '{0} {1} {2}'.format(sdate, stime, who)
        self.outlines.append(
            [bookmark, 'o{0}'.format(self.outlineID + 2), 2, True])
        self.content.append(
            Paragraph(
                '<a name="o{0}"/><a name="o{1}"/><a name="o{2}"/>Signature Details'
                .format(self.outlineID, self.outlineID + 1,
                        self.outlineID + 2), styleH))
        signatureDetailsList = []
        signatureDetailsList.append([
            Paragraph('Server Time', styleR),
            Paragraph('{0} {1}'.format(sdate, stime), styleB)
        ])
        signatureDetailsList.append(
            [Paragraph('Description', styleR),
             Paragraph(desc, styleB)])
        signatureDetailsList.append(
            [Paragraph('Login', styleR),
             Paragraph(who, styleB)])
        signatureDetailsList.append([
            Paragraph('Visit', styleR),
            Paragraph('{0} ({1})'.format(visit, self.headerVisitLabel), styleB)
        ])
        signatureDetailsList.append([
            Paragraph('Plate', styleR),
            Paragraph('{0} ({1})'.format(plate, self.headerPlateLabel), styleB)
        ])
        table = Table(signatureDetailsList,
                      colWidths=[0.2 * 6.3 * inch, 0.8 * 6.3 * inch],
                      splitByRow=1,
                      repeatRows=1,
                      hAlign='LEFT')
        tablestyle = TableStyle([('VALIGN', (0, 0), (-1, -1), 'TOP'),
                                 ('LINEBEFORE', (1, 0), (1, -1), 1, lightgrey),
                                 ('LINEABOVE', (0, 0), (-1, -1), 1, lightgrey)
                                 ])
        table.setStyle(tablestyle)
        self.content.append(table)

        self.outputTable('New or Changed Data Values', fieldchanges)
        self.outputTable('Signature Field Values', signaturevalues)
        self.outlineID += 3

    def nextPage(self):
        self.content.append(PageBreak())

    ###########################################################################
    # escape_string - Escape special characters
    ###########################################################################
    def escape_string(self, s):
        s = s.replace('&', '&amp;')
        s = s.replace('<', '&lt;')
        s = s.replace('>', '&gt;')
        return s
示例#16
0
    def __init__(self,
                 dictValeurs={},
                 IDmodele=None,
                 nomDoc=FonctionsPerso.GenerationNomDoc("INSCRIPTION", "pdf"),
                 afficherDoc=True):
        """ Impression """
        global DICT_VALEURS
        DICT_VALEURS = dictValeurs

        # Initialisation du document
        doc = BaseDocTemplate(nomDoc, pagesize=TAILLE_PAGE, showBoundary=False)

        # Mémorise le ID du modèle
        modeleDoc = DLG_Noedoc.ModeleDoc(IDmodele=IDmodele)
        doc.modeleDoc = modeleDoc

        doc.addPageTemplates(MyPageTemplate(pageSize=TAILLE_PAGE, doc=doc))

        story = []
        styleSheet = getSampleStyleSheet()
        h3 = styleSheet['Heading3']
        styleTexte = styleSheet['BodyText']
        styleTexte.fontName = "Helvetica"
        styleTexte.fontSize = 9
        styleTexte.borderPadding = 9
        styleTexte.leading = 12
        couleurFond = (0.8, 0.8, 1)

        # ----------- Insertion du contenu des frames --------------
        cadre_principal = doc.modeleDoc.FindObjet("cadre_principal")
        if cadre_principal != None:

            if DICT_VALEURS["intro"] != None or DICT_VALEURS["tableau"] == True:

                # ------------------- TITRE -----------------
                dataTableau = []
                largeursColonnes = [
                    TAILLE_CADRE_CONTENU[2],
                ]
                dataTableau.append((_(u"Confirmation d'inscription"), ))
                dataTableau.append((u"", ))
                style = TableStyle([
                    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                    ('FONT', (0, 0), (0, 0), "Helvetica-Bold", 19),
                    ('FONT', (0, 1), (0, 1), "Helvetica", 8),
                    ('LINEBELOW', (0, 0), (0, 0), 0.25, colors.black),
                    ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
                ])
                tableau = Table(dataTableau, largeursColonnes)
                tableau.setStyle(style)
                story.append(tableau)
                story.append(Spacer(0, 10))

                # TEXTE D'INTRODUCTION
                paraStyleIntro = ParagraphStyle(
                    name="intro",
                    fontName="Helvetica",
                    fontSize=11,
                    leading=14,
                    spaceBefore=0,
                    spaceafter=0,
                    leftIndent=0,
                    rightIndent=0,
                    alignment=0,
                )

            if DICT_VALEURS["intro"] != None:
                texteIntro = DICT_VALEURS["intro"]
                story.append(
                    Paragraph(u"<i>%s</i>" % texteIntro, paraStyleIntro))
                story.append(Spacer(0, 20))

            if DICT_VALEURS["tableau"] == True:

                # ------------------- TABLEAU CONTENU -----------------
                dataTableau = []
                largeursColonnes = [80, 280]
                paraStyle = ParagraphStyle(
                    name="detail",
                    fontName="Helvetica-Bold",
                    fontSize=9,
                )
                dataTableau.append((_(u"Nom"),
                                    Paragraph(DICT_VALEURS["{INDIVIDU_NOM}"],
                                              paraStyle)))
                dataTableau.append(
                    (_(u"Prénom"),
                     Paragraph(DICT_VALEURS["{INDIVIDU_PRENOM}"], paraStyle)))
                dataTableau.append(
                    (_(u"Activité"),
                     Paragraph(DICT_VALEURS["{ACTIVITE_NOM_LONG}"],
                               paraStyle)))
                dataTableau.append(
                    (_(u"Groupe"),
                     Paragraph(DICT_VALEURS["{GROUPE_NOM_LONG}"], paraStyle)))
                dataTableau.append(
                    (_(u"Catégorie"),
                     Paragraph(DICT_VALEURS["{NOM_CATEGORIE_TARIF}"],
                               paraStyle)))

                style = TableStyle([
                    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                    ('FONT', (0, 0), (0, -1), "Helvetica", 9),
                    ('GRID', (0, 0), (-1, -1), 0.25, colors.black),
                    ('ALIGN', (0, 0), (0, -1), 'RIGHT'),
                ])
                tableau = Table(dataTableau, largeursColonnes)
                tableau.setStyle(style)
                story.append(tableau)

        # Si aucune frame principale
        if len(story) == 0:
            story.append(Spacer(0, 20))

        # Enregistrement et ouverture du PDF
        try:
            doc.build(story)
        except Exception, err:
            print "Erreur dans ouverture PDF :", err
            if "Permission denied" in err:
                dlg = wx.MessageDialog(
                    None,
                    _(u"Noethys ne peut pas créer le PDF.\n\nVeuillez vérifier qu'un autre PDF n'est pas déjà ouvert en arrière-plan..."
                      ), _(u"Erreur d'édition"), wx.OK | wx.ICON_ERROR)
                dlg.ShowModal()
                dlg.Destroy()
                return
示例#17
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"") 
    def __init__(self, dictComptes={}, dictOptions={}, IDmodele=None, ouverture=True, nomFichier=None):
        """ Impression """
        global DICT_COMPTES, DICT_OPTIONS
        DICT_COMPTES = dictComptes
        DICT_OPTIONS = dictOptions
        
        # Initialisation du document
        if nomFichier == None :
            nomDoc = FonctionsPerso.GenerationNomDoc("ATTESTATIONS_FISCALES", "pdf")
        else :
            nomDoc = nomFichier
        doc = BaseDocTemplate(nomDoc, pagesize=TAILLE_PAGE, showBoundary=False)

        # Mémorise le ID du modèle
        modeleDoc = DLG_Noedoc.ModeleDoc(IDmodele=IDmodele)
        doc.modeleDoc = modeleDoc

        # Vérifie qu'un cadre principal existe bien dans le document
        if doc.modeleDoc.FindObjet("cadre_principal") == None :
            raise Exception("Votre modele de document doit obligatoirement comporter un cadre principal. Retournez dans l'editeur de document et utilisez pour votre modele la commande 'Inserer un objet special > Inserer le cadre principal'.")

        # Mémorise le ID du modèle
        modeleDoc = DLG_Noedoc.ModeleDoc(IDmodele=IDmodele)
        doc.modeleDoc = modeleDoc
        
        # Importe le template de la première page
        doc.addPageTemplates(MyPageTemplate(pageSize=TAILLE_PAGE, doc=doc))
        
        story = []
        styleSheet = getSampleStyleSheet()
        h3 = styleSheet['Heading3']
        styleTexte = styleSheet['BodyText'] 
        styleTexte.fontName = "Helvetica"
        styleTexte.fontSize = 9
        styleTexte.borderPadding = 9
        styleTexte.leading = 12
        
##        # Définit le template des pages suivantes
##        story.append(NextPageTemplate("suivante"))
        
        
        # ----------- Insertion du contenu des frames --------------
        listeNomsSansCivilite = []
        for IDcompte_payeur, dictCompte in dictComptes.iteritems() :
            listeNomsSansCivilite.append((dictCompte["{FAMILLE_NOM}"], IDcompte_payeur))
        listeNomsSansCivilite.sort() 
        
        for nomSansCivilite, IDcompte_payeur in listeNomsSansCivilite :
            dictCompte = dictComptes[IDcompte_payeur]
                
            story.append(DocAssign("IDcompte_payeur", IDcompte_payeur))
            nomSansCivilite = dictCompte["{FAMILLE_NOM}"]
            story.append(Bookmark(nomSansCivilite, str(IDcompte_payeur)))
            
            # ------------------- TITRE -----------------
            dataTableau = []
            largeursColonnes = [ TAILLE_CADRE_CONTENU[2], ]
            dataTableau.append((dictOptions["titre"],))
            texteDateReference = UTILS_Dates.DateEngFr(str(datetime.date.today()))
            dataTableau.append((_(u"Période du %s au %s") % (UTILS_Dates.DateDDEnFr(dictOptions["date_debut"]), UTILS_Dates.DateDDEnFr(dictOptions["date_fin"])),))
            style = TableStyle([
                    ('VALIGN', (0,0), (-1,-1), 'MIDDLE'), 
                    ('FONT',(0,0),(0,0), "Helvetica-Bold", 19), 
                    ('FONT',(0,1),(0,1), "Helvetica", 8), 
                    ('LINEBELOW', (0,0), (0,0), 0.25, colors.black), 
                    ('ALIGN', (0,0), (-1,-1), 'LEFT'), 
                    ])
            tableau = Table(dataTableau, largeursColonnes)
            tableau.setStyle(style)
            story.append(tableau)
            story.append(Spacer(0, 30))
            
                
            couleurFond = (0.8, 0.8, 1)
            couleurFondActivite = (0.92, 0.92, 1)
                    
            # TEXTE CONTENU
            paraStyle = ParagraphStyle(name="contenu",
                          fontName="Helvetica",
                          fontSize=11,
                          leading=16,
                          spaceBefore=0,
                          spaceafter=0,
                          leftIndent=6,
                          rightIndent=6,
                        )
            
            # INTRO
            texte = dictCompte["{INTRO}"]
            if texte != "" :
                listeParagraphes = texte.split("</para>")
                for paragraphe in listeParagraphes :
                    textePara = Paragraph(u"%s" % paragraphe, paraStyle)
                    story.append(textePara)
                
                story.append(Spacer(0, 25))
            
            # DETAIL par enfant
            dataTableau = [(_(u"Nom et prénom"), _(u"Date de naissance"), _(u"Montant")),]
            largeursColonnes = [ 220, 80, 80]
            
            paraStyle = ParagraphStyle(name="detail",
                                      fontName="Helvetica-Bold",
                                      fontSize=9,
                                    )
            
            for nomCompletIndividu, dictIndividu in dictCompte["individus"] :
                dataTableau.append( (nomCompletIndividu, dictIndividu["date_naiss"],  u"%.2f %s" % (dictIndividu["regle"], SYMBOLE)) )
            
            dataTableau.append( ("", "Total :",  dictCompte["{MONTANT_REGLE}"]) )
            
            style = TableStyle([
                    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), 
                    ('ALIGN', (0, 0), (-1, -1), 'CENTER'),
                    ('GRID', (0, 0), (-1, -2), 0.25, colors.black),
                    ('FONT', (0, 0), (-1, 0), "Helvetica", 6), 
                    ('FONT', (0, 1), (-1, -1), "Helvetica", 10), 

                    ('TOPPADDING', (0, 1), (-1, -2), 10), 
                    ('BOTTOMPADDING', (0, 1), (-1, -2), 10), 
                    
                    ('GRID', (-1, -1), (-1, -1), 0.25, colors.black),
                    ('FONT', (-1, -1), (-1, -1), "Helvetica-Bold", 10), 
                    
                    ('ALIGN', (-2, -1), (-2, -1), 'RIGHT'),
                    ('FONT', (-2, -1), (-2, -1), "Helvetica", 6), 
                    ])
            tableau = Table(dataTableau, largeursColonnes)
            tableau.setStyle(style)
            story.append(tableau)

            # Saut de page
            story.append(PageBreak())
        
        # Finalisation du PDF
        doc.build(story)
        
        # Ouverture du PDF
        if ouverture == True :
            FonctionsPerso.LanceFichierExterne(nomDoc)
示例#19
0
def make_invoice(fp, purchase, org, pgnum, tickets, **kw):
    """
    make pdf invoice. Should be called with the same parameters
    as the render_template with the html template.
    """
    doc = BaseDocTemplate(fp, pagesize=A4)
    styles = getSampleStyleSheet()

    args = dict(date=purchase.date[0],
                rcptaddr=[purchase.buyerName[0]],
                senderaddr=[org.name[0]],
                orgnum=org.orgnum[0],
                fskatt=org.fskatt[0],
                kind=purchase.kind[0],
                ocr=purchase.ocr[0],
                conditions='30 dagar netto',
                latefee=u'Efter förfallodatum debiteras '
                u'dröjsmålsränta enligt räntelagen.',
                total=purchase.total[0],
                pgnum=pgnum,
                styles=styles)

    qrcode = {
        'uqr': 1,
        'tp': 1,
        'nme': org.name[0],
        'cid': org.orgnum[0],
        'idt': time.strftime('%Y%m%d', time.localtime(purchase.date[0])),
        'iref': purchase.ocr[0],
        'due': str(purchase.total[0]),
        'pt': 'PG',
        'acc': pgnum[:-1] + '-' + pgnum[-1:]
    }

    if purchase.buyerAddress:
        args['rcptaddr'] += purchase.buyerAddress[0].split('\n')
    if org.address:
        args['senderaddr'] += org.address[0].split('\n')
    if org.phone:
        args['phone'] = org.phone[0]
    if org.email:
        args['email'] = org.email[0]
    if org.url:
        args['url'] = org.url[0]
    if org.seat:
        args['seat'] = org.seat[0]
    if org.vatnum:
        args['vatnum'] = org.vatnum[0]
    if purchase.buyerReference:
        args['buyerref'] = purchase.buyerReference[0]
    if purchase.buyerAnnotation:
        args['annotation'] = purchase.buyerAnnotation[0].split('\n')
    for (code, pct, value) in purchase.vat:
        qrcode[{'10': 'vh', '11': 'vm', '12': 'vl'}[code]] = str(value)
    try:
        args['expiryDate'] = purchase.expiryDate[0]
        qrcode['ddt'] = time.strftime('%Y%m%d',
                                      time.localtime(purchase.expiryDate[0]))
    except (AttributeError, IndexError):
        qrcode['ddt'] = time.strftime('%Y%m%d')

    args['qrcode'] = json.dumps(qrcode)

    tmpl = InvoiceTemplate(name='invoice', **args)
    tmpl2 = Invoice2Template(name='invoice2', **args)

    doc.addPageTemplates([tmpl, tmpl2])

    elements = [NextPageTemplate('invoice'), NextPageTemplate('invoice2')]

    indentedsmallstyle = ParagraphStyle('Small',
                                        fontName='Helvetica',
                                        fontSize=8,
                                        leading=9,
                                        leftIndent=5 * mm)
    boldstyle = ParagraphStyle('Bold',
                               fontName='Helvetica-Bold',
                               fontSize=10,
                               leading=12)
    boldrightstyle = ParagraphStyle('Bold',
                                    fontName='Helvetica-Bold',
                                    fontSize=10,
                                    leading=12,
                                    alignment=TA_RIGHT)
    mycellstyle = CellStyle('mycellstyle')
    mycellstyle.topPadding = mycellstyle.bottomPadding = 0
    tabledata = [
        Table(
            [[
                Paragraph(_('Item'), boldstyle),
                Paragraph(_('Price'), boldrightstyle),
                Paragraph(_('Quantity'), boldrightstyle),
                Paragraph(_('Total'), boldrightstyle)
            ]],
            colWidths=[115 * mm, 20 * mm, 20 * mm, 25 * mm],
            style=TableStyle([
                ('ALIGN', (1, 0), (-1, -1), 'RIGHT'),
                ('TOPPADDING', (0, 0), (-1, -1), 0),
                ('BOTTOMPADDING', (0, 0), (-1, -1), 0),
                #('BOX', (0,0), (-1, -1), 0.25, colors.black),
            ]))
    ]
    for item in purchase.items:
        celldata = [
            Table(
                [[
                    item.name[0],
                    formatters.money(item.price[0], True), item.quantity[0],
                    formatters.money(item.total[0], True)
                ]],
                colWidths=[115 * mm, 20 * mm, 20 * mm, 25 * mm],
                style=TableStyle([
                    ('ALIGN', (1, 0), (-1, -1), 'RIGHT'),
                    ('TOPPADDING', (0, 0), (-1, -1), 0),
                    ('BOTTOMPADDING', (0, 0), (-1, -1), 0),
                    #('BOX', (0,0), (-1, -1), 0.25, colors.black),
                    #('ALIGN', (0,0), (-1, 0), 'LEFT')
                ]),
            )
        ]
        if item.options:
            for opt, val in item.optionsWithValue:
                celldata.append(
                    Paragraph('%s: <i>%s</i>' % (opt, val),
                              indentedsmallstyle))
        tabledata.append(celldata)

    # Sum and VAT
    tabledata.append([
        Table(
            [[
                '',
                Paragraph(_('Total'), boldrightstyle),
                Paragraph(formatters.money(purchase.total[0], True),
                          boldrightstyle)
            ]],
            colWidths=[115 * mm, 40 * mm, 25 * mm],
            style=TableStyle([
                ('ALIGN', (1, 0), (-1, -1), 'RIGHT'),
                ('TOPPADDING', (0, 0), (-1, -1), 0),
                ('BOTTOMPADDING', (0, 0), (-1, -1), 0),
                #('BOX', (0,0), (-1, -1), 0.25, colors.black),
                #('ALIGN', (0,0), (-1, 0), 'LEFT')
            ]),
        )
    ])

    #vats = [(25, decimal.Decimal('11.37')), (12, decimal.Decimal('6.78'))]

    for code, percentage, amount in purchase.vat:
        tabledata.append([
            Table(
                [[
                    '',
                    Paragraph(
                        _('Including %s%% VAT') %
                        py3txt(formatters.vatpercentage(percentage)),
                        boldrightstyle),
                    Paragraph(formatters.money(amount, True), boldrightstyle)
                ]],
                colWidths=[115 * mm, 40 * mm, 25 * mm],
                style=TableStyle([
                    ('ALIGN', (1, 0), (-1, -1), 'RIGHT'),
                    ('TOPPADDING', (0, 0), (-1, -1), 0),
                    ('BOTTOMPADDING', (0, 0), (-1, -1), 0),
                    #('BOX', (0,0), (-1, -1), 0.25, colors.black),
                    #('ALIGN', (0,0), (-1, 0), 'LEFT')
                ]),
            )
        ])

    t = Table(
        [[t] for t in tabledata],
        colWidths=[180 * mm],
        repeatRows=1,
        style=TableStyle([
            ('LEFTPADDING', (0, 0), (0, -1), 0),
            ('RIGHTPADDING', (0, -1), (-1, -1), 0),
            #('BOX', (0,0), (-1, -1), 0.25, colors.black)
        ]))

    elements.append(t)

    extraText = purchase.extraText
    if extraText:
        textElements = []
        text_style = ParagraphStyle('Text',
                                    fontName='Helvetica',
                                    fontSize=8,
                                    leading=9)
        for text in extraText:
            textElements.append(Paragraph(text, text_style))
        elements.append(KeepTogether(textElements))

    doc.multiBuild(elements)
    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)
示例#21
0
    def __init__(self, dictValeurs={}, dictOptions={}, IDmodele=None, mode="facture", ouverture=True, nomFichier=None, titre=None):
        """ Impression """
        global DICT_VALEURS, DICT_OPTIONS
        DICT_VALEURS = dictValeurs
        DICT_OPTIONS = dictOptions
        self.mode = mode
        
        detail = 0
        if dictOptions["affichage_prestations"] != None :
            detail = dictOptions["affichage_prestations"]
        
        # Initialisation du document
        if nomFichier == None :
            nomDoc = _(u"Temp/%ss_%s.pdf") % (mode, FonctionsPerso.GenerationIDdoc())
        else :
            nomDoc = nomFichier
        doc = BaseDocTemplate(nomDoc, pagesize=TAILLE_PAGE, showBoundary=False)
        
        # Mémorise le ID du modèle
        modeleDoc = DLG_Noedoc.ModeleDoc(IDmodele=IDmodele)
        doc.modeleDoc = modeleDoc

        # Vérifie qu'un cadre principal existe bien dans le document
        if doc.modeleDoc.FindObjet("cadre_principal") == None :
            raise Exception("Votre modèle de document doit obligatoirement comporter un cadre principal. Retournez dans l'éditeur de document et utilisez pour votre modèle la commande 'Insérer un objet spécial > Insérer le cadre principal'.")
        
        # Importe le template de la première page
        doc.addPageTemplates(MyPageTemplate(pageSize=TAILLE_PAGE, doc=doc))
        
        story = []
        styleSheet = getSampleStyleSheet()
        h3 = styleSheet['Heading3']
        styleTexte = styleSheet['BodyText'] 
        styleTexte.fontName = "Helvetica"
        styleTexte.fontSize = 9
        styleTexte.borderPadding = 9
        styleTexte.leading = 12
        
##        # Définit le template des pages suivantes
##        story.append(NextPageTemplate("suivante"))
        
        
        # ----------- Insertion du contenu des frames --------------
        listeNomsSansCivilite = []
        for IDcompte_payeur, dictValeur in dictValeurs.iteritems() :
            listeNomsSansCivilite.append((dictValeur["nomSansCivilite"], IDcompte_payeur))
        listeNomsSansCivilite.sort() 
        
        for nomSansCivilite, IDcompte_payeur in listeNomsSansCivilite :
            dictValeur = dictValeurs[IDcompte_payeur]
            if dictValeur["select"] == True :
                
                story.append(DocAssign("IDcompte_payeur", IDcompte_payeur))
                nomSansCivilite = dictValeur["nomSansCivilite"]
                story.append(Bookmark(nomSansCivilite, str(IDcompte_payeur)))
                
                # ------------------- TITRE -----------------
                if dictOptions["afficher_titre"] == True :
                    if titre == None :
                        if mode == "facture" : titre = _(u"Facture")
                        if mode == "attestation" : titre = _(u"Attestation de présence")
                        if dictValeur.has_key("texte_titre") : 
                            titre = dictValeur["texte_titre"]
                    dataTableau = []
                    largeursColonnes = [ CADRE_CONTENU[2], ]
                    dataTableau.append((titre,))
                    texteDateDebut = DateEngFr(str(dictValeur["date_debut"]))
                    texteDateFin = DateEngFr(str(dictValeur["date_fin"]))
                    if dictOptions["afficher_periode"] == True :
                        dataTableau.append((_(u"Période du %s au %s") % (texteDateDebut, texteDateFin),))
                    styles = [
                            ('VALIGN', (0,0), (-1,-1), 'MIDDLE'), 
                            ('FONT',(0,0),(0,0), "Helvetica-Bold", dictOptions["taille_texte_titre"]), 
                            ('LINEBELOW', (0,0), (0,0), 0.25, colors.black), 
                            ('ALIGN', (0,0), (-1,-1), 'LEFT'), 
                            ]
                    
                    if dictOptions["afficher_periode"] == True :
                        styles.append(('FONT',(0,1),(0,1), "Helvetica", dictOptions["taille_texte_periode"]))
                    tableau = Table(dataTableau, largeursColonnes)
                    tableau.setStyle(TableStyle(styles))
                    story.append(tableau)
                    story.append(Spacer(0,20))
                
                # TEXTE D'INTRODUCTION pour Attestation
##                if mode == "attestation" and dictValeur["intro"] != None :
##                    texteIntro = dictValeur["intro"]
##                    paraStyle = ParagraphStyle(name="intro",
##                                          fontName="Helvetica",
##                                          fontSize=9,
##                                          leading=14,
##                                          spaceBefore=0,
##                                          spaceafter=0,
##                                          leftIndent=20,
##                                          rightIndent=20,
##                                          alignment=1,
##                                        )
##                    story.append(Paragraph(u"<i>%s</i>" % texteIntro, paraStyle))
##                    story.append(Spacer(0,20))

                if dictOptions["texte_introduction"] != "" :
                    paraStyle = ParagraphStyle(name="introduction",
                                          fontName="Helvetica",
                                          fontSize=dictOptions["taille_texte_introduction"],
                                          leading=14,
                                          spaceBefore=0,
                                          spaceafter=0,
                                          leftIndent=5,
                                          rightIndent=5,
                                          alignment=dictOptions["alignement_texte_introduction"],
                                          backColor=ConvertCouleurWXpourPDF(dictOptions["couleur_fond_introduction"]),
                                          borderColor=ConvertCouleurWXpourPDF(dictOptions["couleur_bord_introduction"]),
                                          borderWidth=0.5,
                                          borderPadding=5,
                                        )
                    texte = dictValeur["texte_introduction"].replace("\\n", "<br/>")
                    if dictOptions["style_texte_introduction"] == 0 : texte = u"<para>%s</para>" % texte
                    if dictOptions["style_texte_introduction"] == 1 : texte = u"<para><i>%s</i></para>" % texte
                    if dictOptions["style_texte_introduction"] == 2 : texte = u"<para><b>%s</b></para>" % texte
                    if dictOptions["style_texte_introduction"] == 3 : texte = u"<para><i><b>%s</b></i></para>" % texte
                    story.append(Paragraph(texte, paraStyle))
                    story.append(Spacer(0,20))

                    
                couleurFond = ConvertCouleurWXpourPDF(dictOptions["couleur_fond_1"]) # (0.8, 0.8, 1)
                couleurFondActivite = ConvertCouleurWXpourPDF(dictOptions["couleur_fond_2"]) # (0.92, 0.92, 1)

                # ------------------- TABLEAU CONTENU -----------------
                montantPeriode = FloatToDecimal(0.0)
                montantVentilation = FloatToDecimal(0.0)

                # Recherche si TVA utilisée
                activeTVA = False
                for IDindividu, dictIndividus in dictValeur["individus"].iteritems() :
                    for IDactivite, dictActivites in dictIndividus["activites"].iteritems() :
                        for date, dictDates in dictActivites["presences"].iteritems() :
                            for dictPrestation in dictDates["unites"] :
                                if dictPrestation["tva"] != None and dictPrestation["tva"] != 0.0 :
                                    activeTVA = True

                # Remplissage
                for IDindividu, dictIndividus in dictValeur["individus"].iteritems() :
                    
                    if dictIndividus["select"] == True :
                        
                        listeIndexActivites = []
                        montantPeriode += dictIndividus["total"]
                        montantVentilation += dictIndividus["ventilation"]
                        
                        # Initialisation des largeurs de tableau
                        largeurColonneDate = dictOptions["largeur_colonne_date"]
                        largeurColonneMontantHT = dictOptions["largeur_colonne_montant_ht"]
                        largeurColonneTVA = dictOptions["largeur_colonne_montant_tva"]
                        largeurColonneMontantTTC = dictOptions["largeur_colonne_montant_ttc"]
                        largeurColonneBaseTTC = largeurColonneMontantTTC
                        
                        if activeTVA == True and detail == 0 :
                            largeurColonneIntitule = CADRE_CONTENU[2] - largeurColonneDate - largeurColonneMontantHT - largeurColonneTVA - largeurColonneMontantTTC
                            largeursColonnes = [ largeurColonneDate, largeurColonneIntitule, largeurColonneMontantHT, largeurColonneTVA, largeurColonneMontantTTC]
                        else :
                            if detail != 0 :
                                largeurColonneIntitule = CADRE_CONTENU[2] - largeurColonneDate - largeurColonneBaseTTC - largeurColonneMontantTTC
                                largeursColonnes = [ largeurColonneDate, largeurColonneIntitule, largeurColonneBaseTTC, largeurColonneMontantTTC]
                            else :
                                largeurColonneIntitule = CADRE_CONTENU[2] - largeurColonneDate - largeurColonneMontantTTC
                                largeursColonnes = [ largeurColonneDate, largeurColonneIntitule, largeurColonneMontantTTC]
                        
                        # Insertion du nom de l'individu
                        paraStyle = ParagraphStyle(name="individu",
                                              fontName="Helvetica",
                                              fontSize=dictOptions["taille_texte_individu"],
                                              leading=dictOptions["taille_texte_individu"],
                                              spaceBefore=0,
                                              spaceafter=0,
                                            )
                        texteIndividu = Paragraph(dictIndividus["texte"], paraStyle)
                        dataTableau = []
                        dataTableau.append([texteIndividu,])
                        tableau = Table(dataTableau, [CADRE_CONTENU[2],])
                        listeStyles = [
                                ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                                ('FONT', (0, 0), (-1, -1), "Helvetica", dictOptions["taille_texte_individu"]), 
                                ('GRID', (0, 0), (-1, -1), 0.25, colors.black),
                                ('BACKGROUND', (0, 0), (-1, 0), couleurFond),
                                ]
                        tableau.setStyle(TableStyle(listeStyles))
                        story.append(tableau)
                        
                        # Insertion du nom de l'activité
                        for IDactivite, dictActivites in dictIndividus["activites"].iteritems() :
                            texteActivite = dictActivites["texte"]
                            if texteActivite != None :
                                dataTableau = []
                                dataTableau.append([texteActivite,])
                                tableau = Table(dataTableau, [CADRE_CONTENU[2],])
                                listeStyles = [
                                    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                                    ('FONT', (0, 0), (-1, -1), "Helvetica", dictOptions["taille_texte_activite"]),
                                    ('GRID', (0, 0), (-1, -1), 0.25, colors.black),
                                    ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
                                    ('BACKGROUND', (0, 0), (-1, 0), couleurFondActivite),
                                    ]
                                tableau.setStyle(TableStyle(listeStyles))
                                story.append(tableau)

                            # Style de paragraphe normal
                            paraStyle = ParagraphStyle(name="prestation",
                                          fontName="Helvetica",
                                          fontSize=dictOptions["taille_texte_prestation"],
                                          leading=dictOptions["taille_texte_prestation"],
                                          spaceBefore=0,
                                          spaceAfter=0,
                                          )

                            paraLabelsColonnes = ParagraphStyle(name="paraLabelsColonnes",
                                          fontName="Helvetica",
                                          fontSize=dictOptions["taille_texte_noms_colonnes"],
                                          leading=dictOptions["taille_texte_noms_colonnes"],
                                          spaceBefore=0,
                                          spaceAfter=0,
                                          )
                                

                            if detail != 0 :
                                
                                # -------------- MODE REGROUPE ----------------
                                
                                # Regroupement par prestations identiques
                                dictRegroupement = {}
                                for date, dictDates in dictActivites["presences"].iteritems() :
                                    total = dictDates["total"]
                                    for dictPrestation in dictDates["unites"] :
                                        label = dictPrestation["label"]
                                        listeDatesUnite = GetDatesListes(dictPrestation["listeDatesConso"])
                                        montant = dictPrestation["montant"]
                                        deductions = dictPrestation["deductions"]
                                        tva = dictPrestation["tva"]
                                        
                                        if detail == 1 : labelkey = label
                                        if detail == 2 : labelkey = label + " P.U. " + "%.2f %s" % (montant, SYMBOLE)
                                            
                                        if dictRegroupement.has_key(labelkey) == False :
                                            dictRegroupement[labelkey] = {"labelpresta" : label, "total" : 0, "nbre" : 0, "base" : 0, "dates_forfait" : None}
                                            dictRegroupement[labelkey]["base"] = montant
                                        
                                        dictRegroupement[labelkey]["total"] += montant
                                        dictRegroupement[labelkey]["nbre"] += 1
                                        
                                        if detail == 1 :
                                            dictRegroupement[labelkey]["base"] = dictRegroupement[labelkey]["total"] / dictRegroupement[labelkey]["nbre"]
 
                                        if len(listeDatesUnite) > 1 :
                                            listeDatesUnite.sort()
                                            date_debut = listeDatesUnite[0]
                                            date_fin = listeDatesUnite[-1]
                                            nbreDates = len(listeDatesUnite)
                                            dictRegroupement[labelkey]["dates_forfait"] = _(u"<BR/><font size=5>Du %s au %s soit %d jours</font>") % (DateEngFr(str(date_debut)), DateEngFr(str(date_fin)), nbreDates)
        
                                # Insertion des prestations regroupées
                                listeLabels = dictRegroupement.keys() 
                                listeLabels.sort() 

                                dataTableau = [(
                                    Paragraph(_(u"<para align='center'>Quantité</para>"), paraLabelsColonnes), 
                                    Paragraph(_(u"<para align='center'>Prestation</para>"), paraLabelsColonnes),
                                    Paragraph(_(u"<para align='center'>Base</para>"), paraLabelsColonnes),
                                    Paragraph(_(u"<para align='center'>Montant</para>"), paraLabelsColonnes), 
                                    ),]

                                for labelkey in listeLabels :
                                    label = dictRegroupement[labelkey]["labelpresta"]
                                    nbre = dictRegroupement[labelkey]["nbre"]
                                    total = dictRegroupement[labelkey]["total"]
                                    base = dictRegroupement[labelkey]["base"]

                                    # recherche d'un commentaire
                                    if dictOptions.has_key("dictCommentaires") :
                                        key = (label, IDactivite)
                                        if dictOptions["dictCommentaires"].has_key(key) :
                                            commentaire = dictOptions["dictCommentaires"][key]
                                            label = "%s <i><font color='#939393'>%s</font></i>" % (label, commentaire)
                                            
                                    # Formatage du label
                                    intitule = Paragraph(label, paraStyle)
                                    
                                    # Rajout des dates de forfait
                                    #dates_forfait = dictRegroupement[label]["dates_forfait"]
                                    #if dates_forfait != None :
                                    #    intitule = [intitule, Paragraph(dates_forfait, paraStyle)]

                                    dataTableau.append([Paragraph(u"<para align='center'>%d</para>" % nbre, paraStyle), intitule, Paragraph(u"<para align='center'>%.02f %s</para>" % (base, SYMBOLE), paraStyle), Paragraph(u"<para align='center'>%.02f %s</para>" % (total, SYMBOLE), paraStyle)])
 
                            else :
                                
                                # -------------------------------------------------------------- MODE DETAILLE ------------------------------------------------------------------


                                # Insertion de la date
                                listeDates = []
                                for date, dictDates in dictActivites["presences"].iteritems() :
                                    listeDates.append(date)
                                listeDates.sort() 
                                
                                paraStyle = ParagraphStyle(name="prestation",
                                              fontName="Helvetica",
                                              fontSize=dictOptions["taille_texte_prestation"],
                                              leading=dictOptions["taille_texte_prestation"],
                                              spaceBefore=0,
                                              spaceAfter=0,
                                              )

                                dataTableau = []

                                if activeTVA == True :
                                    dataTableau.append([
                                        Paragraph(_(u"<para align='center'>Date</para>"), paraLabelsColonnes), 
                                        Paragraph(_(u"<para align='center'>Prestation</para>"), paraLabelsColonnes), 
                                        Paragraph(_(u"<para align='center'>Montant HT</para>"), paraLabelsColonnes), 
                                        Paragraph(_(u"<para align='center'>Taux TVA</para>"), paraLabelsColonnes), 
                                        Paragraph(_(u"<para align='center'>Montant TTC</para>"), paraLabelsColonnes), 
                                        ])

                                for date in listeDates :
                                    dictDates = dictActivites["presences"][date]
                                    
                                    date = dictDates["texte"]
                                    prestations = dictDates["unites"]
                                    
                                    # Insertion des unités de présence
                                    listeIntitules = []
                                    listeMontantsHT = []
                                    listeTVA = []
                                    listeMontantsTTC = []
                                    texteIntitules = u""
                                    texteMontantsHT = u""
                                    texteTVA = u""
                                    texteMontantsTTC = u""
                                    
                                    for dictPrestation in prestations :
                                        label = dictPrestation["label"]
                                        listeDatesUnite = GetDatesListes(dictPrestation["listeDatesConso"])
                                        montant_initial = dictPrestation["montant_initial"]
                                        montant = dictPrestation["montant"]
                                        deductions = dictPrestation["deductions"]
                                        tva = dictPrestation["tva"]

                                        # Date
                                        texteDate = Paragraph("<para align='center'>%s</para>" % date, paraStyle)
                                        
                                        # recherche d'un commentaire
                                        if dictOptions.has_key("dictCommentaires") :
                                            key = (label, IDactivite)
                                            if dictOptions["dictCommentaires"].has_key(key) :
                                                commentaire = dictOptions["dictCommentaires"][key]
                                                label = "%s <i><font color='#939393'>%s</font></i>" % (label, commentaire)

                                        # Affiche le Label de la prestation
                                        listeIntitules.append(Paragraph(label, paraStyle)) 
                                        
                                        # Recherche si c'est un forfait
                                        if len(listeDatesUnite) > 1 :
                                            listeDatesUnite.sort()
                                            date_debut = listeDatesUnite[0]
                                            date_fin = listeDatesUnite[-1]
                                            nbreDates = len(listeDatesUnite)
                                            label = _(u"<BR/><font size=5>Du %s au %s soit %d jours</font>") % (DateEngFr(str(date_debut)), DateEngFr(str(date_fin)), nbreDates)
                                            listeIntitules.append(Paragraph(label, paraStyle)) 
                                                                                
                                        # TVA
                                        if activeTVA == True :
                                            if tva == None : tva = 0.0
                                            montantHT = (100.0 * float(montant)) / (100 + float(tva)) #montant - montant * 1.0 * float(tva) / 100
                                            listeMontantsHT.append(Paragraph(u"<para align='center'>%.02f %s</para>" % (montantHT, SYMBOLE), paraStyle))
                                            listeTVA.append(Paragraph(u"<para align='center'>%.02f %%</para>" % tva, paraStyle))
                                        else :
                                            listeMontantsHT.append("")
                                            listeTVA.append("")
                                            
                                        # Affiche total
                                        listeMontantsTTC.append(Paragraph(u"<para align='center'>%.02f %s</para>" % (montant, SYMBOLE), paraStyle)) 
                                    
                                        # Déductions
                                        if len(deductions) > 0 :
                                            for dictDeduction in deductions :
                                                listeIntitules.append(Paragraph(u"<para align='left'><font size=5 color='#939393'>- %.02f %s : %s</font></para>" % (dictDeduction["montant"], SYMBOLE, dictDeduction["label"]), paraStyle))
                                                #listeIntitules.append(Paragraph(u"<para align='left'><font size=5 color='#939393'>%s</font></para>" % dictDeduction["label"], paraStyle))
                                                listeMontantsHT.append(Paragraph("&nbsp;", paraStyle))
                                                listeTVA.append(Paragraph("&nbsp;", paraStyle))
                                                listeMontantsTTC.append(Paragraph("&nbsp;", paraStyle))
                                                #listeMontantsTTC.append(Paragraph(u"<para align='center'><font size=5 color='#939393'>- %.02f %s</font></para>" % (dictDeduction["montant"], SYMBOLE), paraStyle)) 
                                                
                                        
                                    if len(listeIntitules) == 1 :
                                        texteIntitules = listeIntitules[0]
                                        texteMontantsHT = listeMontantsHT[0]
                                        texteTVA = listeTVA[0]
                                        texteMontantsTTC = listeMontantsTTC[0]
                                    if len(listeIntitules) > 1 :
                                        texteIntitules = listeIntitules
                                        texteMontantsHT = listeMontantsHT
                                        texteTVA = listeTVA
                                        texteMontantsTTC = listeMontantsTTC
                                                                        
                                    if activeTVA == True :
                                        dataTableau.append([texteDate, texteIntitules, texteMontantsHT, texteTVA, texteMontantsTTC])
                                    else :
                                        dataTableau.append([texteDate, texteIntitules, texteMontantsTTC])
                                    
                            # Style du tableau des prestations
                            tableau = Table(dataTableau, largeursColonnes)
                            listeStyles = [
                                ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                                ('FONT', (0, 0), (-1, -1), "Helvetica", dictOptions["taille_texte_prestation"]), 
                                ('GRID', (0, 0), (-1,-1), 0.25, colors.black), 
                                ('ALIGN', (0, 0), (-1, -1), 'CENTRE'),
                                ('ALIGN', (1, 0), (1, -1), 'LEFT'),
                                ('TOPPADDING', (0, 0), (-1, -1), 1), 
                                ('BOTTOMPADDING', (0, 0), (-1, -1), 3), 
                                ]
                            tableau.setStyle(TableStyle(listeStyles))
                            story.append(tableau)
                        
                        # Insertion des totaux
                        dataTableau = []
                        if activeTVA == True and detail == 0 :
                            dataTableau.append(["", "", "", "", Paragraph("<para align='center'>%.02f %s</para>" % (dictIndividus["total"], SYMBOLE) , paraStyle)])
                        else :
                            if detail != 0 :
                                dataTableau.append(["", "", "", Paragraph("<para align='center'>%.02f %s</para>" % (dictIndividus["total"], SYMBOLE) , paraStyle)])
                            else :
                                dataTableau.append(["", "", Paragraph("<para align='center'>%.02f %s</para>" % (dictIndividus["total"], SYMBOLE) , paraStyle)])
                        
                        listeStyles = [
                                ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                                ('FONT', (0, 0), (-1, -1), "Helvetica", dictOptions["taille_texte_prestation"]), 
                                ('GRID', (-1, -1), (-1,-1), 0.25, colors.black), 
                                ('ALIGN', (-1, -1), (-1, -1), 'CENTRE'),
                                ('BACKGROUND', (-1, -1), (-1, -1), couleurFond), 
                                ('TOPPADDING', (0, 0), (-1, -1), 1), 
                                ('BOTTOMPADDING', (0, 0), (-1, -1), 3), 
                                ]
                            
                        # Création du tableau
                        tableau = Table(dataTableau, largeursColonnes)
                        tableau.setStyle(TableStyle(listeStyles))
                        story.append(tableau)
                        story.append(Spacer(0, 10))
                
                # Intégration des messages, des reports et des qf
                listeMessages = []
                paraStyle = ParagraphStyle(name="message",
                                          fontName="Helvetica",
                                          fontSize=dictOptions["taille_texte_messages"],
                                          leading=dictOptions["taille_texte_messages"],
                                          #spaceBefore=0,
                                          spaceAfter=2,
                                        )
                
                # Date d'échéance
##                if dictOptions["echeance"] != None :
##                    listeMessages.append(Paragraph(dictOptions["echeance"], paraStyle))

               # QF aux dates de facture
                if mode == "facture" and dictOptions["afficher_qf_dates"] == True :
                    dictQfdates = dictValeur["qfdates"]
                    listeDates = dictQfdates.keys() 
                    listeDates.sort() 
                    if len(listeDates) > 0 :
                        for dates in listeDates :
                            texteQf = _(u"--- Votre QF %s : <b>%s</b> ---") % (dates, dictQfdates[dates])
                            listeMessages.append(Paragraph(texteQf, paraStyle))
                
                
                # Reports
                if mode == "facture" and dictOptions["afficher_impayes"] == True :
                    dictReports = dictValeur["reports"]
                    listePeriodes = dictReports.keys() 
                    listePeriodes.sort() 
                    if len(listePeriodes) > 0 :
                        texteReport = _(u"<b>Impayés : </b>Merci de bien vouloir nous retourner également le règlement des prestations antérieures : ")
                        for periode in listePeriodes :
                            annee, mois = periode
                            nomPeriode = PeriodeComplete(mois, annee)
                            montant_impaye = dictReports[periode]
                            texteReport += u"%s (%.02f %s), " % (nomPeriode, montant_impaye, SYMBOLE)
                        texteReport = texteReport[:-2] + u"."
                        listeMessages.append(Paragraph(texteReport, paraStyle))
                
                # Messages
                if mode == "facture" :
                    if dictOptions["afficher_messages"] == True :
                        for message in dictOptions["messages"] :
                            listeMessages.append(Paragraph(message, paraStyle))
                        
                        for message_familial in dictValeur["messages_familiaux"] :
                            texte = message_familial["texte"]
                            if len(texte) > 0 and texte[-1] not in ".!?" : 
                                texte = texte + u"."
                            texte = _(u"<b>Message : </b>%s") % texte
                            listeMessages.append(Paragraph(texte, paraStyle))
                            
                if len(listeMessages) > 0 :
                    listeMessages.insert(0, Paragraph(_(u"<u>Informations :</u>"), paraStyle))
                
                # ------------------ CADRE TOTAUX ------------------------
                dataTableau = []
                largeurColonneLabel = 110
                largeursColonnes = [ CADRE_CONTENU[2] - largeurColonneMontantTTC - largeurColonneLabel, largeurColonneLabel, largeurColonneMontantTTC]

                dataTableau.append((listeMessages, _(u"TOTAL période:"), u"%.02f %s" % (dictValeur["total"], SYMBOLE)))
                dataTableau.append(("", _(u"Montant déjà réglé :"), u"%.02f %s" % (dictValeur["ventilation"], SYMBOLE)))
                dataTableau.append(("", _(u"Reste à régler :"), u"%.02f %s" % (dictValeur["solde"], SYMBOLE) ))

                style = [
                        ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), 
                        ('FONT', (1, 0), (1, -1), "Helvetica-Bold", dictOptions["taille_texte_labels_totaux"]), 
                        ('FONT', (2, 0), (2, -1), "Helvetica-Bold", dictOptions["taille_texte_montants_totaux"]), 
                        
                        ('GRID', (2, 0), (2, 0), 0.25, colors.black),
                        ('GRID', (2, 1), (2, 1), 0.25, colors.black),
                        ('GRID', (2, 2), (2, 2), 0.25, colors.black),
                        
                        ('ALIGN', (1, 0), (1, -1), 'RIGHT'),
                        ('ALIGN', (2, 0), (2, -1), 'CENTRE'), 
                        ('BACKGROUND', (2, 2), (2, 2), couleurFond),
                        
                        ('SPAN', (0, 0), (0, -1)), 
                        ]
                
                if mode == "facture" and len(listeMessages) > 0 :
                    #style.append( ('BACKGROUND', (0, 0), (0, 0), couleurFondActivite) )
                    style.append( ('FONT', (0, 0), (0, -1), "Helvetica", 8)  )
                    style.append( ('VALIGN', (0, 0), (0, -1), 'TOP') )
                    
                tableau = Table(dataTableau, largeursColonnes, rowHeights=[18, 18, None])
                tableau.setStyle(TableStyle(style))
                story.append(tableau)
                
                # ------------------------- PRELEVEMENTS --------------------
                if dictOptions.has_key("afficher_avis_prelevements") and dictValeur.has_key("prelevement") :
                    if dictValeur["prelevement"] != None and dictOptions["afficher_avis_prelevements"] == True :
                        paraStyle = ParagraphStyle(name="intro",
                              fontName="Helvetica",
                              fontSize=8,
                              leading=11,
                              spaceBefore=2,
                              spaceafter=2,
                              alignment=1,
                              backColor=couleurFondActivite,
                            )
                        story.append(Spacer(0,20))
                        story.append(Paragraph(u"<para align='center'><i>%s</i></para>" % dictValeur["prelevement"], paraStyle))
                
                # Texte conclusion
                if dictOptions["texte_conclusion"] != "" :
                    story.append(Spacer(0,20))
                    paraStyle = ParagraphStyle(name="conclusion",
                                          fontName="Helvetica",
                                          fontSize=dictOptions["taille_texte_conclusion"],
                                          leading=14,
                                          spaceBefore=0,
                                          spaceafter=0,
                                          leftIndent=5,
                                          rightIndent=5,
                                          alignment=dictOptions["alignement_texte_conclusion"],
                                          backColor=ConvertCouleurWXpourPDF(dictOptions["couleur_fond_conclusion"]),
                                          borderColor=ConvertCouleurWXpourPDF(dictOptions["couleur_bord_conclusion"]),
                                          borderWidth=0.5,
                                          borderPadding=5,
                                        )
            
                    texte = dictValeur["texte_conclusion"].replace("\\n", "<br/>")
                    if dictOptions["style_texte_conclusion"] == 0 : texte = u"<para>%s</para>" % texte
                    if dictOptions["style_texte_conclusion"] == 1 : texte = u"<para><i>%s</i></para>" % texte
                    if dictOptions["style_texte_conclusion"] == 2 : texte = u"<para><b>%s</b></para>" % texte
                    if dictOptions["style_texte_conclusion"] == 3 : texte = u"<para><i><b>%s</b></i></para>" % texte
                    story.append(Paragraph(texte, paraStyle))
                    
                # Image signature
                if dictOptions["image_signature"] != "" :
                    cheminImage = dictOptions["image_signature"]
                    if os.path.isfile(cheminImage) :
                        img = Image(cheminImage)
                        largeur, hauteur = int(img.drawWidth * 1.0 * dictOptions["taille_image_signature"] / 100.0), int(img.drawHeight * 1.0 * dictOptions["taille_image_signature"] / 100.0)
                        if largeur > CADRE_CONTENU[2] or hauteur > CADRE_CONTENU[3] :
                            raise Exception(_(u"L'image de signature est trop grande. Veuillez diminuer sa taille avec le parametre Taille."))
                        img.drawWidth, img.drawHeight = largeur, hauteur
                        if dictOptions["alignement_image_signature"] == 0 : img.hAlign = "LEFT"
                        if dictOptions["alignement_image_signature"] == 1 : img.hAlign = "CENTER"
                        if dictOptions["alignement_image_signature"] == 2 : img.hAlign = "RIGHT"
                        story.append(Spacer(0,20))
                        story.append(img)
                        


                # Saut de page
                story.append(PageBreak())

        # Finalisation du PDF
##        try :
        doc.build(story)
##        except Exception, err :
##            print "Erreur dans ouverture PDF :", err
##            if "Permission denied" in err :
##                dlg = wx.MessageDialog(None, _(u"Noethys ne peut pas créer le PDF.\n\nVeuillez vérifier qu'un autre PDF n'est pas déjà ouvert en arrière-plan..."), _(u"Erreur d'édition"), wx.OK | wx.ICON_ERROR)
##                dlg.ShowModal()
##                dlg.Destroy()
##                return
        
        # Ouverture du PDF
        if ouverture == True :
            FonctionsPerso.LanceFichierExterne(nomDoc)
示例#22
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) ) )
        if DICT_VALEURS["date_differe"] not in ("", None): dataTableau.append((_(u"Encaissement différé :"), Paragraph(_(u"A partir du %s") % DICT_VALEURS["{DATE_DIFFERE}"], paraStyle)))
        
        style = TableStyle([
                ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), 
                ('FONT', (0, 0), (0, -1), "Helvetica", 9), 
                ('FONT', (1, 0), (1, -1), "Helvetica-Bold", 9), 
                ('GRID', (0, 0), (-1, -1), 0.25, colors.black),
                ('ALIGN', (0, 1), (0, -1), 'RIGHT'),
                ('ALIGN', (1, 1), (1, -1), 'LEFT'), 
                
                ('FONT', (0, 0), (0, 0), "Helvetica", 7), 
                ('SPAN', (0, 0), (-1, 0)), 
                ('BACKGROUND', (0, 0), (-1, 0), couleurFond),
                
                ])
        tableau = Table(dataTableau, largeursColonnes)
        tableau.setStyle(style)
        story.append(tableau)
        
        # --------------------- LISTE DES PRESTATIONS ----------------
        listePrestations = dictValeurs["prestations"]
        if len(listePrestations) > 0 :
            
            story.append(Spacer(0,20))
            textePrestations = _(u"En paiement des prestations suivantes :")
            story.append(Paragraph(u"<i>%s</i>" % textePrestations, paraStyleIntro))
            story.append(Spacer(0,20))

            dataTableau = [(_(u"Date"), _(u"Activité"), _(u"Individu"), _(u"Intitulé"), _(u"Part utilisée")),]
            largeursColonnes = [50, 95, 70, 135, 50]

            paraStyle = ParagraphStyle(name="detail",
                                      fontName="Helvetica",
                                      fontSize=7,
                                      leading=7,
                                      spaceBefore=0,
                                      spaceAfter=0,
                                      )

            for dictPrestation in listePrestations :
                date = UTILS_Dates.DateDDEnFr(dictPrestation["date"])
                activite = dictPrestation["nomActivite"]
                individu = dictPrestation["prenomIndividu"]
                label = dictPrestation["label"]
                montant = dictPrestation["montant"]
                ventilation = dictPrestation["ventilation"]
                
                dataTableau.append((
                    Paragraph(u"<para align='center'>%s</para>"% date, paraStyle), 
                    Paragraph(activite, paraStyle),  
                    Paragraph(individu, paraStyle),  
                    Paragraph(label, paraStyle), 
                    Paragraph(u"<para align='right'>%.2f %s</para>" % (ventilation, SYMBOLE), paraStyle), 
                    ))
                        
            style = TableStyle([
                    ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'), 
                    ('GRID', (0, 0), (-1, -1), 0.25, colors.black),
                    ('FONT', (0, 0), (-1, -1), "Helvetica", 7), 

                    ('TOPPADDING', (0, 1), (-1, -1), 1), 
                    ('BOTTOMPADDING', (0, 1), (-1, -1), 3), 
        
                    # Ligne Entetes
                    ('FONT', (0, 0), (-1, 0), "Helvetica", 7), 
                    ('BACKGROUND', (0, 0), (-1, 0), couleurFond),
                    ('ALIGN', (0, 0), (-1, 0), 'CENTER'),
                    
                    ])
            tableau = Table(dataTableau, largeursColonnes)
            tableau.setStyle(style)
            story.append(tableau)

        
        # Enregistrement et ouverture du PDF
        try :
            doc.build(story)
        except Exception, err :
            print "Erreur dans ouverture PDF :", err
            if "Permission denied" in err :
                dlg = wx.MessageDialog(None, _(u"Noethys ne peut pas créer le PDF.\n\nVeuillez vérifier qu'un autre PDF n'est pas déjà ouvert en arrière-plan..."), _(u"Erreur d'édition"), wx.OK | wx.ICON_ERROR)
                dlg.ShowModal()
                dlg.Destroy()
                return
示例#23
0
    cropMarks=None,
    enforceColorSpace=None,
    displayDocTitle=None,
    lang=None,
    initialFontName=None,
    initialFontSize=None,
    initialLeading=None,
    cropBox=None,
    artBox=None,
    trimBox=None,
    bleedBox=None,
    # keepTogetherClass= KeepTogether
)

# add pages design to document from this metod or when create a document
document.addPageTemplates(page_design_one)
document.addPageTemplates(page_design_two)

# -------------------------------------
# BEGIN TO ADD CONTENT
# when to add content at document, is
# similar to write a story step by step
# and you should use a list of flowables
# that help to write it.
# -------------------------------------

# list of flowables that represent the content of document
content = []

# add the first flowable called Paragraph, that allow write text
content.append(
    def __init__(self, dictValeurs={}, dictOptions={}, IDmodele=None, ouverture=True, nomFichier=None):
        """ Impression """
        global DICT_VALEURS, DICT_OPTIONS
        DICT_VALEURS = dictValeurs
        DICT_OPTIONS = dictOptions

        # Initialisation du document
        if nomFichier == None:
            nomDoc = FonctionsPerso.GenerationNomDoc("INSCRIPTIONS", "pdf")
        else:
            nomDoc = nomFichier
        doc = BaseDocTemplate(nomDoc, pagesize=TAILLE_PAGE, showBoundary=False)

        # Mémorise le ID du modèle
        modeleDoc = DLG_Noedoc.ModeleDoc(IDmodele=IDmodele)
        doc.modeleDoc = modeleDoc

        # Importe le template de la première page
        doc.addPageTemplates(MyPageTemplate(pageSize=TAILLE_PAGE, doc=doc))

        story = []
        styleSheet = getSampleStyleSheet()
        h3 = styleSheet['Heading3']
        styleTexte = styleSheet['BodyText']
        styleTexte.fontName = "Helvetica"
        styleTexte.fontSize = 9
        styleTexte.borderPadding = 9
        styleTexte.leading = 12

        # ----------- Insertion du contenu des frames --------------
        listeLabels = []
        for IDinscription, dictValeur in dictValeurs.iteritems():
            listeLabels.append((dictValeur["{FAMILLE_NOM}"], IDinscription))
        listeLabels.sort()

        for labelDoc, IDinscription in listeLabels:
            dictValeur = dictValeurs[IDinscription]
            if dictValeur["select"] == True:
                story.append(DocAssign("IDinscription", IDinscription))
                nomSansCivilite = dictValeur["{FAMILLE_NOM}"]
                story.append(Bookmark(nomSansCivilite, str(IDinscription)))

                # ----------- Insertion du cadre principal --------------
                cadre_principal = doc.modeleDoc.FindObjet("cadre_principal")
                if cadre_principal != None:

                    if DICT_OPTIONS.has_key("intro") and DICT_OPTIONS["intro"] != None or DICT_OPTIONS.has_key("tableau" ) and DICT_VALEURS["tableau"] == True:
                        # ------------------- TITRE -----------------
                        dataTableau = []
                        largeursColonnes = [TAILLE_CADRE_CONTENU[2], ]
                        dataTableau.append((_(u"Confirmation d'inscription"),))
                        dataTableau.append((u"",))
                        style = TableStyle([
                            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                            ('FONT', (0, 0), (0, 0), "Helvetica-Bold", 19),
                            ('FONT', (0, 1), (0, 1), "Helvetica", 8),
                            ('LINEBELOW', (0, 0), (0, 0), 0.25, colors.black),
                            ('ALIGN', (0, 0), (-1, -1), 'LEFT'),
                        ])
                        tableau = Table(dataTableau, largeursColonnes)
                        tableau.setStyle(style)
                        story.append(tableau)
                        story.append(Spacer(0, 10))

                        # TEXTE D'INTRODUCTION
                        paraStyleIntro = ParagraphStyle(name="intro",
                                                        fontName="Helvetica",
                                                        fontSize=11,
                                                        leading=14,
                                                        spaceBefore=0,
                                                        spaceafter=0,
                                                        leftIndent=0,
                                                        rightIndent=0,
                                                        alignment=0,
                                                        )

                    if DICT_OPTIONS.has_key("intro") and DICT_OPTIONS["intro"] != None:
                        texteIntro = DICT_VALEURS["intro"]
                        story.append(Paragraph(u"<i>%s</i>" % texteIntro, paraStyleIntro))
                        story.append(Spacer(0, 20))

                    if DICT_OPTIONS.has_key("tableau") and DICT_OPTIONS["tableau"] == True:
                        # ------------------- TABLEAU CONTENU -----------------
                        dataTableau = []
                        largeursColonnes = [80, 280]
                        paraStyle = ParagraphStyle(name="detail",
                                                   fontName="Helvetica-Bold",
                                                   fontSize=9,
                                                   )
                        dataTableau.append((_(u"Nom"), Paragraph(DICT_VALEURS["{INDIVIDU_NOM}"], paraStyle)))
                        dataTableau.append((_(u"Prénom"), Paragraph(DICT_VALEURS["{INDIVIDU_PRENOM}"], paraStyle)))
                        dataTableau.append((_(u"Activité"), Paragraph(DICT_VALEURS["{ACTIVITE_NOM_LONG}"], paraStyle)))
                        dataTableau.append((_(u"Groupe"), Paragraph(DICT_VALEURS["{GROUPE_NOM_LONG}"], paraStyle)))
                        dataTableau.append((_(u"Catégorie"), Paragraph(DICT_VALEURS["{NOM_CATEGORIE_TARIF}"], paraStyle)))

                        style = TableStyle([
                            ('VALIGN', (0, 0), (-1, -1), 'MIDDLE'),
                            ('FONT', (0, 0), (0, -1), "Helvetica", 9),
                            ('GRID', (0, 0), (-1, -1), 0.25, colors.black),
                            ('ALIGN', (0, 0), (0, -1), 'RIGHT'),
                        ])
                        tableau = Table(dataTableau, largeursColonnes)
                        tableau.setStyle(style)
                        story.append(tableau)

                # Saut de page
                story.append(PageBreak())

        # Finalisation du PDF
        doc.build(story)

        # Ouverture du PDF
        if ouverture == True:
            FonctionsPerso.LanceFichierExterne(nomDoc)