![]() |
VOOZH | about |
Flutter Community has created several packages to work with PDFs in our apps. In this article, we will be creating a simple PDF-generating app. This application will convert plain text to PDF.
The packages that we are going to need are listed below with their uses:
Create a new Flutter application using the command Prompt. To create a new app, write the following command and run it.
flutter create app_nameTo know more about it refer this article: Creating a Simple Application in Flutter
To add the dependency to the pubspec.yaml file, add pdf, path_provider, and flutter_pdfview as dependencies in the dependencies part of the pubspec.yaml file, as shown below:
Now, run the command below in the terminal.
flutter pub getNow that the packages are installed, first we are going to create a PDF preview screen as a new Dart file(pdf_preview_screen.dart) with the given path as shown below:
pdf_preview_screen.dart:
In this page, we have created PDFPreviewScreen as a StatelessWidgetwith the path of the PDF file as the parameter.
We have imported the necessary packages for creating the desired layout. Here we have imported 'package:pdf/widgets.dart' as pw because the material package already has a widget class.
This is the main function, which is called when the app starts:
The widget package from pdf has different types of widgets for creating the desired layout. MyHomePage() is a StatelessWidgetthat contains the code for PDF creation. Now we are going to add content to the app. We will be creating a function writeOnPdf() for this purpose:
The widgets available in this package are not the same as that available in material package. They are used to structure the layout of the document. Here we have created the document with some header, paragraphs and table to show how the basic structuring can be created.
The savePdf() function is used to save the PDF which is later on used to preview the document from the path provided. After writing the above lines of code we have to rerun the app.
The above below code is for the screen which we will get after running the app. It contains an App Bar along with a Raised Button which is used to generate and preview the PDF we have created by writing the above line of code. We pass an async function to onPressed parameter of the button as the file location is needed which returns a future as already stored while saving the file. This is also the end of the MyHomePage class.
To know more about ElevatedButton in Flutter : Flutter – ElevatedButton Widget.
main.dart: