Flutter PDF框架:
pub:https://pub.dev/packages/pdf
导入: pdf: ^3.7.1
写文本
static Future<String?> writeTxtToPdf(String text, String saveFile) async {
File file = new File(saveFile);
if(file.existsSync()) {
return saveFile;
}
// 中文字库设置,否则中文解析会报错
final ttf = pw.Font.ttf(await rootBundle.load('local_files/fonts/Alibaba-PuHuiTi-Regular.ttf'));
final pdf = pw.Document( );
//分页
pdf.addPage(pw.MultiPage(
footer: (pw.Context context) {
return pw.Container(
alignment: pw.Alignment.centerRight,
margin: const pw.EdgeInsets.only(top: 1.0 * PdfPageFormat.cm),
child: pw.Text(
'${context.pageNumber} / ${context.pagesCount}',
style: pw.TextStyle(fontSize: 12, color: PdfColors.grey))
);
},
build: (pw.Context context) {
return [
pw.Column(
crossAxisAlignment: pw.CrossAxisAlignment.start,
children: _splitText(text, ttf)
)
];
}
));
await file.writeAsBytes(await pdf.save());
return saveFile;
}
static List<pw.Widget> _splitText(String text, pw.Font ttf) {
pw.TextStyle style = pw.TextStyle(font: ttf, fontSize: 18);
List list = text.split(’\n’);
List<pw.Widget> widgets = [];
list.forEach((element) {
widgets.add(pw.Text(element, style: style));
});
return widgets;
}
//写入图片
static Future<String?> writeImagesToPdf(List imgPathList, String saveFile) async {
File file = new File(saveFile);
if(file.existsSync()) {
return saveFile;
}
final pdf = pw.Document();
pdf.addPage(pw.MultiPage(
footer: (pw.Context context) {
return pw.Container(
alignment: pw.Alignment.centerRight,
margin: const pw.EdgeInsets.only(top: 1.0 * PdfPageFormat.cm),
child: pw.Text(
'${context.pageNumber} / ${context.pagesCount}',
style: pw.TextStyle(fontSize: 12, color: PdfColors.grey))
);
},
build: (pw.Context context) {
return _splitImages(imgPathList);
}
));
await file.writeAsBytes(await pdf.save());
return saveFile;
}
static List<pw.Widget> _splitImages(List imgPathList) {
List<pw.Widget> widgets = [];
imgPathList.forEach((element) {
// widgets.add(pw.Image(pw.ImageImage(im.decodeImage(File(element).readAsBytesSync())!)));
widgets.add(pw.Column(
children: [
//本地图片,另外api还有保存网络图netImage,资源图等
pw.Image(pw.MemoryImage(File(element).readAsBytesSync()),width: 500,height: 300),
pw.SizedBox(height: 30)
]
));
});
return widgets;
}