Show downloaded temporary local file(png,jpg,pdf,rtf) in webview using flutter

199

For the image files, you can convert it to base64 to display the image. Here I use a simple version of html for demonstration purpose:

var htmlString = '''
  <html>
    <head><title>Test WebView</title></head>
    <body>{}</body>
  </html>
''';

var image = await http.get(url); // Download the image

// Insert in the base64 String
var htmlString = htmlString.replaceFirst('{}',
          '<img src=data:image/jpeg;base64,${base64Encode(image.bodyBytes)}>');

_controller.loadUrl(
          Uri.dataFromString(htmlString, mimeType: 'text/html').toString());

For the pdf, it's best to use the package flutter_cached_pdfview that's both easy to use for local or online file. Another quick way is to use the embedded view from google docs:

var displayUrl = 'https://docs.google.com/gview?embedded=true&url=$url';

Full example code:

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import 'package:http/http.dart' as http;

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MaterialApp(home: HelpScreen()));
}

class HelpScreen extends StatefulWidget {
  @override
  HelpScreenState createState() => HelpScreenState();
}

class HelpScreenState extends State<HelpScreen> {
  WebViewController _controller;
  var pdfUrl = 'www.africau.edu/images/default/sample.pdf';
  var imageUrl =
      'https://file-examples-com.github.io/uploads/2017/10/file_example_PNG_500kB.png';

  var htmlString = '''
  <html>
  <head><title>Test WebView</title>
  </head>
  <body>
  {}
  </body>
  </html>
  ''';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Help')),
      body: WebView(
        initialUrl: 'about:blank',
        javascriptMode: JavascriptMode.unrestricted,
        onWebViewCreated: (WebViewController webViewController) {
          _controller = webViewController;
          _loadHtmlFromAssets(imageUrl);
          _loadHtmlFromAssets(pdfUrl);
        },
      ),
    );
  }

  _loadHtmlFromAssets(String url) async {
    if (url.contains('png') || url.contains('jpg')) {
      var image = await http.get(url); // Download the image
      htmlString = htmlString.replaceFirst('{}',
          '<img src=data:image/jpeg;base64,${base64Encode(image.bodyBytes)}>');
      _controller.loadUrl(
          Uri.dataFromString(htmlString, mimeType: 'text/html').toString());
    } else if (url.contains('pdf')) {
      var displayUrl = 'https://docs.google.com/gview?embedded=true&url=$url';
      _controller.loadUrl(displayUrl).toString();
    }
  }
}

Share:
199
Darshan Prajapati
Author by

Darshan Prajapati

Updated on December 19, 2022

Comments

  • Darshan Prajapati
    Darshan Prajapati 11 months

    I wants to show any type of file in webview using flutter.

    Code for the load file in webview.

    class ViewFile extends StatelessWidget {
      WebViewController _controller;
    
      String path;
    
      ViewFile({this.path});
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(),
          body: Container(
            height: double.infinity,
            width: double.infinity,
            child: WebView(
              initialUrl: 'about:blank',
              javascriptMode: JavascriptMode.unrestricted,
              onWebViewCreated: (WebViewController webViewController) {
                _controller = webViewController;
                _loadHtmlFromAssets();
              },
            ),
          ),
        );
      }
    
      _loadHtmlFromAssets() async {
        print('path is $path');
        String fileText =  '''<embed src="$path" width="100%" height="100%"/>''';
        _controller.loadUrl(Uri.dataFromString(
            fileText,
            mimeType: 'text/html',
            encoding: Encoding.getByName('utf-8')
        ).toString());
      }
    }
    

    But it shows blank. Although embed tag other tags works perfectly.

    • Bach
      Bach over 2 years
      What format is this path string in, is it an URI or bytes? And did any error show up?
    • Darshan Prajapati
      Darshan Prajapati over 2 years
      It's an temporary file path which i have to shown in the webview