Your experience on this site will be improved by allowing cookies
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 a plain text to PDF. The package that we are going to need are listed below with their uses:
Now let’s do some coding.
First, we have to install the necessary packages in the dependencies section of pubspec.yaml file as shown below:
Now that the packages are installed first we are going to create PDF preview screen as new dart file(pdf_preview_screen.dart) with the given path as shown below:
|
In this page we have created PDFPreviewScreen as a StatelessWidget with 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 widget for creating the desired layout. MyHomePage() is a StatelessWidget which 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.
|
Output:
0 comments