Outils pour utilisateurs

Outils du site


issue159:python

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
Prochaine révisionLes deux révisions suivantes
issue159:python [2020/08/03 08:14] d52frissue159:python [2020/08/07 08:12] d52fr
Ligne 5: Ligne 5:
 It's rather old, and there hasn't been much activity recently. In fact, the last update to the repository was about 3 years ago.** It's rather old, and there hasn't been much activity recently. In fact, the last update to the repository was about 3 years ago.**
  
-PyFPDF est une bibliothèque qui vous permet de générer des documents PDF osus Python. Elle a été portée à partir de FPDF (« Free » -PDF) dans une bibliothèque en PHP. Le dépôt est sur github à https://github.com/reingart/pyfpdf et la documentation est à https://pyfpdf.readthedocs.io/en/latest/index.html+PyFPDF est une bibliothèque qui vous permet de générer des documents PDF sous Python. Elle a été portée à partir de FPDF (« Free » -PDF) dans une bibliothèque en PHP. Le dépôt est sur github à https://github.com/reingart/pyfpdf et la documentation est à https://pyfpdf.readthedocs.io/en/latest/index.html
  
-certaines des fonctionnalités que cette bibliothèque fournit sont la possibilité d'inclure des images graphiques, des impressions à une position définie, des lignes, rectangles, ellipses, entêtes et pieds de page, et la possinbilité de créer des formulaires pré-définis pour des choses comme des factures.+certaines des fonctionnalités que cette bibliothèque fournit sont la possibilité d'inclure des images graphiques, des impressions à une position définie, des lignes, rectangles, ellipses, entêtes et pieds de page, et la possibilité de créer des formulaires pré-définis pour des choses comme des factures.
  
 Elle est assez ancienne et il n'y a pas eu beaucoup d'activité récente. En fait, la dernière mise à jour dans le dépôt date d'environ 3 ans.  Elle est assez ancienne et il n'y a pas eu beaucoup d'activité récente. En fait, la dernière mise à jour dans le dépôt date d'environ 3 ans. 
Ligne 53: Ligne 53:
 pdf.output('tuto1a.pdf', 'F') pdf.output('tuto1a.pdf', 'F')
  
-Maintenant, décomposerons le programme, Après l'import de la bibliothèque FPDF, nous instancions la bibliothèque, par l'appel pdf=FPDF(), avec les options par défaut.+Maintenant, décomposons le programme, Après l'import de la bibliothèque FPDF, nous instancions la bibliothèque, par l'appel pdf=FPDF(), avec les options par défaut.
  
 **Next, we add a page. These are pretty much the first two things that you have to do before you can do anything else. **Next, we add a page. These are pretty much the first two things that you have to do before you can do anything else.
Ligne 65: Ligne 65:
 orientation = (p:portrait, l:landscape) (default = Portrait) orientation = (p:portrait, l:landscape) (default = Portrait)
  
-  units = (pt:point, mm:millimeter, cm:centimeter, in:inch) (default is mm)+units = (pt:point, mm:millimeter, cm:centimeter, in:inch) (default is mm)
  
- format = (A3, A4, A5, Letter, Legal) (default is A4) (see below)**+format = (A3, A4, A5, Letter, Legal) (default is A4) (see below)** 
 + 
 +Ensuite, nous ajoutons une page. Ce sont pratiquement les deux premières choses que vous devez faire avant que vous puissiez faire autre chose. 
 + 
 +Ensuite, nous paramétrons la police par défaut pour la page ; après, nous utilisons la méthode cell pour imprimer un simple texte et, alors, nous appelons la méthode output pour créer le fichier pdf lui-même. 
 + 
 +Quand nous avons créé l'objet PDF, come je l'ai dit, nous avons utilisé les paramètres par défaut. Voici les options : 
 + 
 +pdf = FPDF(orientation, units, page format) 
 + 
 +où : 
 +       
 +orientation = (p:portrait, l:landscape) (valeur par défaut = Portrait) 
 + 
 +  units = (pt:point, mm:millimeter, cm:centimeter, in:inch) (la valeur par défaut est mm) 
 + 
 + format = (A3, A4, A5, Letter, Legal) (A4 est la valeur par défaut) (voir ci-dessous)
  
 **If you need a custom page size, you can send a tuple with the width and height in the given units. If you are using Portrait mode, the order should be (width, height), but if you are using landscape, it should be (height, width). Also, try as I might, I couldn't get the units to work with the inch option. Nothing seems to render, so I stick with 'mm'. **If you need a custom page size, you can send a tuple with the width and height in the given units. If you are using Portrait mode, the order should be (width, height), but if you are using landscape, it should be (height, width). Also, try as I might, I couldn't get the units to work with the inch option. Nothing seems to render, so I stick with 'mm'.
Ligne 81: Ligne 97:
 •  Symbol •  Symbol
 •  ZapfDingbats** •  ZapfDingbats**
 +
 +Si vous avez besoin d'une taille de page personnalisée, vous pouvez envoyer un tuple avec la largeur et la hauteur dans les unités données. Si vous utilisez le mode Portrait, l'ordre devrait être (largeur, hauteur), mais, si vous utilisez le paysage, il devrait être (hauteur, largeur). De plus, essayez comme je le fit, je n'ai pas réussi à faire marcher les unités avec l'option « inch » (pouce). Rien en semblait être restitué ; je suis donc resté aux mm.
 +
 +Ensuite, nous réglons la police à utiliser. L'appel est :
 +
 +<nowiki>fpdf.set_font(family, style='', size = 0)</nowiki>
 +
 +La méthode set-font vous permet de spécifier la police à utiliser pour les lignes suivantes du texte à restituer. Cependant, ce n'est pas aussi libre que vous pourriez le penser. Il y a cinq polices normales utilisables qui sont pré-définies (sauf si vous ajoutez « add_font » en premier). Les voici :
 +• Courier (largeur fixe)
 +• Helvetica or Arial
 +• Times
 +• Symbol
 +• ZapfDingbats
 +
  
 **These 5 fonts provide fixed width, sans-serif, serif, and two symbolic fonts. The font family parameter is case insensitive as well as the font style. Those styles can be: **These 5 fonts provide fixed width, sans-serif, serif, and two symbolic fonts. The font family parameter is case insensitive as well as the font style. Those styles can be:
Ligne 94: Ligne 124:
 If you want to use a special font for some reason, outside of the standard font set provided, you can use the add_font method. However, it is fairly difficult, so we'll discuss it in a future article. In the meantime, you can look at the documentation to see how to do it.** If you want to use a special font for some reason, outside of the standard font set provided, you can use the add_font method. However, it is fairly difficult, so we'll discuss it in a future article. In the meantime, you can look at the documentation to see how to do it.**
  
-**Nowwe'll take a look at the cell methodthat allows you to place the text to be renderedThis method will print a rectangular area with optional borders, possibly background and foreground colors, and the character string. The text can be aligned to the right or left or can be centered. When the call is finished, the current position moves to the right or to the next line, depending on a parameter passed, and allows for an optional link to be attached to the text. The format of the method parameters is fairly comprehensive, but, luckily, the author of the library has set a number of defaults, so it isn't as bad as it could be.+Parmi ces 5 polices sont fournies une à largeur fixeune sans-serifune serif et deux polices symboliquesLe paramètre des familles de polices est insensible à la casse de même qu'au style de policeCes styles peuvent être :
  
 +     B : gras
 +     I : italique
 +     U : sousligné
 +     vide : normal
 +     
 +Note : si vous voulez changer la taille de la police dans le document, changer la famille ou le style, vous pouvez appeler :
 +
 +fpdf.set_font_size(size)
 +
 +Si vous voulez utiliser une police spéciale pour un raison quelconque, en dehors de u lot de polices fournies en standard, vous pouvez utiliser la méthode add_font. Cependant, elle est assez compliquée, donc nous en parlerons dans en un article futur. Entre temps, vous pouvez regarder la documentation pour voir comment le faire.
 +
 +**Now, we'll take a look at the cell method, that allows you to place the text to be rendered. This method will print a rectangular area with optional borders, possibly background and foreground colors, and the character string. The text can be aligned to the right or left or can be centered. When the call is finished, the current position moves to the right or to the next line, depending on a parameter passed, and allows for an optional link to be attached to the text. The format of the method parameters is fairly comprehensive, but, luckily, the author of the library has set a number of defaults, so it isn't as bad as it could be.
  
 fpdf.cell(w, h=0, txt='', border=0, ln=0, align='', fill=false, link='') fpdf.cell(w, h=0, txt='', border=0, ln=0, align='', fill=false, link='')
  
  We'll take a look at each parameter in a bit more depth...**  We'll take a look at each parameter in a bit more depth...**
 +
 +Maintenant, nous allons regarder la méthode cell, qui vous permet de placer le texte à restituer. cette méthode imprimera une zone rectangulaire avec des bordures optionnelles, un possibilité de couleurs de fond et de premier-plan, et la chaîne de caractères. Le texte peut être aligné à droite ou à gauche, ou peut être centré. Quand l'appel est fini, la possition actuelle se déplace à d'autre ou sur la ligne suivante, suivant comment un paramètre a été passé, et vous donne la possibilité d'attacher un lien optionel au texte. Le format des paramètres de la méthode se comprend plutôt bien, mais, par chance, l'auteur de la bilbiothèque a placé un certain nombre de défauts ; aussi, elle n'est pas aussi mauvaise qu'elle l'aurait pu.
 +
 +fpdf.cell(w, h=0, txt='', border=0, ln=0, align='', fill=false, link='')
 +
 +Regardons chacun des paramètres un peu plus en détail...
    
 **w: Cell width. If this value is 0, the cell will extend to the right margin. **w: Cell width. If this value is 0, the cell will extend to the right margin.
Ligne 118: Ligne 166:
  
 Finally, we call pdf.output to render the file and save it as the filename specified (which is the ‘F’ parameter). There are other parameters that you can research in the document.** Finally, we call pdf.output to render the file and save it as the filename specified (which is the ‘F’ parameter). There are other parameters that you can research in the document.**
 +
 +w - largeur de la cellule. Si cette valeur est 0, la cellule s'étendra jusqu'à la marge droite.
 +
 +h - hauteur de la cellule. La valeur par défaut est 0.
 +
 +txt - la chaîne à imprimer.
 +
 +border - 0 : pas de bordure. 1 ; cadre (ou une chaîne contenant quelles sont les lignes du cadre à restituer)
 +
 +ln - 0 : à droite. 1 : au début de la ligne suivante. 2 : en dessous.
 +
 +align - « L » : alignement à gauche, « C » : centré, « R » : alignement à droite
 +
 +fill - True : fond coloré. False : transparent. Valeur par défaut = False
 +
 +link - URL ou indentifiant retourné par add_link()
 +
 +Enfin, nous appelons pdf.output pour un rendu du fichier et sa souvegarde sous le nom de fichier spécifié (qui est le paramètre « F »). Il y a d'autres paramètres, que vous pouvez chercher dans le document.
  
 **Once the program is done, you can open it with your default PDF viewer. It should look something like the image above. **Once the program is done, you can open it with your default PDF viewer. It should look something like the image above.
Ligne 130: Ligne 196:
  
 Notice that we added all the parameters for the cell method. In this version, we will be adding a border with transparent fill, make the text centered, have the cell go from the far left extending to the far right of the page, set the next text line to be on the line below, and added a link to the Full Circle Magazine website, when you click on the text. We also changed the output file name.** Notice that we added all the parameters for the cell method. In this version, we will be adding a border with transparent fill, make the text centered, have the cell go from the far left extending to the far right of the page, set the next text line to be on the line below, and added a link to the Full Circle Magazine website, when you click on the text. We also changed the output file name.**
 +
 +Une fois le proramme terminé, vous pouvez l'ouvrir avec votre visionneuse de PDF par défaut. IL devrait ressembler à quelque chose comme l'image ci-dessus.
 +
 +Maintenant, nous regarderons l'ajout du paramètre link (lien) à la méthode cell. Canfez les deux dernières lignes de votre programme de test pour :
 +
 +pdf.cell(0, 10, 'Hello Full Circle Magazine!',
 +
 +    1,1,'C',0,"http://fullcirclemagazine.org")
 +
 +pdf.output('test1a.pdf', 'F')
 +
 +Notez que nous avons ajouté tous les paramètres à la méthode cell. Dans cette version, nous ajouterons une bordure avec un remplissage transparent, centrerons le texte, la cellule s'étendant de l'extrême gauche à l'extrême droite de la page, paramètrerons pour que la prochaine ligne soit sur la ligne du dessous et ajouterons un lien vers le site Web du Full Circle Magazine, quand nous cliquons sur le texte. Nous changerons aussi le nom du fichier de sortie.
  
 **Save the program as “test1a” and try it again (see image below). **Save the program as “test1a” and try it again (see image below).
Ligne 140: Ligne 218:
  
 It can be used in place of the cell method, but we are going to do something special to demonstrate this. This time, we will extend and override some of the builtin functions (that are simply stubs that are designed to be implemented in your code) which are header and footer, and add a couple of our own. Open another blank file in your IDE and name the file Demo3.py.** It can be used in place of the cell method, but we are going to do something special to demonstrate this. This time, we will extend and override some of the builtin functions (that are simply stubs that are designed to be implemented in your code) which are header and footer, and add a couple of our own. Open another blank file in your IDE and name the file Demo3.py.**
 +
 +Sauvegardez le programme comme « test1a » et essayez-le à nouveau (voie l'image ci-dessous).
 +
 +C'est super, mais que se passe-t-il si nous voulons faire des longs paragraphes de texte ? Il y a une méthode qui est proche de la méthode cell qui le gèrera pour nous. Elle est appelée multi_cell. la méthode multi_cell utilise les paramètres suivant :
 +
 +pdf.multi_cell(w: float, h: float, txt: str, border = 0, 
 +
 +      align: str = 'J', fill: bool = False)
 +      
 +Elle peut être utilisée à la place de la méthode cell, mais nous allons faire quelque chose de spécial pour la démonstration. Cette fois-ci, nous étendrons et recouvrirons certaines fonctions intégrées (ce sont simplement des souches que sont conçues pour être implémentées dans votre code) qui sont header (entête) et footer (pied de page) et ajouter certainesd enotre cru. Ouvrez un nouveau fichier vide dans votre IDE et nommez ce fichier Demo3.py.
  
 **from fpdf import FPDF **from fpdf import FPDF
Ligne 150: Ligne 238:
  
 The header method, as you might guess, creates a header that is (mostly) centered horizontally and consists of the title of our document. First, we set the font, then we use the get_string_width() method to calculate the width in whatever unit value that was set for the title when it would be rendered. That is then placed in a cell starting at the proper place at the top of the page. You could use a “0” in the cell method in place of the “w” and not use the set_x method, forcing the cell to start at a x position of 0 and extending to the right margin, but you really should see this alternate method.** The header method, as you might guess, creates a header that is (mostly) centered horizontally and consists of the title of our document. First, we set the font, then we use the get_string_width() method to calculate the width in whatever unit value that was set for the title when it would be rendered. That is then placed in a cell starting at the proper place at the top of the page. You could use a “0” in the cell method in place of the “w” and not use the set_x method, forcing the cell to start at a x position of 0 and extending to the right margin, but you really should see this alternate method.**
 +
 +from fpdf import FPDF
 +
 +import sys
 +
 +import os
 +
 +La méthode header, comme vous l'avez peut-être deviné, crée une entête qui est (largement) centrée horizontalement et est consistuée du titre de notre document. D'abord, nous paramétrons la police, puis nous utilisons la méthode get_string_width() pour calculer la largeur dans la valeur d'unité qui a été  réglée pour le titre lorsqu'il sera rendu. Puis  c'est mis dans une cellule commençant à l'endroit approprié en haut de la page.  Vous pourriez utiliser un « 0 » dans la méthode cdll à la place du « w » et ne pas utiliser la méthode set_x, forçant la cellule à commencer à la position x valant 0 et s'étendant jusqu'à la marge droite, mais mais vous devriez vraiment regarder cette autre méthode.
 +
  
 **The footer method handles placing the page number at the very bottom of the page, in this case (middle right) 15 mm from the bottom. You can set the color of the font, but I commented it out. **The footer method handles placing the page number at the very bottom of the page, in this case (middle right) 15 mm from the bottom. You can set the color of the font, but I commented it out.
Ligne 158: Ligne 255:
  
 Now, we send each group of text into the chapter_body() method we just created. For the demo, I chose some text from last month’s article and one of the programs to try to demonstrate how to use different font settings *(top right).** Now, we send each group of text into the chapter_body() method we just created. For the demo, I chose some text from last month’s article and one of the programs to try to demonstrate how to use different font settings *(top right).**
 +
 +La méthode footer gère la disposition du numéro de page tout en bas de la page, dans ce cas (au milieu à droite) à 15 mm du bas. Vous pouvez régler la couleur de la police, mais je l'ai commenté.
 +
 +Ensuite, nous créerons une méthode pour gérer un texte multi-lignes. Vous pouvez créer différentes méthodes pour gérer différents types de paragraphes. Ceci (ci-dessous), à nouveau, a été emprunté à la documentation.
 +
 +Maintenant, nous paramétrerons quelques variables normales et ajouterons des propriétés au fichier PDF. La propriétés sont optionnelles, mais nous les ferons ici simplement pour montrer comment faire au cas où vous le voudriez (c'est en dehors de la classe ; aussi, ce n'est pas indenté) :
 +
 +Maintenant, nous envoyons chaque groupe de texte dans la méthode chapter_body() que nous venons de créer. Pour la démo, j'ai choisi du texte de l'article du mois dernier et un des programmes pour essayer de montrer comment utiliser ddifférents réglages des polices *(en haut à droite).
  
 **pdf.chapter_body('demotext1.txt') **pdf.chapter_body('demotext1.txt')
issue159/python.txt · Dernière modification : 2020/08/09 09:48 de auntiee