Load and present a PDF file from URL in Flutter

Overview

URL PDF View

Fetch PDF content

Use Dio lib to load PDF URL link to

Future<Uint8List> _fetchPdfContent(final String url) async {
    try {
      final Response<List<int>> response = await Dio().get<List<int>>(
        url,
        options: Options(responseType: ResponseType.bytes),
      );
      return Uint8List.fromList(response.data);
    } catch (e) {
      print(e);
      return null;
    }
  }

Display PDF content

Use printing to display PDF content from Uint8List.

PdfPreview(
      allowPrinting: false,
      allowSharing: false,
      canChangePageFormat: false,
      initialPageFormat:
          PdfPageFormat(100 * PdfPageFormat.mm, 120 * PdfPageFormat.mm),
      build: (format) => content,
    );

Put Together

User FutureBuilder to build Widget loading content from URL.

class _MyHomePageState extends State<MyHomePage> {
  final String _url =
      "https://www.au-sonpo.co.jp/corporate/upload/article/89/article_89_1.pdf";


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: FutureBuilder<Uint8List>(
        future: _fetchPdfContent(_url),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return PdfPreview(
              allowPrinting: false,
              allowSharing: false,
              canChangePageFormat: false,
              initialPageFormat:
                  PdfPageFormat(100 * PdfPageFormat.mm, 120 * PdfPageFormat.mm),
              build: (format) => snapshot.data,
            );
          }
          return Center(
            child: CircularProgressIndicator(),
          );
        },
      )
    );
  }

  Future<Uint8List> _fetchPdfContent(final String url) async {
    try {
      final Response<List<int>> response = await Dio().get<List<int>>(
        url,
        options: Options(responseType: ResponseType.bytes),
      );
      return Uint8List.fromList(response.data);
    } catch (e) {
      print(e);
      return null;
    }
  }
}

Demo

Demo

Source code

https://github.com/ttpho/PDFViewer

Note

Cover Photo

Thumbnail Photo