Monday, June 17, 2024
Google search engine
HomePackages and PluginsPDF Document View & Download In Flutter

PDF Document View & Download In Flutter

Learn how to implement PDF Document View and Download in your Flutter Apps

In Flutter different elements make your application wealthy in functionality and give simplicity to the client to do stuff inside the application and get a better client experience, being a service provider is likewise vital for designers.

These little yet significant functionalities like getting pictures and videos from the gallery, opening maps, and automatic OTP autofill, are a few significant highlights that make any application easy to utilize and in this article, we will make sense of fundamental yet significant functionality named PDF Document View.

There are various packages that you can use to open a pdf in your application and download it to your local storage some are a piece muddled and some are not difficult to execute, and here I will clarify perhaps the most straightforward way to use it.

In this article, we will explore the PDF View & Download In Flutter. We will see how to implement a demo program. Learn how to view pdf and download it to your local storage using a network or locally stored file in your flutter applications.

For PDF View:

flutter_pdfview | Flutter Package
Native PDF View for iOS and Android Add this to your package’s pubspec.yaml file: dependencies: flutter_pdfview: ^1.2.1…pub.dev

For PDF Download (to your local storage):

path_provider | Flutter Package
A Flutter plugin for finding commonly used locations on the filesystem. Supports Android, iOS, Linux, macOS, and…pub.dev

For Network PDF’s :

dio | Dart Package
Language: English | 中文简体 A powerful Http client for Dart, which supports Interceptors, Global configuration, FormData…pub.dev

For Local PDF’s :

file_picker | Flutter Package
A package that allows you to use the native file explorer to pick single or multiple files, with extensions filtering…pub.dev

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table Of Contents::

Introduction

Implementation

Code Implement

Conclusion

GitHub Link



Introduction:

The demo video below shows how to implement PDF view and download in flutter and shows how we can access PDFs from both networks and locally in your flutter application. We will show a sample PDF when clicking on the button “Load a file from the network” if the user wishes to download this PDF he has an option in the top right corner of the app bar to save the file in the storage. The user can also view already downloaded PDFs from his storage with another button “Pick a file from local”.

Demo Module::


Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies:
flutter:
sdk: flutter
dio: ^4.0.6
file_picker: ^4.5.1
flutter_pdfview: ^1.2.2
path_provider: ^2.0.10

Step 2: Import

import 'package:flutter_pdfview/flutter_pdfview.dart';
import 'package:path_provider/path_provider.dart';
import 'package:dio/dio.dart';
import 'package:file_picker/file_picker.dart';

Step 3: Run flutter packages get in the root directory of your app.

How to implement code in dart file :

You need to implement it in your code respectively:

Create a new dart file called pdf_viewer_page.dart inside the lib folder.

We will create a PDF viewer page which will be a stateful widget, which will be responsible for viewing PDFs in our app.

Widget build(BuildContext context) {
final name = basename(widget.file.path);
return Scaffold(
appBar: AppBar(
title: Text(name),
actions: [
IconButton(
onPressed: () async {
await saveFile(widget.url, "sample.pdf");
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
'success',
style: TextStyle(color: Colors.white),
),
),
);
},
icon: const Icon(Icons.download_rounded),
),
],
),
body: PDFView(
filePath: widget.file.path,
),
);
}

Also, we will create a saveFile() function to save the file locally in our internal storage, we will pass the URL of the PDF file and a name to save it as.

Future<bool> saveFile(String url, String fileName) async {
try {
if (await _requestPermission(Permission.storage)) {
Directory? directory;
directory = await getExternalStorageDirectory();
String newPath = "";
List<String> paths = directory!.path.split("/");
for (int x = 1; x < paths.length; x++) {
String folder = paths[x];
if (folder != "Android") {
newPath += "/" + folder;
} else {
break;
}
}
newPath = newPath + "/PDF_Download";
directory = Directory(newPath);

File saveFile = File(directory.path + "/$fileName");
if (kDebugMode) {
print(saveFile.path);
}
if (!await directory.exists()) {
await directory.create(recursive: true);
}
if (await directory.exists()) {
await Dio().download(
url,
saveFile.path,
);
}
}
return true;
} catch (e) {
return false;
}
}

Now, inmain.dartinside thelibfolder.

We will give the user two ElevatedButton() i.e. “Pick a file from local” & “Load file from the network”, then we will create two separate functions, pickFile() and loadFromNetwrok() which link to each of the two buttons.

  • > For local file access:
Future<File?> pickFile() async {
final result = await FilePicker.platform.pickFiles(
type: FileType.custom,
allowedExtensions: ['pdf'],
);
if (result == null) return null;
return File(result.paths.first ?? '');
}
  • > For network file:
Future<File> loadPdfFromNetwork(String url) async {
final response = await http.get(Uri.parse(url));
final bytes = response.bodyBytes;
return _storeFile(url, bytes);
}

Future<File> _storeFile(String url, List<int> bytes) async {
final filename = basename(url);
final dir = await getApplicationDocumentsDirectory();
final file = File('${dir.path}/$filename');
await file.writeAsBytes(bytes, flush: true);
if (kDebugMode) {
print('$file');
}
return file;
}

And lastly, we will create a function that will redirect us to the pdf_viewer_page.dartfor both local and network-loaded PDF files.

void openPdf(BuildContext context, File file, String url) =>
Navigator.of(context).push(
MaterialPageRoute(
builder: (context) => PdfViewerPage(
file: file,
url: url,
),
),
);

When we run the application, we ought to get the screen’s output like the underneath screen capture.

Output

When a user opens any PDF the output screen will look like this, with the app bar containing the name of the PDF document.

Output

Conclusion:

In the article, I have shed some light on the fundamental construction of PDF viewer and downloader in a flutter program, you can modify this code as per your need. This was a little prologue to PDF View and Download from my side, and its functioning using Flutter.

I trust this blog will give you adequate data on trying up the PDF Document View and Download in your flutter projects. We showed you what PDF Viewer and Downloader are? its implementations, and how to utilize the PDF Document View and Download from both local and network. Made a demo app to work in your flutter applications. So if it’s not too much trouble, try it.

❤ ❤ Thanks for reading this article ❤❤

If I got something wrong? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


GitHub Link:

find the source code of the Flutter PDF Document VIew and Download Demo:

GitHub – flutter-devs/pdf_viewer_and_downloader_example
A new Flutter project. This project is a starting point for a Flutter application. A few resources to get you started…github.com


Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter-related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments