我如何在 flutter 中显示 base64 格式的 pdf

How can i show pdf in base64 format in flutter

我在 postgresql 中有一个 table,它有一个带有 base64 格式的 pdf 文件的字段。当我从 flutter 中获取它时,如何用 pdf 查看器显示它?,有人做过吗??

感谢您的帮助

在pubspec.yaml中添加如下依赖:

dependencies:
  flutter_full_pdf_viewer: ^1.0.6 # for pdf

然后 运行 flutter pub get 在 Android Studio 终端中更新依赖项。

创建文件'pdfBase64Viewer.dart:

import 'dart:async'; // asynchroneous function (await)
import 'dart:io'; // write the file on user's phone
import 'dart:convert'; // handle base64 decoding
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_full_pdf_viewer/full_pdf_viewer_scaffold.dart';
import 'package:path_provider/path_provider.dart';


class PdfBase64Viewer extends StatefulWidget {
  final String url;

  const PdfBase64Viewer(String this.url);
  @override
  _PdfBase64ViewerState createState() => new _PdfBase64ViewerState();
}

class _PdfBase64ViewerState extends State<PdfBase64Viewer> {
  String pathPDF = "";

  @override
  void initState() {
    super.initState();
    createFileOfPdfUrl(widget.url).then((f) {
      setState(() {
        pathPDF = f.path;
        print(pathPDF);
      });
    });
  }


  Future<File> createFileOfPdfUrl(is_base_64) async {
    final filename = widget.url.substring(widget.url.lastIndexOf("/") + 1);

    var request = await HttpClient().getUrl(Uri.parse(widget.url));
    var response = await request.close();
    var bytes = await consolidateHttpClientResponseBytes(response);
    var base64String = utf8.decode(bytes); 
    var decodedBytes = base64Decode(base64String.replaceAll('\n', ''));

    String dir = (await getApplicationDocumentsDirectory()).path;
    File file = new File('$dir/$filename');
    await file.writeAsBytes(decodedBytes.buffer.asUint8List());

    return file;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Plugin example app')),
      body: Center(
        child: RaisedButton(
          child: Text("Open PDF"),
          onPressed: () => Navigator.push(
            context,
            MaterialPageRoute(builder: (context) => PDFScreen(pathPDF)),
          ),
        ),
      ),
    );
  }
}

class PDFScreen extends StatelessWidget {
  String pathPDF = "";
  PDFScreen(this.pathPDF);

  @override
  Widget build(BuildContext context) {
    return PDFViewerScaffold(
        appBar: AppBar(
          title: Text("Document"),
          actions: <Widget>[
            IconButton(
              icon: Icon(Icons.share),
              onPressed: () {},
            ),
          ],
        ),
        path: pathPDF);
  }
}

您可以在 class 上面进行调整,以便将您从数据库中获得的字符串值分配给变量 base64String。

您可以通过以下方式使用它:

import 'pdfBase64Viewer.dart';

(...)
child: PdfBase64Viewer("https://filebin.net/qmvmxbgn6pzgkbzb/sample.base64?t=7g5s9rwr") // url of your base64 file
(...)

您可能需要查看以下文档: