Created
December 13, 2022 12:04
-
-
Save Frankdroid7/f677b9c4984ac3eef17edbdf552daa2f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:io'; | |
import 'dart:typed_data'; | |
import 'package:flutter/material.dart'; | |
import 'package:http/http.dart' as http; | |
import 'package:share_plus/share_plus.dart'; | |
import 'package:path_provider/path_provider.dart'; | |
import 'package:flutter_pdfview/flutter_pdfview.dart'; | |
class PdfView extends StatefulWidget { | |
const PdfView({Key? key}) : super(key: key); | |
@override | |
State<PdfView> createState() => _PdfViewState(); | |
} | |
class _PdfViewState extends State<PdfView> { | |
String? pdfPath; | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
body: SafeArea( | |
child: Column( | |
children: [ | |
Row( | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: [ | |
ElevatedButton( | |
onPressed: () { | |
getPdfBytesFromUrl( | |
'https://www.vuemastery.com/pdf/Vue-Essentials-Cheat-Sheet.pdf') | |
.then((bytes) { | |
storeAndSharePdf(bytes); | |
}); | |
}, | |
child: const Text('Get PDF'), | |
), | |
const SizedBox(width: 10), | |
ElevatedButton( | |
onPressed: () { | |
if (pdfPath != null) { | |
sharePdfFile(pdfPath!); | |
} | |
}, | |
child: const Text('Share PDF'), | |
), | |
], | |
), | |
pdfPath != null | |
? Expanded( | |
child: PDFView( | |
filePath: pdfPath, | |
autoSpacing: false, | |
onError: (error) { | |
print(error.toString()); | |
}, | |
onPageError: (page, error) { | |
print('$page: ${error.toString()}'); | |
}, | |
), | |
) | |
: const SizedBox.shrink(), | |
], | |
), | |
), | |
); | |
} | |
Future storeAndSharePdf(Uint8List bytes) async { | |
const filename = 'VueJs CheatSheet'; | |
final dir = await getApplicationDocumentsDirectory(); | |
final file = File('${dir.path}/$filename.pdf'); | |
await file.writeAsBytes(bytes); | |
setState(() { | |
pdfPath = file.path; | |
}); | |
} | |
Future<Uint8List> getPdfBytesFromUrl(String url) async { | |
final response = await http.get(Uri.parse(url)); | |
Uint8List bytes = response.bodyBytes; | |
return bytes; | |
} | |
sharePdfFile(String pdfPath) { | |
Share.shareXFiles([XFile(pdfPath)]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment