【问题标题】:how to show a pdf fetched from an API response in flutter?如何显示从 API 响应中获取的 pdf?
【发布时间】:2021-11-21 01:05:05
【问题描述】:

我在一个项目中工作,我必须出示用户完成课程的证书,有一个 API 的 URL 使用令牌中的 get 方法来访问 pdf 文件,问题是我不知道如何使用颤振显示或将该响应转换为 pdf, 我尝试使用 url_launcher 依赖项,因为在浏览器中正常显示 pdf,但问题是我需要将令牌传递给该 url。 我尝试的第二件事是获取 api 的响应并将其保存在临时文件中并使用 flutter_pdfview 依赖项,但它显示错误。 这是 api 的响应的样子:

%PDF-1.4
1 0 obj
<<
/Title (þÿ)
/Creator (þÿ)
/Producer (þÿQt 5.5.1)
/CreationDate (D:20211120205047)
>>
endobj
2 0 obj
<<
/Type /Catalog
/Pages 3 0 R
>>
endobj
4 0 obj
<<
/Type /ExtGState
/SA true
/SM 0.02
/ca 1.0
/CA 1.0
/AIS false

这是我尝试过的:

 Future LoadPDF(APIurl)async {
    Map<String,String> Headers={
      'Content-type': 'application/json; charset=UTF-8',
      'Accept': 'application/json',
      'Authorization': 'Bearer $userToken'
    };
    final response = await http.get(Uri.parse(APIurl),headers: Headers);
    final bytes = response.bodyBytes;
    // print(response.bodyBytes);
    var dir = await getTemporaryDirectory();
    File file = File(dir.path + "/data.pdf"); 
    await file.writeAsBytes(bytes, flush: true);
    setState(() {
    loadDocument(file);
    });
    // return file;
    
  }

【问题讨论】:

  • 你找到解决办法了吗?
  • 你修复了这个错误吗?我也有同样的问题。

标签: flutter http pdf token


【解决方案1】:

你好,我得到了和你一样的回复。这里我使用了 Dio api 结构。以此为参考。下面的代码对我来说很好。

Future<File?> downloadPDF(String applicantId, String templateId) async {
try {
  final response = await dioClient.post('xxxxxx/pdfService/pdfOperation/downloadPDF', data:DownloadRequestDTO(applicantId, templateId), headers: <String, dynamic>{
'Content-Type': 'application/json'}, options: Options(responseType: ResponseType.bytes));
  if (response != null) {
    final Directory? appDir = Platform.isAndroid
        ? await getExternalStorageDirectory()
        : await getApplicationDocumentsDirectory();
    String tempPath = appDir!.path;
    final String fileName =
        DateTime.now().microsecondsSinceEpoch.toString() + '-' + 'akt.pdf';
    File file = new File('$tempPath/$fileName');
    if (!await file.exists()) {
      await file.create();
    }
    await file.writeAsBytes(response);
    return file;
  }
  throw DownloadException('The download failed.', response);
} catch (value) {
  if (value is DioError) {
    print(value.response);
  }
  print(value.toString());
}

}

然后使用open_file包打开下载的文件

static Future<String?> openFile(String url) async {
final OpenResult result = await OpenFile.open(url);
switch (result.type) {
  case ResultType.error:
    return result.message;
  case ResultType.fileNotFound:
    return LocaleKeys.fileNotFound.tr();
  case ResultType.noAppToOpen:
    return LocaleKeys.noAppToOpen.tr();
  case ResultType.permissionDenied:
    return LocaleKeys.permissionDenied.tr();
  default:
    return null;
}}

并按如下方式调用此函数

Future<void> downloadAndOpenFile(BuildContext context) async {
try {
  File? file = await downloadPDF('1234', 'xxxxxx');
  if (file != null) {
    final String? result = await openFile(file.path.toString());
    if (result != null) {
      // Warning
    }
  }
} catch (e) {
  print(e);
}}

【讨论】:

    【解决方案2】:

    你可以使用flutter_pdfview包来显示pdf:

    loadDocument(file) {
        PDFView(
          filePath: file.path,
          enableSwipe: true,
          swipeHorizontal: true,
          autoSpacing: false,
          pageFling: false,
          onRender: (_pages) {
            setState(() {
              pages = _pages;
              isReady = true;
            });
          },
          onError: (error) {
            print(error.toString());
          },
          onPageError: (page, error) {
            print('$page: ${error.toString()}');
          },
          onViewCreated: (PDFViewController pdfViewController) {
            _controller.complete(pdfViewController);
          },
          onPageChanged: (int page, int total) {
            print('page change: $page/$total');
          },
        ),
    }
    

    【讨论】:

    • 我尝试使用那个包,但是当我运行项目时它显示错误:出了什么问题:任务':app:checkDebugAarMetadata'的执行失败。 > 无法解析配置“:app:debugRuntimeClasspath”的所有文件。 > 找不到 com.github.barteksc:android-pdf-viewer:3.2.0-beta.1。
    猜你喜欢
    • 2021-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-10
    • 1970-01-01
    • 1970-01-01
    • 2019-04-25
    • 1970-01-01
    相关资源
    最近更新 更多