Open PDF Blob Base64 (Sent from Server) on Web or Mobile Using Flutter

Tiempo de lectura: 2 minutos

Reading time: 2 minutes

Hello, today we are going to learn how we can open a PDF file sent from a REST API in our Flutter app.

The first thing we are going to do is to install the PDF library for mobile in the pubspec.yaml file:

  flutter_pdfview: ^1.0.0

To install the library, use:

flutter pub get

Now, let’s create a Widget that receives the PDF file in Base64 format.

import 'dart:convert';
import 'dart:typed_data';
import 'package:flutter/foundation.dart' show kIsWeb;

import 'package:flutter/material.dart';
import 'package:flutter_pdfview/flutter_pdfview.dart';

import 'dart:html' as html;

class PDFViewerWidget extends StatelessWidget {
  final Uint8List pdfData;

  const PDFViewerWidget({super.key, required this.pdfData});

  @override
  Widget build(BuildContext context) {
    if (isWeb()) {
      // Download PDF:
      html.AnchorElement anchorElement = html.AnchorElement(
          href:
              "data:application/octet-stream;charset=utf-16le;base64,${base64Encode(pdfData)}")
        ..setAttribute("download", "pdf.pdf")
        ..click();
      return Container();
    } else {
      // If we are in a mobile application, use PDFView from flutter_pdfview
      return Scaffold(
        appBar: AppBar(
          title: Text('PDF Viewer'),
        ),
        body: PDFView(
          pdfData: pdfData,
          enableSwipe: true,
          swipeHorizontal: true,
          autoSpacing: false,
          pageFling: true,
          onRender: (pages) {
            // Optional callback when the PDF has been rendered
          },
          onError: (error) {
            // Optional callback to handle errors
          },
          onPageError: (page, error) {
            // Optional callback to handle errors for individual pages
          },
          onViewCreated: (PDFViewController viewController) {
            // You can save a reference to the controller if you need to interact with the PDF
          },
        ),
      );
    }
  }

  bool isWeb() {
    // Check if it is running on the web
    return kIsWeb;
  }
}

This file first checks whether it is running on the web or mobile to determine which library to use.

In the case of mobile, it will generate a new window using PDFView to load the PDF inside it.

In the case of the web, it will directly download the PDF as a file.

Remember to import the Widget like this:

await Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => PDFViewerWidget(pdfData: pdfBytes),
        ),
      );

This way, it will create a new navigable window that opens this container.

Leave a Comment