如何在Flutter中解码base64 PDF字符串? [英] How to decode base64 PDF string in Flutter?

查看:328
本文介绍了如何在Flutter中解码base64 PDF字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有一个名为dart:convert的程序包,它可以让我解码base64图像.但显然,它不适用于pdf文件.如何在Flutter中解码base64 PDF文件?

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?

我想将其存储在Firebase Storage中(我知道该怎么做),但是我需要File变量来完成它.

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

我有一个用js节点编写的Web服务,其中有一个POST路由.在那里,我创建了一个pdf文件,并将其编码为base64.响应是一个base64字符串,请查看代码.

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

    });
});

如您所见,它返回pdf作为base64字符串.

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

现在,在Flutter中,我已经写过:

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"]);

          });

}

如您所见,我在变量'pdf'中有PDF.但是我不知道如何解码它以下载pdf或在Flutter应用中显示它.

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.

推荐答案

@SwiftingDuster

@SwiftingDuster

添加了一些内容,也许除了解码外,还需要创建一个pdf文件并打开它.

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('\n', ''));
    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(() {});
}

所需的库: 1. open_file 2. path_provider 3. pdf

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

这篇关于如何在Flutter中解码base64 PDF字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆