Brother Cat said
Keep enthusiasm to change!
Today's article is to let you complete the creation of PDF on the client side, which can reduce the pressure on the server.
This is necessary because the server's CPU resources are precious.
Flutter plugin https://pub.dev/packages/pdf
The functions are:
- Load picture
- Write text
- Encrypt and sign files
- Pdf can also be loaded
Old iron remember to forward, Brother Mao will present more Flutter good articles~~~~
WeChat group ducafecat
b station https://space.bilibili.com/404904528
original
https://medium.com/flutterdevs/flutter-create-pdf-files-with-multiple-images-4458e813fe37
Code
https://github.com/flutter-devs/flutter_pdf_create_view_demo
reference
- https://pub.dev/packages/pdf
- https://pub.dev/packages/path_provider/versions/2.0.1
- https://pub.dev/packages/syncfusion_flutter_pdfviewer/versions/19.1.64-beta
text
Different functions in Flutter make your application rich in usefulness, and do things within the application for simple clients and improve the experience of the client. It is an expert cooperation is also an indispensable developer.
There are many software packages that can be used to open pdf in the application, some are more complicated, some are not difficult to implement, here I will clarify the method that may be the easiest to use.
In this blog, we will explore Flutter-creating PDF files of multiple images. We will implement a demo program to show how Flutter creates a pdf file with multiple images using three element packages in your Flutter application.
State management
Introduction:
PDF is probably the most famous document format for exchanging business information, because the content cannot be changed as efficiently as different configurations. This protects our information from unapproved changes. Once you know the strategy, which is usually a simple interaction, I will show you the best way to make a pdf document in your task.
For this demonstration, three basic software packages are required.
- https://pub.dev/packages/pdf
- https://pub.dev/packages/path_provider/versions/2.0.1
- https://pub.dev/packages/syncfusion_flutter_pdfviewer/versions/19.1.64-beta
Demo module:
This demo video shows how to create a pdf file with multiple images in one Flutter. It shows how the pdf file will use these three packages in your Flutter application. It shows that when the user clicks a create button, then the pdf appears, and there are multiple images according to the page. It will be displayed on your device.
implementation plan:
- Step 1: add dependencies
Add dependencies to the pubspec ーyaml file.
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
path_provider: ^2.0.1
pdf: ^3.3.0
syncfusion_flutter_pdfviewer: ^19.1.64-beta
- Step 2: add assets
Add assets to the pubspec yaml file.
assets:
- assets/images/
- Step 3: Import
import 'package:pdf/pdf.dart';
import 'package:path_provider/path_provider.dart';
import 'package:syncfusion_flutter_pdfviewer/pdfviewer.dart';
- Step 4: Run the flutter package in the root directory of the application
How to implement the code in the dart file:
You need to implement it in your code separately:
Create a new dart file screen demo. dart in the lib folder.
- First, let's create a basic PDF file:
Create a StatefulWidget in the file named PdfScreenDemo.
String pdfFile = '';
For a basic user interface, we have a raised button that enables our PDF file and a visibility widget to reveal to the PDF browser once the PDF is recorded. To view the PDF record, we will use the SfPdfViewer.file widget of the syncfusion/flutter/pdfviewer package. In this widget, we will make a document in a similar way to the PDF we made.
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Visibility(
visible: pdfFile.isNotEmpty,
child: SfPdfViewer.file(File(pdfFile),
canShowScrollHead: false, canShowScrollStatus:
false),
),
RaisedButton(
color: Colors.tealAccent,
onPressed: () {
},
child: Text('Create a Pdf File')),
],
),
The PDF package has its own widget inventory. In order to call these inventory, we need to import the PDF widget as a variable named pw.
import 'package:pdf/widgets.dart' as pw;
In order to construct a PDF format, we will call the widget by calling pw <widgetnme>.
In order to save a pdf file, we should make one. file(). This unusual widget will save the data of the generated PDF, so how about we generate a variable in \_ PdfScreenDemoState.
var pdf = pw.Document();
Lest’s create createPdfFile() method:
In this model, our idea is to make a multi-page PDF with a4 design. Because of the number of images we want to add, the number of pages may be multiple. In these order, it is a good sign to make a multi-page widget now.
Inside the construction method of the MultiPage widget, there will be a Column and Divider with a Header to separate the substantial content from the Header. In the next few stages, we will add substance under the separator in this column.
createPdfFile() {
pdf.addPage(pw.MultiPage(
margin: pw.EdgeInsets.all(10),
pageFormat: PdfPageFormat.a4,
build: (pw.Context context) {
return <pw.Widget>[
pw.Column(
crossAxisAlignment: pw.CrossAxisAlignment.center,
mainAxisSize: pw.MainAxisSize.min,
children: [
pw.Text('Create a basic PDF',
textAlign: pw.TextAlign.center,
style: pw.TextStyle(fontSize: 26)),
pw.Divider(),
]),
];
}));
}
After that, we should create a savePdfFile () method.
It is an asynchronous method, waiting for the IOS or Android platform directory. Then, the technique uses the name of the ID and the documentPath of the directory to create a record. You can name your records in any way you like, but for different PDF creations, it is smarter to give each PDF document a special name.
Finally, this method saves the PDF as a file. Path and value are assigned to the pdfFile variable in the setState strategy to refresh the UI later.
savePdfFile() async {
Directory documentDirectory = await getApplicationDocumentsDirectory();
String documentPath = documentDirectory.path;
String id = DateTime.now().toString();
File file = File("$documentPath/$id.pdf");
file.writeAsBytesSync(await pdf.save());
setState(() {
pdfFile = file.path;
pdf = pw.Document();
});
}
Important note: The appointment of Democrats is fundamental. After saving the pdf file, convert Document () into a pdf variable. If you don't do this, the pdf will try to make another recently made pdf file, which will result in a defective pdf file being made.
If you need to save the bytes of your PDF file, you can use the method below.
List<int> pdfBytes;
pdfBytes = await file.readAsBytes();
pdfFile base64Encode(pdfBytes);
In addition, use the asynchronous onPressed method:
In order to save the record, we need to first wait for the createPdfFile () strategy.
onPressed: () async {
await createPdfFile();
savePdfFile();
},
Okay, now everything is arranged. You can click the "Create a PDF File" button to view your first basic PDF document. When we run the application, we should get the output of the screen, just like the screenshot below.
- Let's create a pdf file with a picture:
In the pdf package, you can add a picture. MemoryImage. Therefore, we need to change the image to memory bytes.
First import the following packages.
import 'dart:typed_data';
import 'package:flutter/services.dart';
From then on, convert createdffile into an async method and add these two variables.
final ByteData bytes = await rootBundle.load('assets/images/null_safety.png');
final Uint8List byteList = bytes.buffer.asUint8List();
The first variable is changed to a byte on the resource picture, and the second variable is changed to a Uint8List byte list on the byte.
Then, at this point, add a pw image widget below the separator.
createPdfFile() async {
final ByteData bytes =
await rootBundle.load('assets/images/null_safety.png');
final Uint8List byteList = bytes.buffer.asUint8List();
pdf.addPage(pw.MultiPage(
margin: pw.EdgeInsets.all(10),
pageFormat: PdfPageFormat.a4,
build: (pw.Context context) {
return <pw.Widget>[
pw.Column(
crossAxisAlignment: pw.CrossAxisAlignment.center,
mainAxisSize: pw.MainAxisSize.min,
children: [
pw.Text('Flutter Pdf File with Image',
textAlign: pw.TextAlign.center,
style: pw.TextStyle(fontSize: 26)),
pw.Divider(),
]),
pw.SizedBox(height: 70),
pw.Image(
pw.MemoryImage(
byteList,
),
height: 300,
fit: pw.BoxFit.fitHeight),
];
}));
}
MemoryImage accepts byteList as position competition and transfers the image to the pdf record. Now restart the application and try to make another PDF document to view the file containing pictures. When we run the application, we should get the screen output, just like the screenshot below.
- Let's create a pdf file with multiple pictures:
In the last step of the demonstration, we will make a pdf construction technology, which can generate a record with a given variety of images. First of all, we need to develop a strategy to convert the picture into a Uint8List design.
In the status widget, create a blank list for putting pictures into Uint8list.
List<Uint8List> imagesUint8list = [];
Then, we should refactor the createdffile method and focus on another technique for obtaining image bytes.
getImageBytes(String assetImage) async {
final ByteData bytes = await rootBundle.load(assetImage);
final Uint8List byteList = bytes.buffer.asUint8List();
imagesUint8list.add(byteList);
}
Now we will make a list of type pw. A widget in the createPdfFile () technology, which generates a Column with the image title and the image itself.
final List<pw.Widget> pdfImages = imagesUint8list.map((image) {
return pw.Padding(
padding: pw.EdgeInsets.symmetric(vertical: 20, horizontal: 10),
child: pw.Column(
crossAxisAlignment: pw.CrossAxisAlignment.center,
mainAxisSize: pw.MainAxisSize.max,
children: [
pw.Text(
'Image'
' ' +
(imagesUint8list
.indexWhere((element) => element
== image) +
1)
.toString(),
style: pw.TextStyle(fontSize: 22)),
pw.SizedBox(height: 10),
pw.Image(
pw.MemoryImage(
image,
),
height: 400,
fit: pw.BoxFit.fitHeight)
]));
}).toList();
Note: It is urgent to give a specific maximum size image widget, otherwise an image may overflow the page design and cause a failed pdf creation.
Createdffile will initially create a for loop to change multiple pictures to Uint8List. Later, it will make a list of pictures with headers. Finally, pdfImages will be displayed as sub-files in the basic column of the pdf.
createPdfFile() async {
for (String image in assetImages) await getImageBytes(image);
final List<pw.Widget> images = imagesUint8list.map((image) {
return pw.Padding(
padding: pw.EdgeInsets.symmetric(vertical: 20, horizontal: 10),
child: pw.Column(
crossAxisAlignment: pw.CrossAxisAlignment.center,
mainAxisSize: pw.MainAxisSize.max,
children: [
pw.Text(
'Image'
' ' +
(imagesUint8list
.indexWhere((element) => element
== image) +
1)
.toString(),
style: pw.TextStyle(fontSize: 22)),
pw.SizedBox(height: 10),
pw.Image(
pw.MemoryImage(
image,
),
height: 400,
fit: pw.BoxFit.fitHeight)
]));
}).toList();
pdf.addPage(pw.MultiPage(
margin: pw.EdgeInsets.all(10),
pageFormat: PdfPageFormat.a4,
build: (pw.Context context) {
return <pw.Widget>[
pw.Column(
crossAxisAlignment: pw.CrossAxisAlignment.center,
mainAxisSize: pw.MainAxisSize.min,
children: [
pw.Text('Create a Simple PDF',
textAlign: pw.TextAlign.center,
style: pw.TextStyle(fontSize: 26)),
pw.Divider(),
]),
pw.Column(
crossAxisAlignment: pw.CrossAxisAlignment.center,
mainAxisSize: pw.MainAxisSize.max,
children: pdfImages),
];
}));
}
Another step is to wrap the visibility widget with SingleChildScrollView and Expanded widget.
Expanded(
child: SingleChildScrollView(
child: Visibility(
visible: pdfFile.isNotEmpty,
child: SfPdfViewer.file(File(pdfFile),
canShowScrollHead: false, canShowScrollStatus: false),
),
),
),
Now how do we press the button one last chance to make a PDF file with multiple pictures. When we run the application, we should get the output of the screen, just like the screenshot below.
Code:
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;
import 'package:flutter/material.dart';
import 'package:syncfusion_flutter_pdfviewer/pdfviewer.dart';
class PdfScreenDemo extends StatefulWidget {
@override
_PdfScreenDemoState createState() => _PdfScreenDemoState();
}
class _PdfScreenDemoState extends State<PdfScreenDemo> {
String pdfFile = '';
var pdf = pw.Document();
static const List<String> assetImages = [
'assets/images/null_safety.png',
'assets/images/stream.png',
'assets/images/error_handling.jpg'
];
List<Uint8List> imagesUint8list = [];
@override
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Expanded(
child: SingleChildScrollView(
child: Visibility(
visible: pdfFile.isNotEmpty,
child: SfPdfViewer.file(File(pdfFile),
canShowScrollHead: false, canShowScrollStatus: false),
),
),
),
RaisedButton(
color: Colors.tealAccent,
onPressed: () async {
await createPdfFile();
savePdfFile();
},
child: Text('Create a Pdf File')),
],
),
),
),
);
}
getImageBytes(String assetImage) async {
final ByteData bytes = await rootBundle.load(assetImage);
final Uint8List byteList = bytes.buffer.asUint8List();
imagesUint8list.add(byteList);
print(imagesUint8list.length);
}
createPdfFile() async {
for (String image in assetImages) await getImageBytes(image);
final List<pw.Widget> pdfImages = imagesUint8list.map((image) {
return pw.Padding(
padding: pw.EdgeInsets.symmetric(vertical: 50, horizontal: 10),
child: pw.Column(
crossAxisAlignment: pw.CrossAxisAlignment.center,
mainAxisSize: pw.MainAxisSize.max,
children: [
pw.Text(
'Image'
' ' +
(imagesUint8list
.indexWhere((element) => element == image) +
1)
.toString(),
style: pw.TextStyle(fontSize: 22)),
pw.SizedBox(height: 30),
pw.Image(
pw.MemoryImage(
image,
),
height: 300,
fit: pw.BoxFit.fitHeight)
]));
}).toList();
pdf.addPage(pw.MultiPage(
margin: pw.EdgeInsets.all(10),
pageFormat: PdfPageFormat.a4,
build: (pw.Context context) {
return <pw.Widget>[
pw.Column(
crossAxisAlignment: pw.CrossAxisAlignment.center,
mainAxisSize: pw.MainAxisSize.min,
children: [
pw.Text('Flutter Pdf File with Multiple Image',
textAlign: pw.TextAlign.center,
style: pw.TextStyle(fontSize: 26)),
pw.Divider(),
]),
pw.Column(
crossAxisAlignment: pw.CrossAxisAlignment.center,
mainAxisSize: pw.MainAxisSize.max,
children: pdfImages),
];
}));
}
savePdfFile() async {
Directory documentDirectory = await getApplicationDocumentsDirectory();
String documentPath = documentDirectory.path;
String id = DateTime.now().toString();
File file = File("$documentPath/$id.pdf");
file.writeAsBytesSync(await pdf.save());
setState(() {
pdfFile = file.path;
pdf = pw.Document();
});
}
}
Conclusion
In this article, I explained the basic structure of creating PDF files with multiple image Flutter; you can modify this code according to your choice. This is a small introduction to creating PDF files and interacting with multi-image users. From my side, it works using Flutter.
I hope this blog will provide you with sufficient information when trying to create a PDF file with multiple images in your flutter project. We will show you what the introduction is? . Make a demo program for work to create a PDF file with multiple images and display when the user clicks a create button, then the PDF occurs, with multiple images according to the page using all three packages in your Flutter application. So please try it.
© Cat brother
Past
Open source
GetX Quick Start
https://github.com/ducafecat/getx_quick_start
News client
https://github.com/ducafecat/flutter_learn_news
strapi manual translation
WeChat discussion group ducafecat
Series collection
Translation
https://ducafecat.tech/categories/%E8%AF%91%E6%96%87/
Open source project
https://ducafecat.tech/categories/%E5%BC%80%E6%BA%90/
Dart programming language basics
https://space.bilibili.com/404904528/channel/detail?cid=111585
Getting started with Flutter zero foundation
https://space.bilibili.com/404904528/channel/detail?cid=123470
Flutter actual combat from scratch news client
https://space.bilibili.com/404904528/channel/detail?cid=106755
Flutter component development
https://space.bilibili.com/404904528/channel/detail?cid=144262
Flutter Bloc
https://space.bilibili.com/404904528/channel/detail?cid=177519
Flutter Getx4
https://space.bilibili.com/404904528/channel/detail?cid=177514
Docker Yapi
https://space.bilibili.com/404904528/channel/detail?cid=130578
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。