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

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

node.js - How to decode base64 PDF string in Flutter?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

@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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...