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

Prochaine révision
Révision précédente
issue159:python [2020/08/02 17:41]
auntiee créée
issue159:python [2020/08/05 23:09] (Version actuelle)
d52fr
Ligne 1: Ligne 1:
-PyFPDF is a library that allows you to generate PDF documents under Python. It was ported from FPDF ('​Free'​-PDF) to a PHP library. The repository is on github at https://​github.com/​reingart/​pyfpdf and the documentation is at https://​pyfpdf.readthedocs.io/​en/​latest/​index.html+**PyFPDF is a library that allows you to generate PDF documents under Python. It was ported from FPDF ('​Free'​-PDF) to a PHP library. The repository is on github at https://​github.com/​reingart/​pyfpdf and the documentation is at https://​pyfpdf.readthedocs.io/​en/​latest/​index.html
  
 Some of the features that this library provides are the ability to include graphic images, positional printing, lines, rectangles, ellipses, headers and footers, and the ability to create templated forms for things like invoices. Some of the features that this library provides are the ability to include graphic images, positional printing, lines, rectangles, ellipses, headers and footers, and the ability to create templated forms for things like invoices.
  
-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.**
  
-You can easily install it with pip by using:+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 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.  
 + 
 +**You can easily install it with pip by using:
  
 pip install fpdf pip install fpdf
Ligne 13: Ligne 19:
 pip install -e . pip install -e .
  
-from the clone main folder.+from the clone main folder.** 
 + 
 +Vous pouvez facilement l'​installer avec pip en utilisant : 
 + 
 +pip install fpdf 
 + 
 +ou vous pouvez cloner le dépôt github et, à partir de là, l'​installer via pip comme ceci : 
 + 
 +pip install -e 
 + 
 +depuis le dossier principal du clone.
  
-Let's jump right in and create our first example program. Enter this program into your favorite IDE and save it as “ftest1.py”. We’ll make some changes to it later on.+**Let's jump right in and create our first example program. Enter this program into your favorite IDE and save it as “ftest1.py”. We’ll make some changes to it later on.
  
 from fpdf import FPDF from fpdf import FPDF
Ligne 25: Ligne 41:
 pdf.output('​tuto1a.pdf',​ '​F'​) pdf.output('​tuto1a.pdf',​ '​F'​)
  
-Now we'll break down the program. After we import the FPDF library, we instantiate the library, by calling pdf=FPDF(), with the default options.+Now we'll break down the program. After we import the FPDF library, we instantiate the library, by calling pdf=FPDF(), with the default options.**
  
-Next, we add a page. These are pretty much the first two things that you have to do before you can do anything else.+Plongeons-nous dedans et créons notre premier exemple de programme. Saisissez ce programme dasn votre IDE favori et sauvegardez-le sous « ftest1.py ». Plus tard, nous le modifierons un peu. 
 + 
 +from fpdf import FPDF 
 + 
 +pdf = FPDF() 
 +pdf.add_page() 
 +pdf.set_font('​Arial',​ '​B',​ 16) 
 +pdf.cell(40,​ 10, 'Hello Full Circle Magazine!'​) 
 +pdf.output('​tuto1a.pdf',​ '​F'​) 
 + 
 +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.
  
 We then set the default font for the page, then we use the cell method to print some simple text, and then we call the output method to create the PDF file itself. We then set the default font for the page, then we use the cell method to print some simple text, and then we call the output method to create the PDF file itself.
Ligne 37: 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)**
  
-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'​.+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'​.
  
 Next we set the font to be used. The call is: Next we set the font to be used. The call is:
Ligne 52: Ligne 96:
 •  Times •  Times
 •  Symbol •  Symbol
-•  ZapfDingbats+•  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:+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:
      B : bold      B : bold
      I : italic      I : italic
Ligne 64: Ligne 122:
 fpdf.set_font_size(size) fpdf.set_font_size(size)
  
-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=''​)
 +
 + ​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=''​) 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...+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.
  
 h: The cell height. Default is 0. h: The cell height. Default is 0.
Ligne 89: Ligne 165:
 link: URL or identifier returned by add_link() link: URL or identifier returned by add_link()
  
-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.**
  
-Once the program is done, you can open it with your default PDF viewer. It should look something like the image above.+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.
  
 Now, we will take a look at adding the link parameter to the call method. Change the last two lines of your test program to: Now, we will take a look at adding the link parameter to the call method. Change the last two lines of your test program to:
Ligne 101: Ligne 195:
 pdf.output('​test1a.pdf',​ '​F'​) pdf.output('​test1a.pdf',​ '​F'​)
  
-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.**
  
-Save the program as “test1a” and try it again (see image below).+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).
  
 That’s great, but what if we want to do full paragraphs of text? There is a method that is close to the cell method that will handle this for us. It’s called multi_cell. The multi_cell method uses the following parameters: That’s great, but what if we want to do full paragraphs of text? There is a method that is close to the cell method that will handle this for us. It’s called multi_cell. The multi_cell method uses the following parameters:
Ligne 111: Ligne 217:
       align: str = '​J',​ fill: bool = False)       align: str = '​J',​ fill: bool = False)
  
-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.**
  
-from fpdf import FPDF+**from fpdf import FPDF
  
 import sys import sys
Ligne 121: Ligne 227:
 Of course, we have to start off with the import statements. Next, we’ll extend the fpdf class by creating a header and footer method for ourselves (borrowed from one of the demos in the documentation). See top right. Of course, we have to start off with the import statements. Next, we’ll extend the fpdf class by creating a header and footer method for ourselves (borrowed from one of the demos in the documentation). See top right.
  
-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.**
  
-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.
  
 Next, we’ll create a method to handle multi-line text. You can create different methods to handle different types of paragraphs. This, (below) again, was mostly borrowed from the documentation:​ Next, we’ll create a method to handle multi-line text. You can create different methods to handle different types of paragraphs. This, (below) again, was mostly borrowed from the documentation:​
Ligne 129: Ligne 235:
 Now, we’ll set some normal variables and add some properties to the PDF file. The properties are optional, but we’ll do it here, just to show you how to do if you ever want to (these are outside of the class, so they are not indented): Now, we’ll set some normal variables and add some properties to the PDF file. The properties are optional, but we’ll do it here, just to show you how to do if you ever want to (these are outside of the class, so they are not indented):
  
-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).**
  
-pdf.chapter_body('​demotext1.txt'​)+**pdf.chapter_body('​demotext1.txt'​)
  
 pdf.chapter_body('​demotext2.txt','​Arial','​B',​14) pdf.chapter_body('​demotext2.txt','​Arial','​B',​14)
Ligne 141: Ligne 247:
 pdf.output('​demo3.pdf',​ '​F'​) pdf.output('​demo3.pdf',​ '​F'​)
  
-Finally, the following code (again borrowed from the documentation) will open the system default PDF viewer, assuming one is set, to display the PDF we just created. This saves you and the user the need to open a file manager window, dig around for the file and open it that way. I know the code works for Linux, but haven’t tried it on a Windows machine or a Mac.+Finally, the following code (again borrowed from the documentation) will open the system default PDF viewer, assuming one is set, to display the PDF we just created. This saves you and the user the need to open a file manager window, dig around for the file and open it that way. I know the code works for Linux, but haven’t tried it on a Windows machine or a Mac.**
  
-if sys.platform.startswith("​linux"​):​+**if sys.platform.startswith("​linux"​):​
  
     os.system("​xdg-open ./​demo3.pdf"​)     os.system("​xdg-open ./​demo3.pdf"​)
Ligne 154: Ligne 260:
  
  
-So there you have it. The beginnings of the ability to create your own PDF files. I strongly suggest that you download the repository with all the source code. It gives you a great insight into the abilities of the library. The biggest thing we didn’t talk about this time is the ability of the library to use pre-defined templates. We’ll save that for the next article.+So there you have it. The beginnings of the ability to create your own PDF files. I strongly suggest that you download the repository with all the source code. It gives you a great insight into the abilities of the library. The biggest thing we didn’t talk about this time is the ability of the library to use pre-defined templates. We’ll save that for the next article.**
  
-The code files (and the text files for the last demo) have been uploaded to pastebin to make life easy for you. The links are below:+**The code files (and the text files for the last demo) have been uploaded to pastebin to make life easy for you. The links are below:
  
  ​test1.py - https://​pastebin.com/​L2vUhAfa  ​test1.py - https://​pastebin.com/​L2vUhAfa
Ligne 170: Ligne 276:
 birthdays2.py - https://​pastebin.com/​0Gwke6FD birthdays2.py - https://​pastebin.com/​0Gwke6FD
  
-Until next time; stay safe, healthy, positive and creative!+Until next time; stay safe, healthy, positive and creative!**
  
issue159/python.1596382908.txt.gz · Dernière modification: 2020/08/02 17:41 par auntiee