· Frontend developer

Display PDF from base64

Hey,

My input is a base64 string that, when encoded, is a PDF document.

Is there a way to display a PDF from base64 with the built-in widgets from FF or do I need to create my own?
And if I need to create my own, could someone help me out here? I tried this:

import 'dart:io';
import 'dart:convert';
import 'package:flutter_pdfview/flutter_pdfview.dart';
import 'package:path_provider/path_provider.dart';

class Base64PdfViewer extends StatefulWidget {
  const Base64PdfViewer(
      {Key? key, this.width, this.height, required this.base64Pdf})
      : super(key: key);

  final double? width;
  final double? height;
  final String base64Pdf;

  @override
  _Base64PdfViewerState createState() => _Base64PdfViewerState();
}

class _Base64PdfViewerState extends State<Base64PdfViewer> {
  String? filePath;

  @override
  void initState() {
    super.initState();
    _preparePdf();
  }

  Future<void> _preparePdf() async {
    final Uint8List bytes = base64.decode(widget.base64Pdf);
    final String dir = (await getTemporaryDirectory()).path;
    final String path = '$dir/temp.pdf';

    final File file = File(path);
    await file.writeAsBytes(bytes);
    if (mounted) {
      setState(() {
        filePath = path;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: filePath == null
          ? Center(child: CircularProgressIndicator())
          : PDFView(
              filePath: filePath,
            ),
    );
  }
}

But it didn't work

2
8 replies