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

查看:53
本文介绍了如何在 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 存储中(我知道怎么做),但我需要 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 文件并将其编码为 base 64.响应是一个 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('
', ''));
    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_file2. path_provider3.pdf

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

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

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