flutter如何把pdf转为图片?

码云
2020-11-11 09:59

flutter中如何将pdf转为图片,从而便于阅读,这里需要使用到flutter printing包,这个包包含了很多功能,示例代码如下:

  • 依赖包导入
dependencies:
  printing: ^3.7.1
  • 示例代码
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;
import 'package:printing/printing.dart';

void main() {

  //创建文档
  final doc = pw.Document();

  //新建pdf页
  doc.addPage(pw.Page(
      pageFormat: PdfPageFormat.a4,
      build: (pw.Context context) {
        return pw.Center(
          child: pw.Text("Hello World"),
        ); // Center
      })); // Page

  //将图片加到pdf页面
  const imageProvider = const AssetImage('assets/image.png');
  final PdfImage image = await pdfImageFromImageProvider(pdf: doc.document, image: imageProvider);

  doc.addPage(pw.Page(
    build: (pw.Context context) {
      return pw.Center(
        child: pw.Image(image),
      ); // Center
    })); // Page

  //将字体应用到pdf
  final font = await rootBundle.load("assets/open-sans.ttf");
  final ttf = pw.Font.ttf(font);

  doc.addPage(pw.Page(
    build: (pw.Context context) {
      return pw.Center(
        child: pw.Text('Dart is awesome', style: pw.TextStyle(font: ttf, fontSize: 40)),
      ); // Center
    })); // Page

  //pdf保存
  final output = await getTemporaryDirectory();
  final file = File("${output.path}/example.pdf");
  await file.writeAsBytes(doc.save());

  //将pdf页面转为图片
  await for (var page in Printing.raster(document)) {
    final image = page.asImage(); // ...or page.toPng()
  }

  //将html转为pdf
  final pdf = await Printing.convertHtml(
      format: PdfPageFormat.a4,
      html: '<html><body><p>Hello!</p></body></html>',
  ));


}

 

全部评论