我正在尝试使用“ advance_pdf_viewer”库渲染PDF。过程如下
据我所知,第1步和第2步按预期运行,因为我能够在设备内的application文件夹中找到下载的PDF,并且可以使用经过测试的PDF阅读器打开PDF。
将下载,存储和显示PDF的代码:
@override
void initState() {
super.initState();
DocumentDownloader downloader = DocumentDownloader(widget.document);
downloader.download(context).then((data) {
if (kIsWeb) {
/// Send the PDF to the HTML document
} else {
downloader.storeFileData(context, data).then((local) {
if (local == null) {
return;
}
PDFDocument.fromFile(local).then((document) async {
setState(() {
pdf = document;
});
});
});
}
});
}
处理网络请求的类:
class DataProvider {
static const String DOWNLOAD_FILE_ENDPOINT = "/api/document/downloadfile";
Future<Uint8List> downloadFileData({
String filename,
}) {
print(filename);
return http
.post(
"${DataService.normalizeEndpoint(DOWNLOAD_FILE_ENDPOINT)}?filename=$filename",
headers: DataService.validateHeader(null),
)
.then((res) {
return res.bodyBytes;
});
}
}
class DocumentDownloader {
final Document document;
DocumentDownloader(this.document);
Future<Uint8List> download(BuildContext context) {
return DataProvider().downloadFileData(filename: document.filename);
}
Future<dynamic> storeFileData(
BuildContext context,
Uint8List data,
) {
if (data == null) {
return Future.value(null);
}
return getApplicationDocumentsDirectory().then((directory) {
io.File local = io.File("${directory.path}/${document.filename}");
return local.writeAsBytes(
data,
flush: true,
);
});
}
}
这是当查看器尝试加载PDFDocument时收到的错误消息,我的假设是PDFDocument.fromFile由于对我的未知原因(由于PDF存在)而无法加载PDF < / p>
[VERBOSE-2:ui_dart_state.cc(171)] Unhandled Exception: RangeError (index): Invalid value: Valid value range is empty: 0
#0 List.[] (dart:core-patch/array.dart:37:52)
#1 _PDFViewerState._loadPage (package:advance_pdf_viewer/src/viewer.dart:110:15)
#2 _PDFViewerState.didChangeDependencies (package:advance_pdf_viewer/src/viewer.dart:89:5)
#3 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4723:12)
#4 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4538:5)
#5 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3508:14)
#6 Element.updateChild (package:flutter/src/widgets/framework.dart:3263:20)
#7 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4589:16)
#8 Element.rebuild (package:flutter/src/widgets/framework.dart:4280:5)
#9 ProxyElement.update (package:flutter/src/widgets/framework.dart:4924:5)
#10 Element.updateChild (package:flutter/src/widgets/framework.dart:3253
我已经测试过使用PDFDocument.fromURL,并且可以按预期工作,所以我的设置必须有问题...
希望在这里获得一些提示!谢谢!
答案 0 :(得分:0)
这可能不算是一个答案,但我想把它作为解决这些问题的替代方法。
经过一段时间的false
苦苦挣扎之后,我将PDF阅读器库更改为advance_pdf_viewer
,然后就成功了。
我必须创建自己的导航按钮(转到首页,上一页,下一页和最后一页)以及当前页面/整个页面小部件,但是无论如何,这只是几分钟的编码。
我不能说flutter_pdfview
比advance_pdf_viewer
更好还是更坏,但是flutter_pdfview
对我的客户来说已经足够好了,在我的情况下,它按预期工作。