我们不需要额外的插件就可以做到这一点,因为网络浏览器本身可以显示(或下载)pdf
文档。
更新为 pdf 2.0.0 及更高版本
由于方法save https://pub.dev/documentation/pdf/latest/pdf/PdfDocument/save.html现在返回 Future,按钮处理程序变得异步(当然你可以使用未来建造者或者是其他东西)。
import 'dart:html' as html;
import 'package:flutter/material.dart';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;
class PdfLabPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
final pdf = pw.Document();
pdf.addPage(pw.Page(
pageFormat: PdfPageFormat.a4,
build: (pw.Context context) {
return pw.Center(
child: pw.Text('Hello World'),
);
}));
return Scaffold(
appBar: AppBar(),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: () async {
final bytes = await pdf.save();
final blob = html.Blob([bytes], 'application/pdf');
final url = html.Url.createObjectUrlFromBlob(blob);
html.window.open(url, '_blank');
html.Url.revokeObjectUrl(url);
},
child: Text('Open'),
),
ElevatedButton(
onPressed: () async {
final bytes = await pdf.save();
final blob = html.Blob([bytes], 'application/pdf');
final url = html.Url.createObjectUrlFromBlob(blob);
final anchor = html.AnchorElement()
..href = url
..style.display = 'none'
..download = 'some_name.pdf';
html.document.body?.children.add(anchor);
anchor.click();
html.document.body?.children.remove(anchor);
html.Url.revokeObjectUrl(url);
},
child: Text('Download'),
),
],
),
),
);
}
}
原答案
import 'package:flutter/material.dart';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;
import 'package:universal_html/html.dart' as html;
class PdfDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
final pdf = pw.Document();
pdf.addPage(pw.Page(
pageFormat: PdfPageFormat.a4,
build: (pw.Context context) {
return pw.Center(
child: pw.Text("Hello World"),
);
}));
final bytes = pdf.save();
final blob = html.Blob([bytes], 'application/pdf');
return Scaffold(
appBar: AppBar(),
body: Center(
child: Column(
children: <Widget>[
RaisedButton(
child: Text("Open"),
onPressed: () {
final url = html.Url.createObjectUrlFromBlob(blob);
html.window.open(url, "_blank");
html.Url.revokeObjectUrl(url);
},
),
RaisedButton(
child: Text("Download"),
onPressed: () {
final url = html.Url.createObjectUrlFromBlob(blob);
final anchor =
html.document.createElement('a') as html.AnchorElement
..href = url
..style.display = 'none'
..download = 'some_name.pdf';
html.document.body.children.add(anchor);
anchor.click();
html.document.body.children.remove(anchor);
html.Url.revokeObjectUrl(url);
},
),
],
mainAxisAlignment: MainAxisAlignment.center,
),
),
);
}
}