0% found this document useful (0 votes)
8 views11 pages

Génération de PDF avec Flutter

This document shows how to generate PDF documents within a Flutter application. It covers adding the necessary packages, creating classes and files, building a basic PDF with text, and saving the generated PDF file.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views11 pages

Génération de PDF avec Flutter

This document shows how to generate PDF documents within a Flutter application. It covers adding the necessary packages, creating classes and files, building a basic PDF with text, and saving the generated PDF file.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd

import 'package:flutter/material.

dart';

void main() {
runApp(const MyApp());
}

class MyApp extends StatelessWidget {


const MyApp({[Link]});

// This widget is the root of your application.


@override
Widget build(BuildContext context) {
return MaterialApp(
title: '',
theme: ThemeData(
// This is the theme of your application.
//
// TRY THIS: Try running your application with "flutter run". You'll see
// the application has a purple toolbar. Then, without quitting the app,
// try changing the seedColor in the colorScheme below to [Link]
// and then invoke "hot reload" (save your changes or press the "hot
// reload" button in a Flutter-supported IDE, or press "r" if you used
// the command line to start the app).
//
// Notice that the counter didn't reset back to zero; the application
// state is not lost during the reload. To reset the state, use hot
// restart instead.
//
// This works for code too, not just values: Most code changes can be
// tested with just a hot reload.
colorScheme: [Link](seedColor: [Link]),
useMaterial3: true,
),
home: const MyHomePage(title: 'E-Commerce'),
);
}
}

class MyHomePage extends StatefulWidget {


const MyHomePage({[Link], required [Link]});

// This widget is the home page of your application. It is stateful, meaning


// that it has a State object (defined below) that contains fields that affect
// how it looks.

// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".

final String title;

@override
State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {


int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: [Link](context).[Link],
title: Text(
[Link],
style: TextStyle(
color: [Link],
fontStyle: [Link],
),
),
leading: Icon(
[Link],
color: [Link],
),
actions: [
Container(
margin: [Link](0, 0, 15, 0),
child: Icon(
[Link],
color: [Link],
),
),
],
),
body: Column(

children: <Widget>[
Container(
width: 100,
height: 100,
color: [Link],
),
Container(
width: 100,
height: 100,
color: [Link],
)
],
),
);

}
}
mes recherches
Développeurs Siro
Développeurs Siro

Suivre

Produire des PDF dans votre application Flutter 1/2


Photo de [Link] sur Unsplash

Produire des PDF dans votre application Flutter 1/2

Photo de Siro Devs


Développeurs Siro
·
19 novembre 2023
·
7 minutes de lecture

Table des matières


Introduction
Commencer
Étape 1 : Créer un nouveau projet Flutter
Étape 2 : Ajoutez les packages nécessaires
Étape 3 : Créez les classes/fichiers nécessaires
Étape 4 : Créer un document PDF
Étape 5 : Enregistrer le document PDF dans le stockage
Étape 6 : Affichage du document PDF
Conclusion
Introduction
Flutter devient rapidement un choix privilégié pour le développement d'applications
mobiles multiplateformes en raison de sa capacité à écrire du code une seule fois
et à le déployer universellement, garantissant ainsi des expériences utilisateur
cohérentes. Au-delà de sa compétence dans la création d'interfaces visuellement
captivantes, Flutter fournit une gamme de bibliothèques et de plugins fiables pour
gérer diverses tâches, telles que la création de documents PDF. Cet article examine
le processus de génération de documents PDF au sein d'une application Flutter,
ouvrant la voie à la production automatisée de rapports, de factures et de divers
contenus basés sur des documents.

Commencer
Pour commencer à générer des documents PDF dans une application Flutter, nous
utiliserons un package populaire appelé PDF . Ce package fournit un moyen simple de
créer des fichiers PDF par programme.

Étape 1 : Créer un nouveau projet Flutter


Ouvrez votre terminal ou votre invite de commande et créez un nouveau projet
Flutter :

COPIE

COPIE
flutter create my_pdf_app
Accédez au répertoire du projet :

COPIE
COPIE
cd my_pdf_app
Étape 2 : Ajoutez les packages nécessaires
Nous avons besoin de 3 packages pour que notre exemple simple fonctionne :

pdf : permet de créer un document complet de plusieurs pages avec des graphiques,
des images et du texte à l'aide des polices TrueType

path_provider : sert à rechercher les emplacements couramment utilisés sur le


système de fichiers

easy_pdf_viewer : nous aide à visualiser le pdf une fois généré

Pour ajouter tous ces packages à la fois, exécutez la commande suivante

COPIE

COPIE
flutter pub add easy_pdf_viewer path_provider pdf
Vous pouvez ouvrir votre [Link] pour confirmer si le pdfpackage a été
ajouté en tant que dépendance :

COPIE

COPIE
dependencies:
flutter:
sdk: flutter
easy_pdf_viewer: ^1.0.7
path_provider: ^2.1.1
pdf: ^3.10.4
Étape 3 : Créez les classes/fichiers nécessaires

Nous créons d’abord un main_screen.dartfichier pour notre page principale que nous
pouvons placer dans screensle répertoire d’une application propre.

COPIE

COPIE
import 'package:flutter/[Link]';

class MainScreen extends StatefulWidget {


const MainScreen({[Link]});

@override
State<MainScreen> createState() => MainScreenState();
}

class MainScreenState extends State<MainScreen> {

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: [Link](context).[Link],
title: const Text('My PDF App'),
),
body: Center(
child: ElevatedButton(
onPressed: () async {
// our action of PDF Generation goes here
},
child: const Text('Generate PDF'),
),
),
);
}
}
Ajustons notre [Link] vers la classe MainScreen

COPIE

COPIE
import 'package:flutter/[Link]';

import 'screens/main_screen.dart';

void main() {
runApp(const MyApp());
}

class MyApp extends StatelessWidget {


const MyApp({[Link]});

@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'My PDF App',
theme: ThemeData(
colorScheme: [Link](seedColor: [Link]),
useMaterial3: true,
),
home: const MainScreen(),
);
}
}
Créons un pdf_utils.dartfichier sous utilsle répertoire

COPIE

COPIE
import 'dart:io';

class PdfUtils {
PdfUtils._();

static Future<File> generatePDF() async {


final pdfFile = File();
}
}
Étape 4 : Créer un document PDF
Ensuite, améliorez notre fonction generatePDF afin qu'elle puisse générer un
document PDF comme nous le souhaitions.

COPIE

COPIE
import 'dart:io';

import 'package:pdf/[Link]';
import 'package:pdf/[Link]' as pw;

class PdfUtils {
PdfUtils._();
static Future<File> generatePDF() async {
final pdfFile = File();

[Link](
[Link](
margin: const [Link](10),
pageFormat: PdfPageFormat.a4,
build: ([Link] context) {
return [Link](
child: [Link](
"This is a text!",
style: [Link](
fontSize: 30,
color: PdfColors.red900,
fontWeight: [Link],
),
),
);
},
),
);
return pdfFile;
}
}
Décomposons le code étape par étape :

Instructions d'importation : les instructions d'importation apportent les


bibliothèques et les packages nécessaires pour travailler avec des PDF. dart:ioest
importé pour la manipulation de fichiers et le pdfpackage est utilisé pour créer et
manipuler des documents PDF. L' as pwalias est utilisé pour faciliter le travail
avec les pdfwidgets du package.

Génération PDF :

COPIE

COPIE
[Link](
[Link](
margin: const [Link](10),
pageFormat: PdfPageFormat.a4,
build: ([Link] context) {
return [Link](
child: [Link](
"This is a text!",
style: [Link](
fontSize: 30,
color: PdfColors.red900,
fontWeight: [Link],
),
),
);
},
),
);
Cet extrait de code ajoute une page au document PDF à l'aide de la méthode pdfdu
package addPage. Il définit les propriétés de la page, telles que les marges, le
format de la page (A4 dans ce cas) et le contenu à afficher sur la page. Dans cet
exemple, la page contient un élément de texte centré avec un style spécifique.

La buildfonction définit le contenu de la page. Dans ce cas, il renvoie un


[Link] contenant un élément texte.

Cependant, lorsque vous l'exécuterez, ce code n'affichera rien tant que vous
n'aurez pas effectué les actions suivantes décrites ci-dessous.

Étape 5 : Enregistrer le document PDF dans le stockage


Nous devrons améliorer la fonction generatePDF pour qu'elle puisse dans un premier
temps sauvegarder le PDF généré

COPIE

COPIE
import 'dart:io';
import 'dart:developer' as logger show log;

import 'package:path_provider/path_provider.dart';
import 'package:pdf/[Link]';
import 'package:pdf/[Link]' as pw;

class PdfUtils {
PdfUtils._();

static Future<File> generatePDF() async {


final pdf = [Link]();
// fetching a directory to save our pdf to
Directory filePath = await getApplicationDocumentsDirectory();

[Link](
[Link](
margin: const [Link](10),
pageFormat: PdfPageFormat.a4,
build: ([Link] context) {
return [Link](
child: [Link](
"This is a text!",
style: [Link](
fontSize: 30,
color: PdfColors.red900,
fontWeight: [Link],
),
),
);
},
),
);

final pdfFile = File('${[Link]}/my_example.pdf');


[Link]('Saved to: ${[Link]}');
await [Link](await [Link]());
return pdfFile;
}
}
Ce code Dart définit une classe utilitaire appelée PdfUtilsqui génère un document
PDF à l'aide du pdfpackage et l'enregistre dans le système de fichiers de
l'appareil. Décomposons le code étape par étape :

Importation de dépendances où j'en ai ajouté 2 autres :

dart:developer as logger: Cet alias importe la logfonction depuis la


dart:developerbibliothèque, vous permettant de journaliser les messages.

package:path_provider/path_provider.dart: Ce package est utilisé pour accéder au


système de fichiers de l'appareil, en particulier au répertoire de documents de
l'application.

Création du document PDF :

Cela commence par créer un nouvel [Link], qui représentera notre document
PDF.
Obtenir le répertoire de documents :

getApplicationDocumentsDirectory()est une fonction asynchrone du


path_providerpackage. Il récupère le répertoire de documents de l'application, qui
est un répertoire spécifique à la plateforme dans lequel vous pouvez stocker les
données utilisateur. Ce répertoire est un emplacement approprié pour enregistrer
les fichiers générés par l'utilisateur, tels que les bases de données et, dans ce
cas, les PDF.
Définition du chemin du fichier PDF :

Il spécifie le chemin du fichier où le PDF généré sera enregistré à l'aide de


File('${[Link]}/my_example.pdf'). La filePathvariable contient le chemin
d'accès au répertoire de documents de l'application.
Enregistrement du chemin du fichier :

Le code enregistre le chemin où le fichier PDF sera enregistré à l'aide de


[Link](). Cela peut être utile à des fins de débogage pour savoir où le fichier
est stocké.
Enregistrer et renvoyer le PDF :

Il enregistre le contenu PDF dans le chemin de fichier spécifié à l'aide de . La


méthode renvoie le contenu PDF sous forme de liste d'octets, qui est ensuite écrite
dans le [Link] [Link]([Link]())[Link]()
Retour du fichier :

Enfin, la méthode renvoie l' Fileobjet représentant le fichier PDF enregistré.


Étape 6 : Affichage du document PDF
Pour utiliser cette PdfUtilsclasse dans le répertoire utils, je dois appeler la
generatePDF()méthode, et elle générera un document PDF avec le contenu spécifié et
l'enregistrera dans le répertoire de documents de l'application. Je peux ensuite
utiliser ce fichier PDF généré selon mes besoins dans mon application. Le modifié
main_screen.dartressemblera désormais à ceci :

COPIE

COPIE
import 'package:easy_pdf_viewer/easy_pdf_viewer.dart';
import 'package:flutter/[Link]';

import '../utils/pdf_utils.dart';

class MainScreen extends StatefulWidget {


const MainScreen({[Link]});

@override
State<MainScreen> createState() => MainScreenState();
}

class MainScreenState extends State<MainScreen> {


late PDFDocument pdfDoc;

void openPdfViewer() {
final pdfViewer = PDFViewer(document: pdfDoc);
[Link](
context,
MaterialPageRoute(builder: (context) => pdfViewer),
);
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: [Link](context).[Link],
title: const Text('My PDF App'),
),
body: Center(
child: ElevatedButton(
onPressed: () async {
final pdf = await [Link]();
pdfDoc = await [Link](pdf);
openPdfViewer();
},
child: const Text('Generate PDF'),
),
),
);
}
}
Dans ce code, lorsque j'appuie sur le bouton "Générer un PDF", la
generatePDFfonction est appelée, qui génère le document PDF. Pour afficher le PDF,
vous pouvez utiliser des packages tels que easy_pdf_viewer, qui permettent aux
utilisateurs de visualiser les fichiers PDF dans l'application dans un écran séparé
appelé PDFViewer.

Conclusion
Comme vous l'avez vu, générer un document PDF est aussi simple que d'écrire une
arborescence de widgets normale, sauf que vous devez travailler avec [Link]
dans tous vos widgets. Les widgets habituels auxquels vous êtes habitué doivent
être dérivés du pw qui est un alias du package pdf. De plus, vous n'aurez pas
besoin d'autorisations en écriture sur votre appareil, qu'il soit Android ou iOS,
si vous avez l'intention d'enregistrer le PDF dans le répertoire de documents de
l'application, qui est un répertoire spécifique à la plate-forme.

Vous pouvez trouver le code source de l'application que j'ai créée lors de la
rédaction de ce tutoriel sur Github :

Mon exemple d'application PDF

Diapositives pour cet article

Dans le prochain article, qui fera suite à celui-ci, j'aborderai la production de


documents PDF avancés impliquant plus d'une page avec des tableaux. Bon codage !

Battement
Android
IOS
pdf
Écrit par

Développeurs Siro
Développeurs Siro
Ingénieur logiciel et rédacteur technique, meilleur en développement d'applications
mobiles Flutter, développement full stack avec Mern. D'autres domaines sont comme
Android, .Net et Qt

Suivre

PLUS D'ARTICLES

Photo de Siro Devs


Développeurs Siro
Configurer Flutter en tant que débutant
Configurer Flutter en tant que débutant
Premiers pas avec Flutter Flutter est un framework passionnant qui vous permet de
créer de magnifiques cro …

Photo de Siro Devs


Développeurs Siro
Choisir un outil multiplateforme en 2024
Choisir un outil multiplateforme en 2024
Introduction Après avoir examiné la comparaison complète entre le développement
multiplateforme et natif …

Photo de Siro Devs


Développeurs Siro
Développement multiplateforme en 2024 3/3
Développement multiplateforme en 2024 3/3
Introduction Dans mon précédent article Développement multiplateforme en 2024 2/3
j'ai exploré 3 plateformes multiplateformes …

© 2024 Développeurs Siro

Archive
·
Politique de confidentialité
·
Termes
Écrire sur Hashnode
Propulsé par Hashnode - Accueil pour les rédacteurs et lecteurs techniques

Common questions

Powered by AI

To set up a basic PDF generation feature in a Flutter app, first create a new Flutter project and include the necessary packages: pdf for creating PDF documents, path_provider for locating storage directories, and easy_pdf_viewer for displaying PDFs. Then, develop classes for PDF creation, where PdfUtils can be used to generate PDFs. Key steps include initializing a document in the PdfUtils, designing pages with widgets via Packages like 'pdf' for layout purposes, and finally saving the PDF file using path_provider. Afterward, you can display the created PDF using easy_pdf_viewer to provide users with a viewing interface .

In Flutter, state changes within a StatefulWidget are managed through the setState method. When the state or properties of a widget change and require the screen to update, setState is called to notify the Flutter framework that the widget's state has changed. Upon execution, Flutter rebuilds only the related parts of the UI, reflecting the changes. This method ensures efficient UI updates by reusing the widget tree whenever possible to minimize re-rendering costs .

The path_provider package is essential in Flutter applications generating PDF documents because it allows the app to access the file system of the device. Specifically, it helps locate the directory where documents can be stored, such as the application's document directory. This is crucial for saving the generated PDF files on the device where they can be accessed later within the app or by the user .

The easy_pdf_viewer package enhances a Flutter application's functionality by providing a straightforward way to display PDF files within the app. This package simplifies the process of rendering PDF documents on the screen, allowing users to view them without leaving the application. It aids in creating a seamless user experience, as the viewer integrates the PDF rendering and the application interface, potentially supporting features like navigation and search within PDFs .

Flutter's reactiveness, paired with widget nesting, enables efficient UI builds by minimizing the workload during UI changes. Flutter’s reactive system listens for state changes and only rebuilds the necessary parts of the UI, not the entire tree, thus optimizing performance. The widget tree design allows developers to build complex UIs by composing small, reusable widget units, facilitating easier management and scalability. This composition and reaction framework reduces redundant processing, allowing for asynchronous updates that adjust only the affected widgets, significantly improving runtime efficiency .

Flutter’s widget-based architecture allows developers to create visually complex and dynamic UIs by using a hierarchical structure where everything is a widget—from the basic UI components like buttons and text to more complex layouts. Each widget can manage its own properties, state, and rendering. This architecture supports a compositional UI design where developers can nest widgets to build complex interfaces in a flexible way, efficiently handling dynamic changes in UI due to its reactivity to state changes .

The ThemeData class in Flutter provides a centralized structure for defining visual styles across an application, enabling cohesive and consistent UI themes. It allows developers to specify colors, typography, icon themes, and more, which can be applied throughout the application. This ensures that changes in theme properties such as colors or fonts are propagated automatically, simplifying the maintenance and customization of the app's appearance. It supports the application's visual branding and helps to maintain a uniform look and feel .

Hot reload in Flutter allows developers to instantly view changes made to the code without losing the current state of the application. This means that if you modify the code, you can see the updated UI on your app without restarting it, allowing for fast iteration. In contrast, a hot restart resets the application state, restarting the entire application so all the changes apply from the start, but losing any unsaved data or state changes .

In Flutter, StatelessWidget is designed for widgets that do not require mutable state. They are immutable and rebuilt only when their parent requires it. In contrast, StatefulWidget is used for widgets that maintain mutable state across re-builds. It comprises an immutable configuration (the StatefulWidget itself) and a State object holding the state. The StatefulWidget allows more complex interactivity due to its ability to change its UI dynamically in response to state changes, while StatelessWidgets are best suited for static content or purely presentational purposes .

Flutter is advantageous for cross-platform mobile application development due to its ability to use a single codebase to target multiple platforms, reducing development time and effort. It ensures consistent user experiences across different operating systems. Its framework allows for rapid UI construction with its widget-based architecture, supporting custom interfaces. Flutter also benefits from strong community support and a wide range of plugins, such as those for handling PDFs, enhancing its functionality and developer productivity .

You might also like