简体   繁体   English

如何显示从 flutter 中的 API 响应中获取的 pdf?

[英]how to show a pdf fetched from an API response in flutter?

I am working in a project where I have to show certificate that the user finished a course, there is an URL of the API that uses the get method within a token to have acces to a pdf file, the problem is that I do not know how to show or transform that response into a pdf, using flutter, I tried to use the url_launcher dependency because in the browser shows the pdf normally, but the problem is that it I need to pass a token to that url.我在一个项目中工作,我必须出示用户完成课程的证书,API 的 URL 使用令牌中的 get 方法来访问 Z437175BA4191210EE004E1D97 的问题是how to show or transform that response into a pdf, using flutter, I tried to use the url_launcher dependency because in the browser shows the pdf normally, but the problem is that it I need to pass a token to that url. the second thing that i tried was to fetched the response of the api and save it in a temporal file and use flutter_pdfview dependency but it shows errors.我尝试的第二件事是获取 api 的响应并将其保存在临时文件中并使用 flutter_pdfview 依赖项,但它显示错误。 this is how the response of the api looks like: 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

this is what I tried:这是我尝试过的:

 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;
    
  }

you can use flutter_pdfview package to show pdf:您可以使用flutter_pdfview package 来显示 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');
      },
    ),
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM