Outils pour utilisateurs

Outils du site


issue50:tutopython

Différences

Ci-dessous, les différences entre deux révisions de la page.

Lien vers cette vue comparative

Les deux révisions précédentesRévision précédente
Prochaine révision
Révision précédente
issue50:tutopython [2011/07/05 20:57] fredphil91issue50:tutopython [2011/08/07 08:31] (Version actuelle) fredphil91
Ligne 11: Ligne 11:
 Waouh ! Il est difficile de croire que ceci est déjà le 24ème numéro. Cela fait deux ans que nous apprenons le Python ! Vous avez parcouru un très long chemin. Waouh ! Il est difficile de croire que ceci est déjà le 24ème numéro. Cela fait deux ans que nous apprenons le Python ! Vous avez parcouru un très long chemin.
  
-Cette fois, nous allons couvrir deux sujets. Le premier est l'impression sur une imprimante, le second est la création de fichiers RTF (Rich Text Format) comme sortie.+Cette fois-ci, nous allons traiter deux sujets. Le premier est l'impression sur une imprimante, le second est la création de fichiers RTF (Rich Text Format, ou Format de Texte Riche) comme sortie.
  
 Impression générique sous Linux Impression générique sous Linux
  
-Commençons donc avec l'impression sur une imprimante. L'idée de parler de cela provenait d'un courriel envoyé par Gord Campbell. Il est réellement facile de faire la plupart des impressions depuis Linux, et plus facile qu'avec cet autre système d'exploitation qui commence par « WIN » - et dont je ne parlerai pas.+Commençons donc avec l'impression sur une imprimante. L'idée de parler de cela provenait d'un courriel envoyé par Gord Campbell. Il est réellement facile de faire la plupart des impressions depuis Linux plus facile qu'avec cet autre système d'exploitation qui commence par « WIN » - et dont je ne parlerai pas.
  
-Tout est plutôt simple tant que vous ne souhaitez imprimer que du texte simple, sans gras, italique, changements de polices, etc. Voici une application simple qui permet d'imprimer directement sur votre imprimante ...+Tout est plutôt facile tant que vous ne souhaitez imprimer que du texte simple, sans gras, italique, changements de polices, etc. Voici une application simple qui permet d'imprimer directement sur votre imprimante ...
  
 **import os  **import os 
Ligne 39: Ligne 39:
 We can also create a text file, then send it out to the printer like this...** We can also create a text file, then send it out to the printer like this...**
  
 +C'est assez facile à comprendre si vous élargissez un peu votre esprit. Dans le code ci-dessus, « lpr » est le spooler d'impression. Le seul pré-requis est que nous ayons déjà configuré « lpd » et qu'il fonctionne. C'est très probablement déjà fait pour vous si vous utilisez une imprimante sous Ubuntu. « lpd » est généralement considéré comme un « filtre magique » qui permet de convertir automatiquement différents types de documents en quelque chose que l'imprimante peut comprendre. Nous allons imprimer sur le périphérique/objet « lpr ». Pensez-y comme à un simple fichier. Nous ouvrons le fichier ; nous devons importer « os ». Puis à la ligne 2, nous avons ouvert « lpr » avec un accès en écriture, en l'assignant à la variable objet « pr ». Nous procédons alors à une écriture « pr.write » avec tout ce que nous voulons imprimer. Enfin (ligne 5), nous fermons le fichier ce qui va envoyer les données vers l'imprimante.
  
 +Nous pouvons également créer un fichier texte puis l'envoyer à l'imprimante comme ceci...
  
 **import os **import os
Ligne 51: Ligne 53:
 I'll leave you to play with this for now.** I'll leave you to play with this for now.**
  
 +  import os
 +  filename = 'fichier.bidon'
 +  os.system('lpr %s' % filename)
  
 +Dans ce cas, nous utilisons toujours l'objet lpr mais avec la commande « os.system » qui sert simplement à envoyer à Linux une commande comme si on l'avait saisie depuis un terminal.
 +
 +Je vous laisserai vous amuser un peu avec cela.
  
 **PyRTF **PyRTF
Ligne 59: Ligne 67:
 First, you need to download and install the PyRTF package. Go to http://pyrtf.sourceforge.net and get the PyRTF-0.45.tar.gz package. Save it someplace and use archive manager to unpack it. Then using terminal, go to where you unpacked it. First we need to install the package, so type “sudo python setup.py install” and it will be installed for you. Notice there is an examples folder there. There's some good information there on how to do some advanced things.** First, you need to download and install the PyRTF package. Go to http://pyrtf.sourceforge.net and get the PyRTF-0.45.tar.gz package. Save it someplace and use archive manager to unpack it. Then using terminal, go to where you unpacked it. First we need to install the package, so type “sudo python setup.py install” and it will be installed for you. Notice there is an examples folder there. There's some good information there on how to do some advanced things.**
  
 +pyRTF
  
 +Maintenant occupons-nous des fichiers RTF. Le format RTF (c'est comme quand on dit le numéro PIN puisque PIN signifie Numéro d'Identification Personnel et que ça revient à dire le Numéro Numéro d'Identification Personnel [Ndt : en français on n'a pas ce problème de redondance puisqu'on parle de code PIN] : ça dépend du département Département des Redondances, non ?) a été créé à l'origine par Microsoft en 1987 et sa syntaxe s'est inspirée du langage de composition de texte TeX. PyRTF est une merveilleuse bibliothèque qui facilite la création de fichiers RTF. Cela nécessite de réfléchir en amont à ce à quoi le fichier doit ressembler, mais le résultat en vaut vraiment la peine.
  
-Here we go. Let's start as we usually do, creating the stub of our program which is shown on the next page, top r**ight.+Tout d'abord il faut télécharger et installer le paquet pyRTF. Allez sur http://pyrtf.sourceforge.net et récupérez le paquet PyRTF-0.45.tar.gz. Sauvegardez-le quelque part et utilisez le gestionnaire d'archives pour le décompresser. Puis ouvrez un terminal et déplacez-vous à l'endroit où vous l'avez décompressé. Tout d'abord il faut installer le paquet, avec la commande « sudo python setup.py install ». Remarquez qu'il y a un répertoire d'exemples, qui contient de bonnes informations pour faire des choses un peu compliquées. 
 + 
 +**Here we go. Let's start as we usually do, creating the stub of our program which is shown on the next page, top right.
 Before going any further, we'll discuss what's going on. Line 2 imports the PyRTF library. Note that we are using a different import format than normal. This one imports everything from the library. Before going any further, we'll discuss what's going on. Line 2 imports the PyRTF library. Note that we are using a different import format than normal. This one imports everything from the library.
 Our main working routine is MakeExample. We've stubbed for now. The OpenFile routine creates the file for us with the name we pass into it, appends the extension “rtf”, puts it into the “write” mode, and returns a file handle. Our main working routine is MakeExample. We've stubbed for now. The OpenFile routine creates the file for us with the name we pass into it, appends the extension “rtf”, puts it into the “write” mode, and returns a file handle.
Ligne 69: Ligne 81:
 Here, we create an instance of the Renderer object, call the MakeExample routine, getting the returned object doc. We then write the file (in doc) using the OpenFile routine.** Here, we create an instance of the Renderer object, call the MakeExample routine, getting the returned object doc. We then write the file (in doc) using the OpenFile routine.**
  
 +Nous y voilà. Commençons comme d'habitude en créant le canevas de notre programme que vous pouvez voir en haut à droite de la page suivante.
 +Avant d'aller plus loin, parlons de ce qui se passe. La ligne 2 importe la bibliothèque pyRTF. Remarquez que nous utilisons un format d'importation différent des autres fois : cette fois-ci nous importons tout ce qui se trouve dans la biblothèque.
 +Notre routine principale s'appelle FabriqueExemple et ne fait rien pour le moment. La routine OuvreFichier crée un fichier avec pour nom celui passé en argument, lui ajoute l'extension .rtf, le place en mode écriture et retourne un pointeur sur ce fichier.
  
 +Nous avons déjà parlé de la routine <nowiki>__name__</nowiki> précédemment, mais pour vous rafraîchir la mémoire je vous rappelle que si nous exécutons le programme en mode autonome la variable interne <nowiki>__name__</nowiki> est réglée à « <nowiki>__main__</nowiki> » ; par contre, si on l'appelle comme « import » depuis un autre programme, cette portion de code sera ignorée.
 +
 +Nous créons là une instance de l'objet Renderer, appelons la routine FabriqueExemple et récupérons l'objet retourné docu. Puis nous écrivons le fichier (docu) en utilisant la routine OuvreFichier.
  
 **Now for the meat of our worker routine MakeExample. Replace the pass statement with the code shown below. **Now for the meat of our worker routine MakeExample. Replace the pass statement with the code shown below.
Ligne 79: Ligne 97:
 Save the program as “rtftesta.py” and run it. When it's completed, use openoffice (or LibreOffice) to open the file and look at it.** Save the program as “rtftesta.py” and run it. When it's completed, use openoffice (or LibreOffice) to open the file and look at it.**
  
- +Passons maintenant au contenu de la routine principale FabriqueExemple. Remplacez l'instruction pass par le code ci-dessous. 
 + 
 +Regardons ce que nous avons fait. La première ligne crée une instance de document. Puis on crée une instance de feuille de style. Ensuite nous créons une instance de l'objet section et on l'ajoute au document. Imaginez une section comme un chapitre dans un livre. Ensuite nous créons un paragraphe en utilisant le style Normal. L'auteur de pyRTF a préréglé ce style avec une police Arial en 11 points. Ensuite on écrit le texte qu'on veut dans ce paragraphe, on l'ajoute à la section et on retourne notre document docu. 
 + 
 +C'est vraiment facile. Encore une fois, vous devez réfléchir soigneusement en amont à la sortie désirée, mais ce n'est pas très compliqué. 
 + 
 +Sauvegardez ce programme en tant que « rtftesta.py » et exécutez-le. Enfin, utilisez OpenOffice (ou LibreOffice) pour ouvrir le fichier et l'examiner.
  
 **Now let's do some neat things. First, we'll add a header. Once again, the author of PyRTF has given us a predefined style called Header1. We'll use that for our header. In between the doc.Sections.append line and the p = Paragraph line, add the following.  **Now let's do some neat things. First, we'll add a header. Once again, the author of PyRTF has given us a predefined style called Header1. We'll use that for our header. In between the doc.Sections.append line and the p = Paragraph line, add the following. 
Ligne 93: Ligne 117:
 DR.Write(doc, OpenFile('rtftestb'))** DR.Write(doc, OpenFile('rtftestb'))**
  
 +Maintenant faisons quelques modifications sympathiques. Tout d'abord, ajoutons un en-tête. Là encore l'auteur de pyRTF nous fournit un style prédéfini appelé Header1, que nous allons utiliser pour notre en-tête. Ajoutez ce qui suit entre les lignes docu.Sections.append et p = Paragraph.
  
 +  p = Paragraph(ss.ParagraphStyles.Heading1)
 +  p.append('Exemple d'en-tete')
 +  section.append(p)
 +
 +Modifiez le nom du fichier en « rtftestb » ; cela devrait donner ceci :
 +
 +  DR.Write(doc, OuvreFichier('rtftestb'))
  
 **Save this as rtftestb.py and run it. So now we have a header. I'm sure your mind is going down many roads thinking about what more can we do. Here's a list of what the author has given us as the predefined styles. **Save this as rtftestb.py and run it. So now we have a header. I'm sure your mind is going down many roads thinking about what more can we do. Here's a list of what the author has given us as the predefined styles.
Ligne 103: Ligne 135:
 It is also possible to provide overrides for elements of a style. For example you can change just the font size to 24 point or typeface to Impact or even more Attributes like BOLD or Italic or BOTH.** It is also possible to provide overrides for elements of a style. For example you can change just the font size to 24 point or typeface to Impact or even more Attributes like BOLD or Italic or BOTH.**
  
 +Sauvegardez-le sous le nom rtftestb.py et exécutez-le. Maintenant nous avons un en-tête. Je suis sûr que votre esprit est en train de se demander tout ce qu'on peut faire encore. Voici une liste des styles prédéfinis que l'auteur nous fournit.
  
 +Normal, Normal Short, Heading 1, Heading 2, Normal Numbered, Normal Numbered 2. Il y a également un style List que je vous laisserai découvrir. Si vous voulez en voir davantage, sur ça et sur d'autres sujets, les styles sont définis dans le fichier Elements.py que vous avez installé tout à l'heure.
 +
 +Ces styles prédéfinis sont utiles pour beaucoup de choses, mais on peut avoir besoin d'en créer d'autres. Voyons maintenant comment modifier les polices, leur taille et leurs attributs (gras, italique, etc.) à la volée. Après notre paragraphe, et avant de retourner l'objet document, insérez le code ci-dessus à droite et modifiez le nom du fichier de sortie en rtftestc. Sauvegardez le fichier sous le nom rtftestc.py et exécutez-le. La nouvelle portion du document revrait ressembler à ceci...
 +
 +Il est également possible de passer outre les éléments d'un style. Par exemple vous pouvez modifier seulement la taille de la police à 24 points, ou son type à Impact ou même modifier d'autres attributs comme la graisse ou l'italique ou les deux.
  
 **Now what have we done? Line 1 creates a new paragraph. We then start, as we did before, putting in our text. Look at the fourth line (TEXT(' size to 24 point', size = 48),). By using the TEXT qualifier, we are telling PyRTF to do something different in the middle of the sentence, which in this case is to change the size of the font (Arial at this point) to 24-point, followed by the 'size = ' command. But, wait a moment. The 'size =' says 48, and what we are printing says 24 point, and the output is actually in 24-point text. What's going on here? Well the size command is in half points. So if we want an 8-point font we have to use size = 16. Make sense? **Now what have we done? Line 1 creates a new paragraph. We then start, as we did before, putting in our text. Look at the fourth line (TEXT(' size to 24 point', size = 48),). By using the TEXT qualifier, we are telling PyRTF to do something different in the middle of the sentence, which in this case is to change the size of the font (Arial at this point) to 24-point, followed by the 'size = ' command. But, wait a moment. The 'size =' says 48, and what we are printing says 24 point, and the output is actually in 24-point text. What's going on here? Well the size command is in half points. So if we want an 8-point font we have to use size = 16. Make sense?
Ligne 113: Ligne 151:
 We can also set the color of the text within the TEXT inline command. Like this.** We can also set the color of the text within the TEXT inline command. Like this.**
  
 +Bon, qu'avons-nous fait ? La ligne 1 crée un nouveau paragraphe. On commence comme auparavant à l'ajouter au texte. Regardez la ligne 4 (TEXT(' taille de la police a 24 points', size=48),) : en utilisant le qualificatif TEXT on indique à pyRTF qu'il faut faire quelque chose de différent au milieu de la phrase, dans ce cas on modifie la taille de la police (Arial) à 24 points, en précisant à la suite la commande «  size = ». Mais attendez une minute : on indique 48 comme taille alors qu'on veut écrire en 24 points ; et la sortie est réellement en 24 points. Que se passe-t-il ici ? Eh bien, la commande de taille est en demi-points ; ainsi si on veut écrire en police 8 points, on doit utiliser « size = 16 ». Vous comprenez ?
 +
 +Ensuite, on continue le texte et on modifie la police avec la commande « font = ». Cette fois encore, tout ce qui est dans l'instruction en ligne TEXT entre les guillemets sera affecté, mais pas le reste.
 +
 +Bien. Si vous avez compris tout cela, que peut-on faire d'autre ?
  
 +On peut aussi régler la couleur du texte avec l'instruction en ligne TEXT de cette façon :
  
 **p = Paragraph() **p = Paragraph()
Ligne 125: Ligne 169:
 section.append(p)** section.append(p)**
  
 +  p = Paragraph() 
 +  p.append('Voici un nouveau paragraphe avec le mot ', 
 +     TEXT('ROUGE',colour=ss.Colours.Red), 
 +     ' ecrit en rouge.'
 +  section.append(p)
    
 **Notice that we didn't have to restate the paragraph style as Normal, since it sticks until we change it. Also notice that if you live in the U.S., you have to use the “proper” spelling of colour. **Notice that we didn't have to restate the paragraph style as Normal, since it sticks until we change it. Also notice that if you live in the U.S., you have to use the “proper” spelling of colour.
Ligne 137: Ligne 185:
 So now you must be thinking that this is all well and good, but how do we make our own styles? That's pretty easy. Move to the top of our file, and before our header line, add the following code.** So now you must be thinking that this is all well and good, but how do we make our own styles? That's pretty easy. Move to the top of our file, and before our header line, add the following code.**
  
 +Remarquez que nous n'avons pas eu à repréciser que le style de paragraphe est Normal, puisqu'il ne change pas tant qu'on ne lui dit pas. Remarquez également que si vous habitez aux États-Unis vous devez utiliser la bonne orthographe pour « Colours » [Ndt : les américains utilisent souvent l'orthographe « impropre » Color].
 +
 +Voici les couleurs prédéfinies : Black, Blue, Turquoise, Green, Pink, Red, Yellow, White, BlueDark, Teal, GreenDark, Violet, RedDark, YellowDark, GreyDark et Grey.
 +
 +Et voici une liste de toutes les polices prédéfinies (ce sont les notations pour les utiliser) :
 +
 +Arial, ArialBlack, ArialNarrow, BitstreamVeraSans, BitstreamVeraSerif, BookAntiqua, BookmanOldStyle, Castellar, CenturyGothic, ComicSansMS, CourierNew, FranklinGothicMedium, Garamond, Georgia, Haettenschweiler, Impact, LucidaConsole, LucidaSansUnicode, MicrosoftSansSerif, PalatinoLinotype, MonotypeCorsiva, Papyrus, Sylfaen, Symbol, Tahoma, TimesNewRoman, TrebuchetMS et Verdana.
  
 +Maintenant vous devez penser que tout cela est bien joli, mais comment peut-on créer ses propres styles ? C'est assez simple. Retournez en haut de notre fichier et ajoutez le code qui suit avant la ligne d'en-tête.
  
 **result = doc.StyleSheet **result = doc.StyleSheet
Ligne 149: Ligne 205:
 Before we write the code to actually use it, let's see what we have done. We are creating a new stylesheet instance called result. In the second line, we are setting the font to 8-point Courier New, and then “registering” the style as Courier. Remember, we have to use 16 as the size since the font size is in half-point values.** Before we write the code to actually use it, let's see what we have done. We are creating a new stylesheet instance called result. In the second line, we are setting the font to 8-point Courier New, and then “registering” the style as Courier. Remember, we have to use 16 as the size since the font size is in half-point values.**
  
 +  result = docu.StyleSheet
 +  NormalText = TextStyle(TextPropertySet(result.Fonts.CourierNew,16))
 +  ps2 = ParagraphStyle('Courier',NormalText.Copy())
 +  result.ParagraphStyles.append(ps2)
  
 +Avant d'écrire le code pour l'utiliser, regardons ce que nous avons fait. Nous créons une nouvelle instance feuille de style nommée result. À la deuxième ligne nous réglons la police à CourierNew en 8 points puis « enregistrons » le style comme Courier. Souvenez-vous que nous devons indiquer 16 comme taille puisque ce sont des demi-points.
  
 **Now, before the return line at the bottom of the routine, let's include a new paragraph using the Courier style. **Now, before the return line at the bottom of the routine, let's include a new paragraph using the Courier style.
Ligne 161: Ligne 222:
 result.ParagraphStyles.append(ps2)** result.ParagraphStyles.append(ps2)**
  
 +Maintenant, ajoutons un nouveau paragraphe en utilisant le style Courier, avant la ligne return en bas de la routine.
  
 +Maintenant que vous avez un nouveau style, vous pouvez l'utiliser quand vous le souhaitez. Vous pouvez utiliser n'importe quelle police de la liste ci-dessus et créer vos propres styles. Recopiez simplement le code du style et remplacez les informations de police et de taille comme vous le voulez. On peut aussi faire cela :
 +
 +  TexteNormal = TextStyle(TextPropertySet(result.Fonts.Arial,22,bold=True,colour=ss.Colours.Red))
 +  ps2 = ParagraphStyle('ArialGrasRouge',TexteNormal.Copy())
 +  result.ParagraphStyles.append(ps2)
  
 **And add the code below... **And add the code below...
Ligne 173: Ligne 240:
 to print the ArialBoldRed style.** to print the ArialBoldRed style.**
  
 +Et ajouter le code suivant :
 +
 +  p = Paragraph(ss.ParagraphStyles.ArialGrasRouge)
 +  p.append(LINE,'Et maintenant on utilise le style ArialGrasRouge.',LINE)
 +  section.append(p)
  
 +pour afficher en style ArialGrasRouge.
  
 **Tables **Tables
Ligne 187: Ligne 260:
 We don't need to discuss this since it's basically the same code that we used before. Now, we'll flesh out the TableExample routine. I'm basically using part of the example file provided by the author of PyRTF. Replace the pass statement in the routine with the following code...** We don't need to discuss this since it's basically the same code that we used before. Now, we'll flesh out the TableExample routine. I'm basically using part of the example file provided by the author of PyRTF. Replace the pass statement in the routine with the following code...**
  
 +Tableaux
  
 +Souvent, la seule manière de présenter correctement des données dans un document est d'utiliser un tableau. Faire des tableaux dans un texte est plutôt difficile, mais PARFOIS c'est plutôt facile avec pyRTF. J'expliquerai cela plus tard dans cet article.
 +
 +Regardons un tableau standard (ci-dessous) dans OpenOffice/LibreOffice. Cela ressemble à une feuille de calcul, où tout est placé dans des colonnes.
 +
 +Des lignes horizontales, et des colonnes verticales. Un concept simple.
 +
 +Commençons une nouvelle application nommée rtfTableau-a.py. Démarrons avec notre code standard (page suivante) et construisons à partir de là.
 +
 +Pas besoin d'explications ici puisque c'est à peu près le même code que nous avons utilisé précédemment. Maintenant, écrivons la routine ExempleTableau. J'utilise en partie l'exemple fourni par l'auteur de pyRTF. Remplacez l'instruction pass dans la routine par le code suivant...
  
 **doc = Document() **doc = Document()
Ligne 205: Ligne 288:
      TabPS.DEFAULT_WIDTH * 3)**      TabPS.DEFAULT_WIDTH * 3)**
  
 +  docu = Document()
 +  ss = docu.StyleSheet
 +  section = Section()
 +  docu.Sections.append(section)
  
 +Cette partie est la même que précédemment, passons à la suite.
 +
 +  tableau = Table(TabPS.DEFAULT_WIDTH * 7,
 +     TabPS.DEFAULT_WIDTH * 3,
 +     TabPS.DEFAULT_WIDTH * 3)
  
 **This line (yes, it's really one line, but is broken up for easy viewing) creates our basic table. We are creating a table with 3 columns, the first is 7 tabs wide, the second and third are three tabs wide. We don't have to deal with tabs alone, you can enter the widths in twips. More on that in a moment. **This line (yes, it's really one line, but is broken up for easy viewing) creates our basic table. We are creating a table with 3 columns, the first is 7 tabs wide, the second and third are three tabs wide. We don't have to deal with tabs alone, you can enter the widths in twips. More on that in a moment.
Ligne 217: Ligne 309:
 table.AddRow(c1,c2,c3)** table.AddRow(c1,c2,c3)**
  
 +Cette ligne (oui, il ne s'agit que d'une ligne, mais découpée pour plus de clarté) crée notre tableau basique. Nous créons un tableau à trois colonnes, la première contient 7 cellules, les deux suivantes en contiennent 3. Nous n'avons pas que des cellules uniques à notre disposition, car on pourra saisir les largeurs en « twips » [Ndt : ce sont des unités de mesure, utilisées en LibreOffice et pour le RTF, équivalentes à 1/1440 d'un pouce (2,54 cm). CF http://en.wikipedia.org/wiki/Twip#In_computing.] Nous y reviendrons dans un moment.
  
 +  c1 = Cell(Paragraph('ligne 1, cellule 1'))
 +  c2 = Cell(Paragraph('ligne 1, cellule 2'))
 +  c3 = Cell(Paragraph('ligne 1, cellule 3'))
 +  tableau.AddRow(c1,c2,c3)
  
 **Here we are setting the data that goes into each cell in the first row. **Here we are setting the data that goes into each cell in the first row.
Ligne 231: Ligne 328:
 This group of code sets the data for row number two. Notice we can set a different style for a single or multiple cells.** This group of code sets the data for row number two. Notice we can set a different style for a single or multiple cells.**
  
 +Ici nous réglons les données qui vont dans chaque cellule de la première ligne.
  
 +  c1 = Cell(Paragraph(ss.ParagraphStyles.Heading2,'Style en-tete 2'))
 +  c2 = Cell(Paragraph(ss.ParagraphStyles.Normal,'Retour au style Normal'))
 +  c3 = Cell(Paragraph('Encore du style Normal'))
 +  tableau.AddRow(c1,c2,c3)
 +
 +Ce morceau de code règle les données pour la deuxième ligne. Remarquez que nous pouvons régler des styles différents pour une seule ou plusieurs cellules.
  
 **c1 = Cell(Paragraph(ss.ParagraphStyles.Heading2,'Heading2 Style')) **c1 = Cell(Paragraph(ss.ParagraphStyles.Heading2,'Heading2 Style'))
Ligne 249: Ligne 353:
 This appends the table into the section and returns the document for printing.** This appends the table into the section and returns the document for printing.**
  
 +  c1 = Cell(Paragraph(ss.ParagraphStyles.Heading2,'Style en-tete 2'))
 +  c2 = Cell(Paragraph(ss.ParagraphStyles.Normal,'Retour au style Normal'))
 +  c3 = Cell(Paragraph('Encore du style Normal'))
 +  tableau.AddRow(c1,c2,c3)
  
 +Ceci règle la dernière ligne.
 +
 +  section.append(tableau)
 +  return docu
 +
 +Ceci ajoute le tableau dans la section et retourne le document pour affichage.
  
 **Save and run the app. You'll notice that everything is about what you would expect, but there is no border for the table. That can make things difficult. Let's fix that. Again, I'll mainly use code from the example file provided by the PyRTF author. **Save and run the app. You'll notice that everything is about what you would expect, but there is no border for the table. That can make things difficult. Let's fix that. Again, I'll mainly use code from the example file provided by the PyRTF author.
Ligne 255: Ligne 369:
 Save your file as rtftable-b.py. Now, delete everything between 'doc.Sections.append(section)' and 'return doc' in the TableExample routine, and replace it with the following...** Save your file as rtftable-b.py. Now, delete everything between 'doc.Sections.append(section)' and 'return doc' in the TableExample routine, and replace it with the following...**
  
 +Sauvegardez et exécutez l'application. Vous remarquerez que tout ressemble à ce que vous attendiez, mais qu'il n'y a pas de bordures pour le tableau. Ceci peut rendre les choses difficiles à lire : réglons ce problème. À nouveau, j'utilise en grande partie le code de l'exemple fourni par l'auteur de pyRTF.
  
 +Sauvegardez votre fichier sous le nom rtfTableau-b.py, puis effacez tout ce qui est entre « docu.Sections.append(section) » et « return docu » dans la routine ExempleTableau, et remplacez-le par ce qui suit...
  
 **thin_edge  = BorderPS( width=20, style=BorderPS.SINGLE ) **thin_edge  = BorderPS( width=20, style=BorderPS.SINGLE )
Ligne 279: Ligne 395:
 table.AddRow( c1, c2, c3 )** table.AddRow( c1, c2, c3 )**
  
 +  cote_fin  = BorderPS( width=20, style=BorderPS.SINGLE )
 +  cote_epais = BorderPS( width=80, style=BorderPS.SINGLE )
 +  bord_fin  =  FramePS( cote_fin,   cote_fin,   cote_fin,   cote_fin )
 +  bord_epais = FramePS( cote_epais, cote_epais, cote_epais, cote_epais )
 +  bord_mixte = FramePS( cote_fin,   cote_epais, cote_fin,   cote_epais )
  
 +Ici nous réglons les définitions des côtés et des bords pour les encadrements.
 +
 +  tableau = Table( TabPS.DEFAULT_WIDTH * 3, TabPS.DEFAULT_WIDTH * 3, TabPS.DEFAULT_WIDTH * 3 )
 +  c1 = Cell( Paragraph( 'L1C1' ), bord_fin )
 +  c2 = Cell( Paragraph( 'L1C2' ) )
 +  c3 = Cell( Paragraph( 'L1C3' ), bord_epais )
 +  tableau.AddRow( c1, c2, c3 )
  
 **In row one, the cells in column one (thin frame) and column 3 (thick frame) will have a border around them. **In row one, the cells in column one (thin frame) and column 3 (thick frame) will have a border around them.
Ligne 301: Ligne 429:
 table.AddRow( c1, c2, c3 )** table.AddRow( c1, c2, c3 )**
  
 +Dans la première ligne, les cellules de la colonne 1 (bord_fin) et de la colonne 3(bord_epais) auront une bordure.
  
 +  c1 = Cell( Paragraph( 'L2C1' ) )
 +  c2 = Cell( Paragraph( 'L2C2' ) )
 +  c3 = Cell( Paragraph( 'L2C3' ) )
 +  tableau.AddRow( c1, c2, c3 )
 +
 +Aucune des cases n'aura de bordure dans la ligne 2.
 +
 +  c1 = Cell( Paragraph( 'L3C1' ), bord_mixte )
 +  c2 = Cell( Paragraph( 'L3C2' ) )
 +  c3 = Cell( Paragraph( 'L3C3' ), bord_mixte )
 +  tableau.AddRow( c1, c2, c3 )
  
 **Once again, cells in column 1 and three have a mixed frame in row three. **Once again, cells in column 1 and three have a mixed frame in row three.
Ligne 313: Ligne 453:
 Source code can be found at pastebin as usual. The first part can be found at http://pastebin.com/3Rs7T3D7 which is the sum of rtftest.py (a-e), and the second rtftable.py (a-b) is at http://pastebin.com/XbaE2uP7.** Source code can be found at pastebin as usual. The first part can be found at http://pastebin.com/3Rs7T3D7 which is the sum of rtftest.py (a-e), and the second rtftable.py (a-b) is at http://pastebin.com/XbaE2uP7.**
  
 +À nouveau, les cases des colonnes 1 et 3 auront une bordure mixte dans la troisième ligne.
 +
 +  section.append( tableau )
 +
 +Et voilà. Vous avez maintenant les bases pour créer des documents RTF avec du code.
 +
 +À la prochaine fois !
  
 +Le code source est disponible sur pastebin comme d'habitude. La première partie est ici : http://pastebin.com/uRVrGjkV et contient le résumé de rtftest.py (a à e), la seconde partie rtfTableeau.py (a et b) est ici : http://pastebin.com/L8DGU7Lz.
  
 ====== CODE PAGE 9 (haut) ====== ====== CODE PAGE 9 (haut) ======
  
-#!/usr/bin/env python +  #!/usr/bin/env python 
-from PyRTF import *+  from PyRTF import *
  
-def MakeExample():+  def FabriqueExemple():
     pass     pass
  
-def OpenFile(name) : +  def OuvreFichier(nom) : 
-    return file('%s.rtf'name, 'w')+    return file('%s.rtf'nom, 'w')
  
-if __name__ == '__main__' :+  if __name__ == '__main__' :
     DR = Renderer()     DR = Renderer()
-    doc MakeExample() +    docu FabriqueExemple() 
-    DR.Write(docOpenFile('rtftesta')) +    DR.Write(docuOuvreFichier('rtftesta')) 
-    print "Finished"+    print "Fini"
  
 ====== CODE PAGE 9 (bas) ====== ====== CODE PAGE 9 (bas) ======
  
-    doc = Document() +    docu = Document() 
-    ss  = doc.StyleSheet+    ss  = docu.StyleSheet
     section = Section()     section = Section()
-    doc.Sections.append(section)+    docu.Sections.append(section)
  
     p = Paragraph(ss.ParagraphStyles.Normal)     p = Paragraph(ss.ParagraphStyles.Normal)
-    p.append('This is our first test writing to a RTF file. ' +    p.append('Voici notre premier exemple de création de fichier RTF. ' 
-             'This first paragraph is in the preset style called normal ' +             'Ce premier paragraphe est dans le style prédéfini appelé normal ' 
-             'and any following paragraphs will use this style until we change it.')+             'et tous les paragraphes suivants utiliseront ce style sauf si on le change.')
     section.append(p)     section.append(p)
  
-    return doc+    return docu
  
 ====== CODE PAGE 10 ====== ====== CODE PAGE 10 ======
  
     p = Paragraph(ss.ParagraphStyles.Normal)     p = Paragraph(ss.ParagraphStyles.Normal)
-    p.append( 'It is also possible to provide overrides for elements of a style. ', +    p.append( 'Il est aussi possible de passer outre les elements d''un style. ', 
-            'For example you can change just the font ', +            'Par exemple vous pouvez modifier seulement la ', 
-            TEXT(' size to 24 point', size=48), +            TEXT(' taille de la police a 24 points', size=48), 
-            ' or', +            ' ou', 
-            TEXT(' typeface to Impact', font=ss.Fonts.Impact), +            TEXT(' son type a Impact', font=ss.Fonts.Impact), 
-            ' or even more Attributes like', +            ' ou meme d''autres attributs comme', 
-            TEXT(' BOLD',bold=True), +            TEXT(' LA GRAISSE',bold=True), 
-            TEXT(' or Italic',italic=True), +            TEXT(' ou l''italique',italic=True), 
-            TEXT(' or BOTH',bold=True,italic=True),+            TEXT(' ou LES DEUX',bold=True,italic=True),
             '.' )             '.' )
     section.append(p)     section.append(p)
Ligne 377: Ligne 525:
 ====== CODE PAGE 12 ====== ====== CODE PAGE 12 ======
  
-#!/usr/bin/env python+  #!/usr/bin/env python
  
-from PyRTF import *+  from PyRTF import *
  
-def TableExample():+  def ExempleTableau():
     pass     pass
  
-def OpenFile(name): +  def OuvreFichier(nom): 
-    return file('%s.rtf'name, 'w')+    return file('%s.rtf'nom, 'w')
  
-if __name__ == '__main__':+  if __name__ == '__main__':
     DR = Renderer()     DR = Renderer()
-    doc TableExample() +    docu ExempleTableau() 
-    DR.Write(docOpenFile('rtftable-a')) +    DR.Write(docuOuvreFichier('rtftable-a')) 
-    print "Finished"+    print "Fini"
  
issue50/tutopython.1309892259.txt.gz · Dernière modification : 2011/07/05 20:57 de fredphil91