Search code examples
flutterpdf-viewerurl-launcher

How convert a binary to pdf in flutter


I have a variable to return in console:

[/PDF /Text /ImageB /ImageC /ImageI] I/flutter (15515): endobj I/flutter (15515): 10 0 obj I/flutter (15515): << /Length 5716 /Filter /FlateDecode >> stream ...

in flutter, my pdf is genereated through post

    launchURL(String text) async {
    var response = await http.post(
        Uri.parse(
            "http://web.exampleExt.aspx"),
        headers: {"Accept": "*/*"},
        body: {'codigo': '10020014499'});
    print(response.body);

    return "success!";

}

so, my response.body is pdf but not visualizate


Solution

  • What you can do is the following:

    Future<Widget> getAndShowPdf() async {
      var response = await http.post(Uri.parse("http://web.exampleExt.aspx"),
          headers: {"Accept": "*/*"}, body: {'codigo': '10020014499'});
    
      // Get the current directory
      final dir = await getExternalStorageDirectory();
      // Create a new File in the directory named pdfFromWeb.pdf
      final file = File("${dir.path}/pdfFromWeb.pdf");
    
      // Write down the file as bytes from the bytes getted from the HTTP request.
      await file.writeAsBytes(response.body.asUint8List());
    
    
      // Return a widget to view the PDF.
      return PDFView(
        filePath: file.path,
        enableSwipe: true,
        swipeHorizontal: true,
        autoSpacing: false,
        pageFling: false,
      );
    }
    

    This will work if and only if what your receiving on the body are bytes and you use a FutureBuilder to render the widget, you may also split the logic of the function in 2, one for creating a PDF File and the other one for rendering the PDF.

    flutter_pdfview

    This may also interest you:

    How to convert ByteBuffer to pdf