Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I know there is a package called dart:convert which let me decode base64 image. But apparently, it doesn't work with pdf files. How can I decode the base64 PDF file in Flutter?

I want to store it in Firebase Storage (I know how to do it) but I need the File variable to do it.

I have a web service written in node js where I have a POST route. There, I create a pdf file and encode it to base 64. The response is a base64 string, look at the code.

router.post('/pdf', (req, res, next) => {
    //res.send('PDF');

    const fname = req.body.fname;
    const lname = req.body.lname;

    var documentDefinition = {
        content: [ write your pdf with pdfMake.org ],
        styles: { write your style };

    const pdfDoc = pdfMake.createPdf(documentDefinition);
    pdfDoc.getBase64((data) => {

        res.send({ "base64": data });

    });
});

As you can see, it returns the pdf as a base64 string.

Now, in Flutter, I have written this:

http.post("https://mypostaddreess.com",body: json.encode({"data1":"data"}))
              .then((response) {
            print("Response status: ${response.statusCode}");
            print("Response body: ${response.body}");

            var data = json.decode(response.body);
            var pdf = base64.decode(data["base64"]);

          });

}

I have the PDF in the variable 'pdf' as you see. But I don't know how to decode it to download the pdf or show it in my Flutter app.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.5k views
Welcome To Ask or Share your Answers For Others

1 Answer

@SwiftingDuster

a little added, maybe besides decoding, it's also necessary to create a pdf file and open it.

createPdf() async {
    var bytes = base64Decode(widget.base64String.replaceAll('
', ''));
    final output = await getTemporaryDirectory();
    final file = File("${output.path}/example.pdf");
    await file.writeAsBytes(bytes.buffer.asUint8List());

    print("${output.path}/example.pdf");
    await OpenFile.open("${output.path}/example.pdf");
    setState(() {});
}

library needed: 1. open_file 2. path_provider 3. pdf


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

Just Browsing Browsing

[3] html - How to create even cell spacing within a

548k questions

547k answers

4 comments

86.3k users

...