【发布时间】:2019-02-12 06:01:39
【问题描述】:
我在 Flutter 中开发 pdf 生成器应用程序,但是当我想将图像添加到 pdf 时,它需要很长时间,我还想知道如何添加多个图像。
我正在使用 3 个库,图像选择器 - pdf - 打印
这是我的代码:
Future getImage() async {
var image = await ImagePicker.pickImage(source: ImageSource.gallery);
final tempDir = await getTemporaryDirectory();
final path = tempDir.path;
int rand = new Math.Random().nextInt(10000000);
imge.Image imagee = imge.decodeImage(image.readAsBytesSync());
imge.Image smallerImage = imge.copyResize(imagee, 500);
setState(() {
var _image = new File('$path/img_$rand.jpg')..writeAsBytesSync(imge.encodeJpg(smallerImage, quality: 85));
_sharePdf(_image);
});
}
PDFDocument _generateDocument(File _image) {
final pdf = new PDFDocument(deflate: zlib.encode);
final page = new PDFPage(pdf, pageFormat: PDFPageFormat.LETTER);
final g = page.getGraphics();
final font = new PDFFont(pdf);
final top = page.pageFormat.height;
print(top);
imge.Image img = imge.decodeImage(_image.readAsBytesSync());
PDFImage image = new PDFImage(
pdf,
image: img.data.buffer.asUint8List(),
width: img.width,
height: img.height);
g.drawImage(image, 100.0, top - 150.0, 80.0, 100.0);
return pdf;
}
void _sharePdf(File _image) {
print("Share ...");
final pdf = _generateDocument(_image);
// Calculate the widget center for iPad sharing popup position
final RenderBox referenceBox =
shareWidget.currentContext.findRenderObject();
final topLeft =
referenceBox.localToGlobal(referenceBox.paintBounds.topLeft);
final bottomRight =
referenceBox.localToGlobal(referenceBox.paintBounds.bottomRight);
final bounds = new Rect.fromPoints(topLeft, bottomRight);
Printing.sharePdf(document: pdf, bounds: bounds);
}
然后我调用函数getImage()。
在我选择图像后,需要 2-3 分钟,所有内容都会冻结,然后您可以共享 pdf!
【问题讨论】:
-
您是否尝试使用断点调试您的代码以找出需要这么长时间的原因?
-
是的,它是pdf中图像的生成,因为选择图像很快
-
这部分?
writeAsBytesSync(imge.encodeJpg(smallerImage, quality: 85)) -
当它调用 _sharePdf(_image);冻结,压缩和获取图像正常
-
你能提供一个完整但最小的复制品吗?
标签: image pdf optimization dart flutter