issue159:python
Différences
Ci-dessous, les différences entre deux révisions de la page.
Les deux révisions précédentesRévision précédenteProchaine révision | Révision précédente | ||
issue159:python [2020/08/03 23:15] – d52fr | issue159:python [2020/08/09 09:48] (Version actuelle) – auntiee | ||
---|---|---|---|
Ligne 7: | Ligne 7: | ||
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:// | 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:// | ||
- | certaines | + | Certaines |
Elle est assez ancienne et il n'y a pas eu beaucoup d' | Elle est assez ancienne et il n'y a pas eu beaucoup d' | ||
Ligne 43: | Ligne 43: | ||
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.** | ||
- | Plongeons-nous dedans et créons notre premier exemple de programme. Saisissez ce programme | + | Plongeons-nous dedans et créons notre premier exemple de programme. Saisissez ce programme |
from fpdf import FPDF | from fpdf import FPDF | ||
Ligne 53: | Ligne 53: | ||
pdf.output(' | pdf.output(' | ||
- | Maintenant, décomposons le programme, Après l' | + | Maintenant, décomposons le programme. Après l' |
**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 69: | Ligne 69: | ||
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 | + | Ensuite, nous ajoutons une page. Ce sont pratiquement les deux premières |
- | 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. | + | 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, |
- | Quand nous avons créé l' | + | Quand nous avons créé l' |
- | pdf = FPDF(orientation, | + | pdf = FPDF(orientation, |
où : | où : | ||
Ligne 81: | Ligne 81: | ||
orientation = (p: | orientation = (p: | ||
- | units = (pt:point, mm:millimeter, cm:centimeter, in:inch) (la valeur par défaut est mm) | + | unités |
- | format = (A3, A4, A5, Letter, Legal) (A4 est la valeur par défaut) (voir ci-dessous) | + | 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' | **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' | ||
Ligne 98: | Ligne 98: | ||
• ZapfDingbats** | • ZapfDingbats** | ||
- | Si vous avez besoin d'une taille de page personnalisée, | + | Si vous avez besoin d'une taille de page personnalisée, |
Ensuite, nous réglons la police à utiliser. L' | Ensuite, nous réglons la police à utiliser. L' | ||
- | < | + | fpdf.set_font(family, |
- | La méthode set-font vous permet de spécifier la police à utiliser pour les lignes suivantes du texte à restituer. | + | La méthode set-font vous permet de spécifier la police à utiliser pour les lignes suivantes du texte à restituer. |
• Courier (largeur fixe) | • Courier (largeur fixe) | ||
- | • Helvetica | + | • Helvetica |
• Times | • Times | ||
• Symbol | • Symbol | ||
Ligne 124: | 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.** | ||
- | **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, | + | Ces 5 polices fournissent une largeur fixe, une sans-serif, une serif et deux polices symboliques. Le paramètre des familles de polices est insensible à la casse de même que le style de la police. Ces styles peuvent être : |
+ | B : gras | ||
+ | I : italique | ||
+ | U : souligné | ||
+ | vide : normal | ||
+ | |||
+ | Note : si vous voulez changer la taille de la police dans le document, la famille ou le style, vous pouvez appeler : | ||
+ | |||
+ | fpdf.set_font_size(size) | ||
+ | |||
+ | Si vous voulez utiliser une police spéciale pour une raison quelconque, en dehors du lot de polices fournies en standard, vous pouvez utiliser la méthode add_font. Cependant, elle est assez compliquée, | ||
+ | |||
+ | **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, | ||
fpdf.cell(w, | fpdf.cell(w, | ||
| | ||
+ | |||
+ | 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, | ||
+ | |||
+ | fpdf.cell(w, | ||
+ | |||
+ | 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 148: | 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' | ||
+ | |||
+ | 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 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 identifiant retourné par add_link(). | ||
+ | |||
+ | Enfin, nous appelons pdf.output pour un rendu du fichier et sa sauvegarde sous le nom de fichier spécifié (qui est le paramètre « F »). Il y a d' | ||
**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 160: | 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 programme terminé, vous pouvez l' | ||
+ | |||
+ | Maintenant, nous regarderons l' | ||
+ | |||
+ | pdf.cell(0, 10, 'Hello Full Circle Magazine!', | ||
+ | |||
+ | 1, | ||
+ | |||
+ | pdf.output(' | ||
+ | |||
+ | Notez que nous avons ajouté tous les paramètres de la méthode cell. Dans cette version, nous ajouterons une bordure avec un remplissage transparent, | ||
**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 170: | 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 (voir l' | ||
+ | |||
+ | C'est super, mais que se passe-t-il si nous voulons faire de 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 suivants : | ||
+ | |||
+ | pdf.multi_cell(w: | ||
+ | |||
+ | align: str = ' | ||
+ | | ||
+ | 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 passerons outre certaines fonctions intégrées (ce sont simplement des souches qui sont conçues pour être implémentées dans votre code) qui sont header (en-tête) et footer (pied de page) et en ajouter d' | ||
**from fpdf import FPDF | **from fpdf import FPDF | ||
Ligne 180: | 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 | ||
+ | |||
+ | Bien sûr, nous devons commencer par les déclarations d' | ||
+ | |||
+ | La méthode header, comme vous l'avez peut-être deviné, crée une en-tête qui est (principalement) centrée horizontalement et est constituée du titre de notre document. D' | ||
+ | |||
**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 188: | Ligne 257: | ||
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), | ||
+ | |||
+ | Maintenant, nous paramétrerons quelques variables normales et ajouterons des propriétés au fichier PDF. Les propriétés sont optionnelles, | ||
+ | |||
+ | 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' | ||
**pdf.chapter_body(' | **pdf.chapter_body(' | ||
Ligne 200: | Ligne 277: | ||
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.** | ||
+ | |||
+ | pdf.chapter_body(' | ||
+ | |||
+ | pdf.chapter_body(' | ||
+ | |||
+ | pdf.chapter_body(' | ||
+ | |||
+ | Maintenant, nous restituons et sauvegardons le fichier PDF : | ||
+ | |||
+ | pdf.output(' | ||
+ | |||
+ | Enfin, le code suivant (emprunté à nouveau à la documentation) ouvrira la visionneuse de document PDF par défaut du système, en supposant qu'il y en ait une de définie, pour afficher le PDF que nous venons de créer. Pour vous et l' | ||
**if sys.platform.startswith(" | **if sys.platform.startswith(" | ||
Ligne 213: | Ligne 302: | ||
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.** | ||
+ | |||
+ | if sys.platform.startswith(" | ||
+ | |||
+ | os.system(" | ||
+ | |||
+ | else: | ||
+ | |||
+ | os.system(" | ||
+ | | ||
+ | Maintenant que le PDF est (je l' | ||
+ | |||
+ | Voilà, c'est tout. Les débuts d'une possibilité de créer vos propres fichiers PDF. Je vous suggère instamment de télécharger le dépôt avec tout le code source. Il vous donne une bonne vue des possibilités de la bibliothèque. La chose la plus importante dont nous n' | ||
**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: | ||
Ligne 229: | Ligne 330: | ||
Until next time; stay safe, healthy, positive and creative!** | Until next time; stay safe, healthy, positive and creative!** | ||
+ | |||
+ | Les fichiers de code (et les fichiers texte de la dernière démo) ont été téléversés sur pastebin pour vous simplifier la vie. Voici les liens : | ||
+ | |||
+ | test1.py - https:// | ||
+ | |||
+ | test1a.py - https:// | ||
+ | |||
+ | demo3.py - https:// | ||
+ | | ||
+ | demotext1.txt - https:// | ||
+ | | ||
+ | demotext2.txt - https:// | ||
+ | | ||
+ | birthdays2.py - https:// | ||
+ | |||
+ | Jusqu' | ||
issue159/python.1596489306.txt.gz · Dernière modification : 2020/08/03 23:15 de d52fr