如何将整个flutter屏幕转换为pdf



我有一个flutter电子商务应用程序,它有一个orderDetails页面,我想使用flutter pdf包将整个页面转换为pdf,因为它会更方便,因为数据是从FirebaseFirestore检索的。我有办法做到这一点吗?

sub:我想使用这个库将整个flutter屏幕转换为pdf

您可以使用此包截图捕获屏幕

然后将该图像添加到pdf文档中并保存为

import 'dart:io';
import 'dart:typed_data';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart ' as pw;
Future getPdf(Uint8List screenShot) async {
pw.Document pdf = pw.Document();
pdf.addPage(
pw.Page(
pageFormat: PdfPageFormat.a4,
build: (context) {
return pw.Expanded(
child: pw.Image(PdfImage.file(pdf.document, bytes: screenShot), fit: pw.BoxFit.contain)
);
},
),
);
File pdfFile = File('Your path + File name');
pdfFile.writeAsBytesSync(pdf.save());
}

完整详细信息:pubspec.yaml:中的负载依赖关系

screenshot: 
share_plus: 
path_provider:
permission_handler:

在您的dart文件中导入包:

import 'package:screenshot/screenshot.dart';
import 'package:share_plus/share_plus.dart';
import 'package:permission_handler/permission_handler.dart';
shareImage() async {
final uint8List = await screenshotController.capture();
String tempPath = (await getTemporaryDirectory()).path;
String fileName ="myFile";
if (await Permission.storage.request().isGranted) {
File file = await File('$tempPath/$fileName.png').create();
file.writeAsBytesSync(uint8List);
await Share.shareFiles([file.path]);
}
}

并在任何位置调用shareImage((:

GestureDetector(
onTap: (){ shareImage();},
child: ........,
),

记得把你的愿望小部件包装在:

Screenshot(
controller: screenshotController,
child: Text("This text will be captured as image"),
),
newest solution will be
shareImage() async {
final uint8List = await screenshotController.capture();
String tempPath = (await getTemporaryDirectory()).path;
String fileName =" ";>>>>>your file name between ""
File file = await File('$tempPath/$fileName" }.png').create();
file.writeAsBytesSync(uint8List!);
await Share.shareFiles([file.path]);
}
import 'dart:io';
import 'dart:typed_data';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart ' as pw;
import 'package:path_provider/path_provider.dart';
import 'package:share_plus/share_plus.dart';
Future screenToPdf(String fileName,Uint8List screenShot) async {
pw.Document pdf = pw.Document();
pdf.addPage(
pw.Page(
pageFormat: PdfPageFormat.a4,
build: (context) {
return pw.Expanded(
child: pw.Image(pw.MemoryImage(screenShot), fit: pw.BoxFit.contain),
);
},
),
);
String path = (await getTemporaryDirectory()).path;
File pdfFile = await File('$path/$fileName.pdf').create();
pdfFile.writeAsBytesSync(await pdf.save());
await Share.shareFiles([pdfFile.path]);
}

您需要

1. flutter pub add pdf
2. flutter pub add screenshot

然后

Future<void> getPdf(Uint8List screenShot) async {
final pdf = pw.Document();
pdf.addPage(
pw.Page(
pageFormat: PdfPageFormat.a4,
build: (context) {
return pw.Center(
child: pw.Image(pw.MemoryImage(screenShot), fit: pw.BoxFit.contain),
);
},
),
);
final output = File('Your path + File name');
await output.writeAsBytes(await pdf.save());
}

最新更新