import 'dart:io';
import 'package:flutter/material.dart' as material ;
import 'package:flutter/services.dart';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;
class PdfParagraphApi {
static Future<void> generate(key) async {
final pdf = pw.Document();
final img = pw.MemoryImage(await rootBundle.load('assets/img.png')).buffer.asUint8List();
pdf.addPage(
pw.MultiPage(
build: (context) => <pw.Widget>[
pw.Image(img),
]),
);
}
}
我正在尝试创建一个包含图像的pdf,并使用库pdf/widgets.dart来创建我在flufs文档中找到的图像,但我遇到了一个问题。错误消息如下:未定义函数"MemoryImage"。尝试导入定义"MemoryImage"的库,将名称更正为现有函数的名称,或定义名为"MemoryImage'"的函数。dartdundefined_function
insert image into pdf not working
将pw.MemoryImage
替换为material.MemoryImage
,因为MemoryImage来自绘画库,该库包含在材质库中。
尝试替换以下导入:
import 'package:flutter/material.dart' as material ;
用这个import 'package:flutter/material.dart';
尝试以下方式:
您需要的进口
import 'package:flutter/material.dart';
import 'dart:math';
import 'dart:typed_data';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart ' as pw;
import 'dart:io';
import 'package:permission_handler/permission_handler.dart';
在顶部,您需要定义要打印的图像_imageFile = someImage
:
Uint8List? _imageFile ;
然后这是一个将图像制作成pdf并将其保存在下载文件夹中的功能
Future getPdf() async {
var random = Random();
var uniqueNum = random.nextInt(99999);
//get storage permission
Map<Permission, PermissionStatus> storagePermission = await [
Permission.storage,
].request();
pw.Document pdf = pw.Document();
pdf.addPage(
pw.Page(
pageFormat: PdfPageFormat.a4,
build: (context) {
return pw.Expanded(
child: pw.Image(pw.MemoryImage(_imageFile), fit: pw.BoxFit.contain),
);
},
),
);
String path = await ExternalPath.getExternalStoragePublicDirectory(
ExternalPath.DIRECTORY_DOWNLOADS);
String mainPath = "$path/Report$uniqueNum.pdf";
File pdfFile = File(mainPath);
pdfFile.writeAsBytesSync(await pdf.save());
}