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)
Ejemplo n.º 2
0
def generate_pdf(file):
    with open(file, 'r', encoding='utf-8') as file:
        data = file.read().replace('\n', '<br/>') \
            .replace('Juliet: <Media weggelaten> Neutral', 'Juliet: ' + 1 * "<br/>" + 11 * '<br/>' +
                     '<img src= "img_resized/neutral_juliet.jpg"/>' + 1 * '<br/>') \
            .replace('Juliet: <Media weggelaten> Positive', 'Juliet: ' + 1 * "<br/>" + 11 * '<br/>' +
                     '<img src= "img_resized/happy_juliet.jpg"/>' + 1 * '<br/>') \
            .replace('Juliet: <Media weggelaten> Negative', 'Juliet: ' + 1 * "<br/>" + 11 * '<br/>' +
                     '<img src= "img_resized/angry_juliet.jpg"/>' + 1 * '<br/>') \
            .replace('Romeo: <Media weggelaten> Neutral', 'Romeo: ' + 1 * "<br/>" + 11 * '<br/>' +
                     '<img src= "img_resized/neutral_romeo.jpg"/>' + 1 * '<br/>') \
            .replace('Romeo: <Media weggelaten> Positive', 'Romeo: ' + 1 * "<br/>" + 11 * '<br/>' +
                     '<img src= "img_resized/happy_romeo.jpg"/>' + 1 * '<br/>') \
            .replace('Romeo: <Media weggelaten> Negative', 'Romeo: ' + 1 * "<br/>" + 11 * '<br/>' +
                     '<img src= "img_resized/angry_romeo.jpg"/>' + 1 * '<br/>')

    story = [
        DocAssign("currentFrame", "doc.frame.id"),
        DocAssign("currentPageTemplate", "doc.pageTemplate.id"),
        DocAssign("aW", "availableWidth"),
        DocAssign("aH", "availableHeight"),
        DocAssign("aWH", "availableWidth,availableHeight"),
        Paragraph("<b>Romeo and Juliet</b>" + 15 * '<br/>', title),
        Image('img/romeo_juliet.jpg', width=4 * inch, height=5 * inch),
        PageBreak(),
        Paragraph("<b>Introduction</b>", header),
        Paragraph(
            2 * '<br/>' +
            "<i>A 2019 interpretation of the famous love story in the form of a WhatsApp dialogue. Made for NaNoGenMo.</i>",
            normal),
        PageBreak(),
        Paragraph(data, normal)
    ]

    doc = SimpleDocTemplate("romeo_and_juliet.pdf")
    doc.build(story)
 def test1(self):
     from reportlab.lib.styles import ParagraphStyle
     from reportlab.platypus import SimpleDocTemplate, Paragraph
     from reportlab.platypus.flowables import DocAssign, DocExec, DocPara, DocIf, DocWhile
     normal = ParagraphStyle(name='Normal',
                             fontName='Helvetica',
                             fontSize=8.5,
                             leading=11)
     header = ParagraphStyle(name='Heading1',
                             parent=normal,
                             fontSize=14,
                             leading=19,
                             spaceAfter=6,
                             keepWithNext=1)
     story = [
         DocAssign('currentFrame', 'doc.frame.id'),
         DocAssign('currentPageTemplate', 'doc.pageTemplate.id'),
         DocAssign('aW', 'availableWidth'),
         DocAssign('aH', 'availableHeight'),
         DocAssign('aWH', 'availableWidth,availableHeight'),
         DocAssign('i', 3),
         DocIf('i>3', Paragraph('The value of i is larger than 3', normal),
               Paragraph('The value of i is not larger than 3', normal)),
         DocIf('i==3', Paragraph('The value of i is equal to 3', normal),
               Paragraph('The value of i is not equal to 3', normal)),
         DocIf('i<3', Paragraph('The value of i is less than 3', normal),
               Paragraph('The value of i is not less than 3', normal)),
         DocWhile('i', [
             DocPara('i',
                     format='The value of i is %(__expr__)d',
                     style=normal),
             DocExec('i-=1')
         ]),
         DocPara('repr(doc._nameSpace)', escape=True),
         DocPara('doc.canv.getPageNumber()',
                 'The current page number is %(__expr__)d',
                 style=normal)
     ]
     doc = SimpleDocTemplate(outputfile('test_doc_programming.pdf'))
     doc.build(story)
 def test1(self):
     from reportlab.lib.styles import ParagraphStyle
     from reportlab.platypus import SimpleDocTemplate, Paragraph
     from reportlab.platypus.flowables import DocAssign, DocExec, DocPara, DocIf, DocWhile
     normal = ParagraphStyle(name='Normal', fontName='Helvetica', fontSize=8.5, leading=11)
     header = ParagraphStyle(name='Heading1', parent=normal, fontSize=14, leading=19,
                 spaceAfter=6, keepWithNext=1)
     story = [
             DocAssign('currentFrame','doc.frame.id'),
             DocAssign('currentPageTemplate','doc.pageTemplate.id'),
             DocAssign('aW','availableWidth'),
             DocAssign('aH','availableHeight'),
             DocAssign('aWH','availableWidth,availableHeight'),
             DocAssign('i',3),
             DocIf('i>3',Paragraph('The value of i is larger than 3',normal),Paragraph('The value of i is not larger than 3',normal)),
             DocIf('i==3',Paragraph('The value of i is equal to 3',normal),Paragraph('The value of i is not equal to 3',normal)),
             DocIf('i<3',Paragraph('The value of i is less than 3',normal),Paragraph('The value of i is not less than 3',normal)),
             DocWhile('i',[DocPara('i',format='The value of i is %(__expr__)d',style=normal),DocExec('i-=1')]),
             DocPara('"{"+", ".join(("%s=%s" % (_k,(_v.__class__.__name__ if "<" in repr(_v) else repr(_v)[1:] if repr(_v) and repr(_v)[0] in "ub" else repr(_v))) for _k,_v in sorted(doc._nameSpace.items()) if _k not in ("_k","_v")))+"}"',escape=True),
             DocPara('doc.canv.getPageNumber()','The current page number is %(__expr__)d',style=normal) 
             ]
     doc = SimpleDocTemplate(outputfile('test_doc_programming.pdf'))
     doc.build(story)
    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)
Ejemplo n.º 6
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"") 
Ejemplo n.º 7
0
    def test2(self):
        "This makes one long multi-page paragraph in multi-pass for testing docWhile etc etc"
        from reportlab.platypus.flowables import DocAssign, DocExec, DocPara, DocIf, DocWhile
        from test_platypus_xref import MyDocTemplate
        from reportlab.platypus.tableofcontents import TableOfContents, SimpleIndex
        from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
        from reportlab.platypus import Paragraph
        from reportlab.lib import colors
        from reportlab.lib.randomtext import randomText, PYTHON

        # Build story.
        story = []

        styleSheet = getSampleStyleSheet()
        h1 = styleSheet['Heading1']
        h1.pageBreakBefore = 1
        h1.keepWithNext = 1
        h1.outlineLevel = 0

        h2 = styleSheet['Heading2']
        h2.backColor = colors.cyan
        h2.keepWithNext = 1
        h2.outlineLevel = 1

        bt = styleSheet['BodyText']

        story.append(
            Paragraph("""Cross-Referencing Test""", styleSheet["Title"]))
        story.append(
            Paragraph(
                """
            Subsequent pages test cross-references: indexes, tables and individual
            cross references.  The number in brackets at the end of each paragraph
            is its position in the story. (%d)""" % len(story), bt))

        story.append(Paragraph("""Table of Contents:""", styleSheet["Title"]))
        toc = TableOfContents()
        story.append(toc)

        chapterNum = 1
        for i in range(10):
            story.append(
                Paragraph(
                    'Chapter %d: Chapters always starts a new page' %
                    chapterNum, h1))
            chapterNum += chapterNum
            story.append(DocAssign('chapterNum', chapterNum))
            for j in range(3):
                story.append(
                    Paragraph(
                        'Heading1 paragraphs should always'
                        'have a page break before.  Heading 2 on the other hand'
                        'should always have a FRAME break before (%d)' %
                        len(story), bt))
                story.append(
                    Paragraph(
                        'Heading 2 should always be kept with the next thing (%d)'
                        % len(story), h2))
                for j in range(3):
                    story.append(
                        Paragraph(
                            randomText(theme=PYTHON, sentences=2) +
                            ' (%d)' % len(story), bt))
                    story.append(
                        Paragraph(
                            'I should never be at the bottom of a frame (%d)' %
                            len(story), h2))
                    story.append(
                        Paragraph(
                            randomText(theme=PYTHON, sentences=1) +
                            ' (%d)' % len(story), bt))

            story.extend([
                DocAssign('currentFrame', 'doc.frame.id'),
                DocAssign('currentPageTemplate', 'doc.pageTemplate.id'),
                DocAssign('aW', 'availableWidth'),
                DocAssign('aH', 'availableHeight'),
                DocAssign('aWH', 'availableWidth,availableHeight'),
                DocAssign('i', 3, life='forever'),
                DocIf('i>3', Paragraph('The value of i is larger than 3', bt),
                      Paragraph('The value of i is not larger than 3', bt)),
                DocIf('i==3', Paragraph('The value of i is equal to 3', bt),
                      Paragraph('The value of i is not equal to 3', bt)),
                DocIf('i<3', Paragraph('The value of i is less than 3', bt),
                      Paragraph('The value of i is not less than 3', bt)),
                DocWhile('i', [
                    DocPara('i',
                            format='The value of i is %(__expr__)d',
                            style=bt),
                    DocExec('i-=1')
                ]),
                DocPara('repr(doc._nameSpace)', escape=True),
            ])
        story.append(Paragraph('The Index which goes at the back', h1))
        story.append(SimpleIndex())

        doc = MyDocTemplate(
            outputfile('test_platypus_programming_multipass.pdf'))
        doc.multiBuild(story)
Ejemplo n.º 8
0
story.append(Paragraph("""Cross-Referencing Test""", styleSheet["Title"]))  # 第0级标题
story.append(Paragraph("""                                                            
Subsequent pages test cross-references: indexes, tables and individual
cross references.  The number in brackets at the end of each paragraph
is its position in the story. ({})""".format(len(story)), bt))

story.append(Paragraph("""Table of Contents:""", styleSheet["Title"]))
toc = TableOfContents()  # 目录对象
story.append(toc)

chapterNum = 1  # 记录章节
for i in range(10):  # 共10章
    story.append(Paragraph('Chapter {}: Chapters always starts a new page'.format(chapterNum), h1))
    # 每一个章节的标题
    chapterNum += chapterNum
    story.append(DocAssign('chapterNum', chapterNum))
    for j in range(3):
        story.append(Paragraph('Heading1 paragraphs should always'
                               'have a page break before.  Heading 2 on the other hand'
                               'should always have a FRAME break before ({})'.format(len(story)), bt))
        # 普通文本
        story.append(Paragraph('Heading 2 should always be kept with the next thing ({})'.format(len(story)), h2))
        # 二级标题
        for p in range(3):
            story.append(Paragraph(randomText(theme=PYTHON, sentences=2) + ' ({})'.format(len(story)), bt))
            # 两句,内容随机产生,普通文本
            story.append(Paragraph('I should never be at the bottom of a frame ({})'.format(len(story)), h2))
            # 二级标题
            story.append(Paragraph(randomText(theme=PYTHON, sentences=1) + ' ({})'.format(len(story)), bt))
            # 一句,内容随机产生,普通文本
    story.extend([
Ejemplo n.º 9
0
    def __init__(self,
                 dictComptes={},
                 dictOptions={},
                 IDmodele=None,
                 ouverture=True,
                 nomFichier=None):
        """ Impression """
        global DICT_COMPTES, DICT_OPTIONS
        DICT_COMPTES = dictComptes
        DICT_OPTIONS = dictOptions

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

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

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

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

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

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

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

        for nomSansCivilite, IDcompte_payeur in listeNomsSansCivilite:
            dictCompte = dictComptes[IDcompte_payeur]
            if dictCompte["select"] == True:

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

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

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

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

                texte = dictCompte["texte"]
                listeParagraphes = texte.split("</para>")
                for paragraphe in listeParagraphes:
                    if "<para" in paragraphe:
                        paragraphe = u"%s</para>" % paragraphe
                        textePara = Paragraph(paragraphe, paraStyle)
                        story.append(textePara)
                        if "> </para" in paragraphe:
                            story.append(Spacer(0, 13))

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

        # Finalisation du PDF
        doc.build(story)

        # Ouverture du PDF
        if ouverture == True:
            FonctionsPerso.LanceFichierExterne(nomDoc)
    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)
Ejemplo n.º 11
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)