How to Download PDF from URL in Flutter

The importance of PDF files needs no explanation. In this blog post, let’s check how to download a PDF file from a URL in Flutter.

We use dio package for this tutorial. Dio is a powerful HTTP client which supports file downloading.

Install dio to your Flutter project using the following command.

flutter pub add dio

You can import dio as given below.

import 'package:dio/dio.dart';

Note: This tutorial is only tested on Android 13 device. For iOS devices and other low end Android devices you may need additional tweaks such as requesting storage permission.

Following is the function that helps to download the Pdf file from a URL.

Future download(String url, String filename) async {
    var savePath = '/storage/emulated/0/Download/$filename';
    var dio = Dio();
    dio.interceptors.add(LogInterceptor());
    try {
      var response = await dio.get(
        url,
        onReceiveProgress: showDownloadProgress,
        //Received data with List<int>
        options: Options(
          responseType: ResponseType.bytes,
          followRedirects: false,
          receiveTimeout: 0,
        ),
      );
      var file = File(savePath);
      var raf = file.openSync(mode: FileMode.write);
      // response.data is List<int> type
      raf.writeFromSync(response.data);
      await raf.close();
    } catch (e) {
      debugPrint(e.toString());
    }
  }

The following function prints the progress of the download.

void showDownloadProgress(received, total) {
    if (total != -1) {
      debugPrint((received / total * 100).toStringAsFixed(0) + '%');
    }
  }

Following is the complete code to download PDF file from URL.

import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'dart:io';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'Flutter Demo',
        theme: ThemeData(
          useMaterial3: true,
        ),
        home: const MyStatefulWidget());
  }
}

class MyStatefulWidget extends StatefulWidget {
  const MyStatefulWidget({super.key});

  @override
  State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  Future download(String url, String filename) async {
    var savePath = '/storage/emulated/0/Download/$filename';
    var dio = Dio();
    dio.interceptors.add(LogInterceptor());
    try {
      var response = await dio.get(
        url,
        onReceiveProgress: showDownloadProgress,
        //Received data with List<int>
        options: Options(
          responseType: ResponseType.bytes,
          followRedirects: false,
          receiveTimeout: 0,
        ),
      );
      var file = File(savePath);
      var raf = file.openSync(mode: FileMode.write);
      // response.data is List<int> type
      raf.writeFromSync(response.data);
      await raf.close();
    } catch (e) {
      debugPrint(e.toString());
    }
  }

  void showDownloadProgress(received, total) {
    if (total != -1) {
      debugPrint((received / total * 100).toStringAsFixed(0) + '%');
    }
  }

  @override
  void initState() {
    super.initState();
    var url = 'https://www.africau.edu/images/default/sample.pdf';
    var filename = 'demo.pdf';
    download(url, filename);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('Flutter PDF Example'),
        ),
        body: const Text('Check your downloads folder!'));
  }
}

Check your downloads folder to see whether the pdf file is downloaded. If you want to view the downloaded pdf file using a pdf viewer then see this Flutter PDF tutorial.

If you want to display a pdf file from a URL within your Flutter app then see this tutorial.

I hope this Flutter pdf download from the URL tutorial is helpful for you.

Similar Posts

Leave a Reply