我有这个基本的 flutter 应用程序。 在 chrome 上运行它并单击下载按钮时,pdf 正在下载,但无法打开,它显示“无法加载 PDF 文档”
注意:如果文件名是“sample.txt”,则文件将保存为 txt,并且也会以内容“ABCDE”打开
如何打开pdf格式的内容?
代码:
import 'package:flutter/material.dart';
import 'dart:html' as html;
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('PDF Downloader'),
),
body: Center(
child: DownloadButton(),
),
),
);
}
}
class DownloadButton extends StatelessWidget {
final Uint8List pdfData = Uint8List.fromList([65, 66, 67, 68, 69]); // Sample Uint8List data
void _downloadPdf(BuildContext context) {
String filename = 'sample.pdf'; // Set the filename with appropriate extension
String mimeType = 'application/pdf'; // Set the MIME type for PDF
// Create a Blob from the Uint8List with the specified MIME type
var blob = html.Blob([pdfData], mimeType);
// Create an anchor element
var anchor = html.AnchorElement(href: html.Url.createObjectUrlFromBlob(blob))
..setAttribute("download", filename);
// Trigger download by simulating click event
anchor.click();
}
@override
Widget build(BuildContext context) {
return ElevatedButton(
onPressed: () => _downloadPdf(context),
child: Text('Download PDF'),
);
}
}
您创建的 Uint8List 仅包含字母“ABCDE”的 ASCII 代码,这不是有效的 PDF 文件。 要生成有效的 PDF 文件,您需要使用 pdf 或 syncfusion_flutter_pdf 等库创建 PDF 文档。
这是使用 pdf 库的示例:
import 'package:pdf/pdf.dart';
void _downloadPdf(BuildContext context) {
String filename = 'sample.pdf';
String mimeType = 'application/pdf';
final pdfDoc = PWDocument();
final page = pdfDoc.addPage();
final text = PWText(
text: 'Hello, World!',
fontSize: 24,
);
page.add(text);
// this will convert PDF document to a Uint8List
final pdfData = pdfDoc.save();
// creating a Blob from the Uint8List with the specified MIME type
var blob = html.Blob([pdfData], mimeType);
// create an anchor element
var anchor = html.AnchorElement(href: html.Url.createObjectUrlFromBlob(blob))
..setAttribute("download", filename);
// Download the pdf
anchor.click();
}
此代码将生成有效的 pdf。