Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

Abrir PDF blob base64 (enviado de servidor) en Web o Móvil usando Flutter

Tiempo de lectura: 2 minutos

Hola, hoy vamos a aprender cómo podemos abrir un archivo PDF enviado desde un API REST a nuestra APP Flutter.

Lo primero que vamos a hacer es instalar la librería de PDF para móvil en el pubspec.yaml

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
flutter_pdfview: ^1.0.0
flutter_pdfview: ^1.0.0
  flutter_pdfview: ^1.0.0

Para instalar la librería utiliza:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
flutter pub get
flutter pub get
flutter pub get 

Ahora vamos a crear un Widget que reciba el archivo PDF en Base64.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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()) {
//Descargar 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 {
// Si estamos en una aplicación móvil, utiliza PDFView de flutter_pdfview
return Scaffold(
appBar: AppBar(
title: Text('PDF Viewer'),
),
body: PDFView(
pdfData: pdfData,
enableSwipe: true,
swipeHorizontal: true,
autoSpacing: false,
pageFling: true,
onRender: (pages) {
// Callback opcional cuando el PDF ha sido renderizado
},
onError: (error) {
// Callback opcional para manejar errores
},
onPageError: (page, error) {
// Callback opcional para manejar errores de páginas individuales
},
onViewCreated: (PDFViewController viewController) {
// Puedes guardar una referencia al controlador si necesitas interactuar con el PDF
},
),
);
}
}
bool isWeb() {
//Verificar si se ejecuta en web
return kIsWeb;
}
}
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()) { //Descargar 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 { // Si estamos en una aplicación móvil, utiliza PDFView de flutter_pdfview return Scaffold( appBar: AppBar( title: Text('PDF Viewer'), ), body: PDFView( pdfData: pdfData, enableSwipe: true, swipeHorizontal: true, autoSpacing: false, pageFling: true, onRender: (pages) { // Callback opcional cuando el PDF ha sido renderizado }, onError: (error) { // Callback opcional para manejar errores }, onPageError: (page, error) { // Callback opcional para manejar errores de páginas individuales }, onViewCreated: (PDFViewController viewController) { // Puedes guardar una referencia al controlador si necesitas interactuar con el PDF }, ), ); } } bool isWeb() { //Verificar si se ejecuta en web return kIsWeb; } }
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()) {
      //Descargar 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 {
      // Si estamos en una aplicación móvil, utiliza PDFView de flutter_pdfview
      return Scaffold(
        appBar: AppBar(
          title: Text('PDF Viewer'),
        ),
        body: PDFView(
          pdfData: pdfData,
          enableSwipe: true,
          swipeHorizontal: true,
          autoSpacing: false,
          pageFling: true,
          onRender: (pages) {
            // Callback opcional cuando el PDF ha sido renderizado
          },
          onError: (error) {
            // Callback opcional para manejar errores
          },
          onPageError: (page, error) {
            // Callback opcional para manejar errores de páginas individuales
          },
          onViewCreated: (PDFViewController viewController) {
            // Puedes guardar una referencia al controlador si necesitas interactuar con el PDF
          },
        ),
      );
    }
  }

  bool isWeb() {
    //Verificar si se ejecuta en web
    return kIsWeb;
  }
}

Este archivo primero verifica si es web o móvil para saber que librería utilizar.

En caso de móvil va a generar una nueva ventana usando PDFView para cargar el PDF dentro de ella.

En caso de web, descargará el PDF directamente como archivo.

Recuerda importar el Widget de esta forma:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PDFViewerWidget(pdfData: pdfBytes),
),
);
await Navigator.push( context, MaterialPageRoute( builder: (context) => PDFViewerWidget(pdfData: pdfBytes), ), );
await Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => PDFViewerWidget(pdfData: pdfBytes),
        ),
      );

De esta forma creará una nueva ventana navegable que abrirá este contenedor.

3

Deja un comentario