how to implement pdf viewer in flutter
Introduction:
A PDF viewer allows users to view PDF documents within your Flutter app. The `syncfusion_flutter_pdfviewer` package provides a convenient way to integrate a PDF viewer. This guide will walk you through the steps to implement a PDF viewer in your Flutter app. on.
Content:
Step 1: Add Dependency
Ensure you have the `syncfusion_flutter_pdfviewer` package added to your `pubspec.yaml` file. Run the following command in your terminal:
syncfusion_flutter_pdfviewer: ^24.2.4
Run flutter pub get
to fetch the package.
Step 2: Import Dependencies
In your Dart file, import the necessary packages:
import 'package:flutter/material.dart';
import 'package:syncfusion_flutter_pdfviewer/pdfviewer.dart';
Step 3: Create PDF Viewer Widget
Create a widget to display the PDF viewer. For example
class PDFViewerWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('PDF Viewer'),
),
body: SfPdfViewer.network(
'https://cdn.syncfusion.com/content/PDFViewer/flutter-succinctly.pdf',
),
);
}
}
Step 4: Run the Application
Run your Flutter application and navigate to the screen containing the PDF viewer. You should see the PDF document rendered within the viewer.
Save your changes and run the app using the following command in your terminal:
flutter run
Sample code:
import 'package:flutter/material.dart';
import 'package:syncfusion_flutter_pdfviewer/pdfviewer.dart';
/// Represents Homepage for Navigation
class PdfViewPage extends StatefulWidget {
const PdfViewPage({super.key});
@override
_HomePage createState() => _HomePage();
}
class _HomePage extends State<PdfViewPage> {
final GlobalKey<SfPdfViewerState> _pdfViewerKey = GlobalKey();
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
elevation: 1,
actions: <Widget>[
IconButton(
icon: const Icon(
Icons.bookmark,
color: Colors.green,
semanticLabel: 'Bookmark',
),
onPressed: () {
_pdfViewerKey.currentState?.openBookmarkView();
},
),
],
backgroundColor: Colors.blue[200],
centerTitle: true,
title: Text(
"PDF Viewer",
style: TextStyle(color: Colors.white),
),
),
body: Container(
padding: EdgeInsets.symmetric(vertical: 2, horizontal: 5),
child: SfPdfViewer.network(
'https://cdn.syncfusion.com/content/PDFViewer/flutter-succinctly.pdf',
key: _pdfViewerKey,
),
),
);
}
}
Output:
Conclusion:
Congratulations! You’ve successfully implemented a PDF viewer in your Flutter app using the syncfusion_flutter_pdfviewer
package. You can now display PDF documents seamlessly and provide users with the ability to view PDF content directly within your app.
Feel free to explore additional features provided by the syncfusion_flutter_pdfviewer
package, such as customization options and interaction capabilities, to enhance the PDF viewing experience in your app.