### Run Example App Source: https://github.com/endigo/flutter_pdfview/blob/master/CLAUDE.md Navigate to the example directory, install its dependencies, and run the example application. ```bash cd example flutter pub get flutter run ``` -------------------------------- ### Install Dependencies Source: https://github.com/endigo/flutter_pdfview/blob/master/CLAUDE.md Use this command to install project dependencies before development or testing. ```bash flutter pub get ``` -------------------------------- ### Build Example App for Platform Source: https://github.com/endigo/flutter_pdfview/blob/master/CLAUDE.md Build the example application for either iOS or Android platforms. ```bash flutter build ios flutter build apk ``` -------------------------------- ### Usage Examples Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/SUMMARY.txt A collection of complete, working examples demonstrating various use cases and patterns. ```APIDOC ## Usage Examples ### Description This section provides practical, ready-to-use code examples that illustrate how to implement different features and handle common scenarios with the `flutter_pdfview` package. ### Working Examples 1. **Basic PDF Viewer**: Simple implementation to display a PDF. 2. **Controlled Viewer with Navigation**: Example showing how to use `PDFViewController` for page navigation. 3. **Loading from Binary Data**: Demonstrates loading PDF content directly from bytes. 4. **Password-Protected PDFs**: How to handle PDFs that require a password. 5. **Custom Link Handling**: Example of implementing custom logic for URI links within PDFs. 6. **Status Display Overlay**: Shows how to display loading or error status. 7. **Screenshot Capability**: Example for capturing a screenshot of the PDF view. 8. **iPad Safe Mode Configuration**: Demonstrates configuring the viewer for iPad safe areas. ### Common Patterns - Pattern 1: Description - Pattern 2: Description - Pattern 3: Description - Pattern 4: Description ``` -------------------------------- ### Basic PDF Viewer Setup Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/10-usage-examples.md Minimal setup for displaying a local PDF file. Requires a file path to the PDF. ```dart import 'package:flutter/material.dart'; import 'package:flutter_pdfview/flutter_pdfview.dart'; class BasicPdfViewer extends StatefulWidget { final String filePath; BasicPdfViewer({required this.filePath}); @override _BasicPdfViewerState createState() => _BasicPdfViewerState(); } class _BasicPdfViewerState extends State { int? _totalPages = 0; int? _currentPage = 0; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('PDF Viewer'), subtitle: Text('Page ${(_currentPage ?? 0) + 1}/$_totalPages'), ), body: PDFView( filePath: widget.filePath, onRender: (pages) { setState(() { _totalPages = pages; }); }, onPageChanged: (page, total) { setState(() { _currentPage = page; }); }, onError: (error) { print('Error: $error'); ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('Error loading PDF')), ); }, ), ); } } ``` -------------------------------- ### Basic PDF Viewer Example Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/SUMMARY.txt A simple example demonstrating how to display a PDF using the PDFView widget. Ensure the PDF file is accessible. ```dart PDFView(filePath: "path/to/your/document.pdf") ``` -------------------------------- ### Install Packages with Flutter Source: https://github.com/endigo/flutter_pdfview/blob/master/README.md Run this command in your terminal to install the project dependencies, including flutter_pdfview. ```bash $ flutter packages get ``` -------------------------------- ### Usage Example - Link Handling Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/README.md Example illustrating how to handle link clicks within the PDF, allowing custom actions or navigation. ```dart PDFView( filePath: 'path/to/links.pdf', onLinkHandler: (uri) { print('Link clicked: $uri'); // Handle URI navigation, e.g., launchUrl(uri); return true; // Indicate that the link was handled }, // ... other parameters ) ``` -------------------------------- ### Usage Example - Status Display Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/README.md Example demonstrating how to display the current page number and total pages using the onPageChanged callback. ```dart int _currentPage = 0; int _totalPages = 0; PDFView( filePath: 'path/to/your.pdf', onPageChanged: (page, totalPages) { setState(() { _currentPage = page; _totalPages = totalPages; }); }, ) // Display status: Text('Page $_currentPage of $_totalPages') ``` -------------------------------- ### Usage Example - Controlled Viewer Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/README.md Example of using PDFViewController to control the PDF viewer, allowing programmatic navigation and zooming. ```dart PDFView( filePath: 'path/to/your.pdf', controller: _pdfViewController, // Assign the controller onRender: (_pages) { print('PDF rendered with $_pages pages.'); }, // ... other callbacks ) // Later, use the controller: // _pdfViewController.setPage(3); // _pdfViewController.zoom(2.0); ``` -------------------------------- ### RenderCallback Usage Example Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/03-types-and-enums.md Example of using the onRender callback to update the total page count and readiness state. ```dart PDFView( onRender: (pages) { setState(() { _totalPages = pages ?? 0; _isReady = true; }); }, ) ``` -------------------------------- ### PDFViewCreatedCallback Usage Example Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/03-types-and-enums.md Example of how to use the onViewCreated callback to get and store the PDFViewController. ```dart PDFView( onViewCreated: (PDFViewController controller) { // Store or use controller _pdfController = controller; }, ) ``` -------------------------------- ### Usage Example - Screenshots Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/README.md Illustrates how to capture a screenshot of the current PDF view. ```dart final PDFViewController controller = PDFViewController(); // ... inside your widget build method ... PDFView( filePath: 'path/to/your.pdf', controller: controller, ) // To take a screenshot: // controller.takeSnapshot().then((data) => print('Screenshot captured: $data')); ``` -------------------------------- ### Usage Example - Passwords Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/README.md Shows how to handle password-protected PDF files by providing the password to the PDFView widget. ```dart PDFView( filePath: 'path/to/protected.pdf', password: 'your_password', // ... other parameters ) ``` -------------------------------- ### Usage Example - iPad Safe Mode Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/README.md Example showing how to enable or disable iPad-specific safe mode handling for the PDF viewer. ```dart PDFView( filePath: 'path/to/your.pdf', enableiPadSafeMode: true, // or false // ... other parameters ) ``` -------------------------------- ### FitPolicy Usage Example Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/03-types-and-enums.md Example demonstrating how to set the fitPolicy for the PDFView widget on Android. ```dart PDFView( fitPolicy: FitPolicy.WIDTH, ) ``` -------------------------------- ### Usage Example - Binary Data Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/README.md Demonstrates how to display PDF content directly from binary data (Uint8List) instead of a file path. ```dart PDFView( pdfBytes: Uint8List.fromList(yourPdfBytes), // ... other parameters ) ``` -------------------------------- ### ErrorCallback Usage Example Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/03-types-and-enums.md Example of using the onError callback to print the error and show a dialog. ```dart PDFView( onError: (error) { print('Error: $error'); _showErrorDialog(error.toString()); }, ) ``` -------------------------------- ### LinkHandlerCallback Usage Example Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/03-types-and-enums.md Example of using onLinkHandler to handle different types of URIs, preventing default navigation if needed. ```dart PDFView( preventLinkNavigation: true, onLinkHandler: (uri) { if (uri != null) { if (uri.startsWith('http')) { _launchUrl(uri); } else if (uri.startsWith('tel:')) { _dialPhone(uri); } } }, ) ``` -------------------------------- ### PageChangedCallback Usage Example Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/03-types-and-enums.md Example of using the onPageChanged callback to print the current page number and total pages. ```dart PDFView( onPageChanged: (page, total) { print('Page ${(page ?? 0) + 1} of $total'); }, ) ``` -------------------------------- ### Controlled PDF Viewer with Navigation Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/SUMMARY.txt Example of a PDF viewer controlled by PDFViewController, allowing for navigation between pages. Requires initialization of the controller. ```dart PDFViewController controller; PDFView( filePath: "path/to/your/document.pdf", controller: controller, ) // To navigate to page 5: controller.setPage(5); ``` -------------------------------- ### PDF Viewer with Controller and Navigation Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/10-usage-examples.md Complete example using PDFViewController for navigation control, zooming, and displaying page numbers. Includes a loading indicator. ```dart import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_pdfview/flutter_pdfview.dart'; class ControlledPdfViewer extends StatefulWidget { final String filePath; ControlledPdfViewer({required this.filePath}); @override _ControlledPdfViewerState createState() => _ControlledPdfViewerState(); } class _ControlledPdfViewerState extends State { final Completer _pdfViewController = Completer(); int? _pages = 0; int? _currentPage = 0; bool _isReady = false; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Controlled PDF Viewer'), ), body: Stack( children: [ PDFView( filePath: widget.filePath, enableSwipe: true, swipeHorizontal: false, autoSpacing: true, pageFling: true, onViewCreated: (PDFViewController controller) { _pdfViewController.complete(controller); }, onRender: (pages) { setState(() { _pages = pages; _isReady = true; }); }, onPageChanged: (page, total) { setState(() { _currentPage = page; }); }, onError: (error) { print('PDF Error: $error'); }, onLoadComplete: (pages) { print('PDF loaded: $pages pages'); }, ), if (!_isReady) Center( child: CircularProgressIndicator(), ), ], ), bottomNavigationBar: _buildNavigationBar(), ); } Widget _buildNavigationBar() { return Container( color: Colors.grey.shade200, padding: EdgeInsets.all(8), child: Row( mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ IconButton( icon: Icon(Icons.skip_previous), onPressed: _currentPage! > 0 ? _previousPage : null, ), Text('${(_currentPage ?? 0) + 1}/$_pages'), IconButton( icon: Icon(Icons.skip_next), onPressed: (_currentPage ?? 0) < (_pages ?? 1) - 1 ? _nextPage : null, ), IconButton( icon: Icon(Icons.zoom_in), onPressed: _zoomIn, ), IconButton( icon: Icon(Icons.zoom_out), onPressed: _zoomOut, ), ], ), ); } void _previousPage() async { final controller = await _pdfViewController.future; final page = _currentPage ?? 0; if (page > 0) { await controller.setPage(page - 1); } } void _nextPage() async { final controller = await _pdfViewController.future; final page = _currentPage ?? 0; if (page < (_pages ?? 1) - 1) { await controller.setPage(page + 1); } } void _zoomIn() async { final controller = await _pdfViewController.future; final currentZoom = await controller.getScale(); await controller.setScale(currentZoom * 1.5); } void _zoomOut() async { final controller = await _pdfViewController.future; final currentZoom = await controller.getScale(); await controller.setScale(currentZoom / 1.5); } } ``` -------------------------------- ### PDFView Widget Constructor Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/README.md Reference for the PDFView widget constructor, detailing all parameters, their types, defaults, and platform-specific behaviors. Includes usage examples and assertions. ```dart PDFView( filePath: "path/to/your/pdf.pdf", // Other parameters like onPageChanged, onError, etc. ) ``` -------------------------------- ### Use LoadCompleteCallback Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/03-types-and-enums.md Example of how to use the onLoadComplete callback in a PDFView widget to display a message with the number of loaded pages. ```dart PDFView( onLoadComplete: (pages) { ScaffoldMessenger.of(context).showSnackBar( SnackBar(content: Text('PDF loaded: $pages pages')) ); }, ) ``` -------------------------------- ### Display PDF with Status Overlay Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/10-usage-examples.md Shows how to display a PDF file and overlay status information like page number, zoom level, and offsets. This example utilizes the `PDFView` widget and its callbacks to update the UI. ```dart import 'package:flutter/material.dart'; import 'dart:async'; import 'package:flutter_pdfview/flutter_pdfview.dart'; class StatusPdfViewer extends StatefulWidget { final String filePath; StatusPdfViewer({required this.filePath}); @override _StatusPdfViewerState createState() => _StatusPdfViewerState(); } class _StatusPdfViewerState extends State { final Completer _controller = Completer(); double _xOffset = 0.0; double _yOffset = 0.0; double _scale = 1.0; int? _currentPage = 0; int? _totalPages = 0; bool _isReady = false; String? _error; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('PDF Status Viewer'), ), body: Stack( children: [ PDFView( filePath: widget.filePath, onViewCreated: (controller) { _controller.complete(controller); }, onRender: (pages) { setState(() { _totalPages = pages; _isReady = true; }); }, onPageChanged: (page, total) { setState(() { _currentPage = page; }); }, onDraw: (xOffset, yOffset, scale) { setState(() { _xOffset = xOffset; _yOffset = yOffset; _scale = scale; }); }, onError: (error) { setState(() { _error = error.toString(); _isReady = false; }); }, onLoadComplete: (_) { print('PDF load complete'); }, ), // Loading indicator if (!_isReady && _error == null) Center( child: CircularProgressIndicator(), ), // Error message if (_error != null) Center( child: Text('Error: $_error'), ), // Status overlay if (_isReady) Positioned( top: 16, left: 16, child: Container( decoration: BoxDecoration( color: Colors.black87, borderRadius: BorderRadius.circular(8), ), padding: EdgeInsets.all(12), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ _buildStatusRow('Page', '${(_currentPage ?? 0) + 1}/$_totalPages'), _buildStatusRow('Zoom', '${(_scale * 100).toStringAsFixed(0)}%'), _buildStatusRow('X Offset', '${_xOffset.toStringAsFixed(1)}'), _buildStatusRow('Y Offset', '${_yOffset.toStringAsFixed(1)}'), ], ), ), ), ], ), ); } Widget _buildStatusRow(String label, String value) { return Padding( padding: EdgeInsets.symmetric(vertical: 4), child: Row( children: [ Text( label, style: TextStyle(color: Colors.white70, fontSize: 12), ), SizedBox(width: 8), Text( value, style: TextStyle(color: Colors.white, fontWeight: FontWeight.bold), ), ], ), ); } } ``` -------------------------------- ### Screenshot Capability for PDF View Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/SUMMARY.txt Example of capturing a screenshot of the current PDF view. Requires access to the PDFViewController. ```dart PDFViewController controller; // ... inside a button's onPressed or similar ... final uint8List = await controller.takeSnapshot(); // Use the uint8List to save or display the image ``` -------------------------------- ### Constructor for FlutterPDFView Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/06-ios-platform-implementation.md Initializes the `FlutterPDFView` with specified frame, arguments, and a controller. It handles device detection, PDFView setup, document loading, display configuration, password unlocking, gesture recognition, page setup, scroll view configuration, and notification registration. ```objc - (instancetype)initWithFrame:(CGRect)frame arguments:(id _Nullable)args controller:(nonnull FLTPDFViewController *)controller ``` -------------------------------- ### Import flutter_pdfview in Dart Source: https://github.com/endigo/flutter_pdfview/blob/master/README.md Import the package into your Dart files to start using its functionalities. ```dart import 'package:flutter_pdfview/flutter_pdfview.dart'; ``` -------------------------------- ### PDFView Widget Usage Example Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/01-pdfview-widget.md This snippet demonstrates how to use the PDFView widget to display a PDF file. It includes configurations for swipe gestures, spacing, page flinging, scroll indicators, background color, and various callback functions for rendering, errors, view creation, page changes, load completion, and drawing. ```dart PDFView( filePath: '/path/to/document.pdf', enableSwipe: true, swipeHorizontal: true, autoSpacing: false, pageFling: false, showScrollIndicators: true, backgroundColor: Colors.grey, onRender: (pages) { setState(() { totalPages = pages; isReady = true; }); }, onError: (error) { print('PDF Error: $error'); }, onPageError: (page, error) { print('Page $page Error: $error'); }, onViewCreated: (PDFViewController controller) { pdfViewController = controller; }, onPageChanged: (page, total) { print('Page changed: ${page! + 1}/$total'); }, onLoadComplete: (pages) { print('PDF loaded with $pages pages'); }, onDraw: (xOffset, yOffset, scale) { print('Draw: x=$xOffset, y=$yOffset, scale=$scale'); }, ) ``` -------------------------------- ### Get Current Page Method Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/06-ios-platform-implementation.md Returns the zero-based index of the currently displayed page in the PDF document. ```objc - (void)getCurrentPage:(FlutterMethodCall *)call result:(FlutterResult)result ``` -------------------------------- ### Key Setup Calls for PDF Rendering Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/04-android-platform-implementation.md This snippet highlights essential configuration calls for PDF rendering within FlutterPDFView, including setting rendering quality, enabling smooth zoom, configuring gestures, page navigation, link handling, and zoom limits. ```java // pdfView.useBestQuality() — Set rendering quality // pdfView.enableRenderDuringScale() — Smooth zoom rendering // config.enableSwipe()`, `.swipeHorizontal()` — Gesture configuration // config.pageFling()`, `.pageSnap()` — Page navigation style // config.linkHandler()` — Register link handler // config.onPageChange()`, `.onError()`, `.onRender()` — Callback registration // pdfView.setMaxZoom()`, `.setMinZoom()` — Zoom limits ``` -------------------------------- ### Custom Link Handling in PDF Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/SUMMARY.txt Example of intercepting and handling link clicks within the PDF. Allows for custom navigation or actions when a link is tapped. ```dart PDFView( filePath: "path/to/your/document.pdf", onLinkTap: (url) async { print('Tapped on link: $url'); // Implement custom handling, e.g., using url_launcher }, ) ``` -------------------------------- ### Get Current Page Size Method Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/06-ios-platform-implementation.md Returns the dimensions (width and height) of the current PDF page. Returns an error if no page is currently loaded. ```objc - (void)getCurrentPageSize:(FlutterMethodCall *)call result:(FlutterResult)result ``` -------------------------------- ### FLTPDFViewController onMethodCall Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/06-ios-platform-implementation.md Handles method calls received from the Dart side, routing them to the appropriate view methods. Supports various operations like getting page count, current page size, position, scale, setting page, position, scale, updating settings, and reloading. ```APIDOC ## FLTPDFViewController onMethodCall ### Description Handles method calls received from the Dart side, routing them to the appropriate view methods. Supports various operations like getting page count, current page size, position, scale, setting page, position, scale, updating settings, and reloading. ### Method Signature ```objc - (void)onMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result ``` ### Parameters - **call** (FlutterMethodCall *) - The method call object containing the method name and arguments. - **result** (FlutterResult) - The result callback to send a response back to Dart. ### Supported Methods | Method Name | Handler Method | Returns Type | Description | |---|---|---|---| | `pageCount` | `getPageCount:` | NSNumber | Returns the total number of pages. | | `currentPageSize` | `getCurrentPageSize:` | NSArray [width, height] | Returns the size of the current page. | | `getPosition` | `getPosition:` | NSArray [x, y] | Returns the current scroll position of the PDF view. | | `getScale` | `getScale:` | NSNumber | Returns the current zoom scale of the PDF view. | | `setPosition` | `setPosition:` | NSNumber(BOOL) | Sets the scroll position of the PDF view. Returns YES on success. | | `setScale` | `setScale:` | NSNumber(BOOL) | Sets the zoom scale of the PDF view. Returns YES on success. | | `currentPage` | `getCurrentPage:` | NSNumber | Returns the current page number. | | `setPage` | `setPage:` | NSNumber(BOOL) | Sets the current page of the PDF view. Returns YES on success. | | `updateSettings` | `onUpdateSettings:` | nil | Updates the settings of the PDF view. | | `setZoomLimits` | `setZoomLimits:` | NSNumber(BOOL) | Sets the zoom limits for the PDF view. Returns YES on success. | | `reload` | `reload:` | NSNumber(BOOL) | Reloads the PDF view. Returns YES on success. | | `getScreenshot` | - | Error: "UNSUPPORTED" | This method is not supported. | ``` -------------------------------- ### Layout Subviews in PDFView Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/06-ios-platform-implementation.md Manages the layout of the PDFView, including setting its frame, calculating scale limits, and handling initial page setup. It skips execution if the view is currently scrolling to prevent conflicts. ```objc - (void)layoutSubviews ``` -------------------------------- ### Configuration and Parameters - PDFView Constructor Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/README.md Documentation for all parameters available in the PDFView constructor, including default values and constraints. ```dart PDFView( filePath: "path/to/pdf.pdf", autoSpacing: true, nightMode: false, // ... other parameters ) ``` -------------------------------- ### PageErrorCallback Usage Example Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/03-types-and-enums.md Example of using the onPageError callback to print a message when a specific page fails to render. ```dart PDFView( onPageError: (page, error) { print('Page ${(page ?? 0) + 1} failed: $error'); }, ) ``` -------------------------------- ### Configuration and Parameters - updateSettings() Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/README.md Demonstrates how to update PDF viewer settings at runtime using the updateSettings() method. ```dart final PDFViewController controller = PDFViewController(); // Update settings dynamically controller.updateSettings({ 'autoSpacing': false, 'nightMode': true, }); ``` -------------------------------- ### Load PDF from Binary Data (Assets/Network) Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/10-usage-examples.md Demonstrates loading PDF data from either local assets or a network URL. Handles loading states and errors, displaying the PDF once data is available. ```dart import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_pdfview/flutter_pdfview.dart'; import 'package:http/http.dart' as http; import 'package:path_provider/path_provider.dart'; class BinaryPdfViewer extends StatefulWidget { @override _BinaryPdfViewerState createState() => _BinaryPdfViewerState(); } class _BinaryPdfViewerState extends State { Uint8List? _pdfData; String? _errorMessage; bool _isLoading = false; @override void initState() { super.initState(); _loadPdfFromAsset(); } Future _loadPdfFromAsset() async { try { setState(() => _isLoading = true); final data = await rootBundle.load('assets/sample.pdf'); setState(() { _pdfData = data.buffer.asUint8List(); _errorMessage = null; }); } catch (e) { setState(() { _errorMessage = 'Failed to load PDF from assets: $e'; }); } finally { setState(() => _isLoading = false); } } Future _loadPdfFromNetwork(String url) async { try { setState(() => _isLoading = true); final response = await http.get(Uri.parse(url)); if (response.statusCode != 200) { throw Exception('HTTP ${response.statusCode}'); } setState(() { _pdfData = response.bodyBytes; _errorMessage = null; }); } catch (e) { setState(() { _errorMessage = 'Failed to download PDF: $e'; }); } finally { setState(() => _isLoading = false); } } @override Widget build(BuildContext context) { if (_isLoading) { return Scaffold( appBar: AppBar(title: Text('Loading PDF')), body: Center(child: CircularProgressIndicator()), ); } if (_errorMessage != null) { return Scaffold( appBar: AppBar(title: Text('Error')), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Icon(Icons.error, color: Colors.red, size: 64), SizedBox(height: 16), Text(_errorMessage!, textAlign: TextAlign.center), SizedBox(height: 24), ElevatedButton.icon( icon: Icon(Icons.refresh), label: Text('Retry'), onPressed: _loadPdfFromAsset, ), ], ), ), ); } if (_pdfData == null) { return Scaffold( body: Center(child: Text('No PDF loaded')), ); } return Scaffold( appBar: AppBar(title: Text('PDF Viewer')), body: PDFView( pdfData: _pdfData, onError: (error) { print('PDF Error: $error'); }, ), ); } } ``` -------------------------------- ### Publish to pub.dev Source: https://github.com/endigo/flutter_pdfview/blob/master/CLAUDE.md Publish the plugin to the official pub.dev repository. ```bash flutter pub publish ``` -------------------------------- ### Android PDFViewFlutterPlugin Entry Point Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/README.md The entry point for the PDFViewFlutterPlugin on Android, responsible for initializing the plugin and handling platform view creation. ```java public class PDFViewFlutterPlugin implements FlutterPlugin, ActivityAware { // ... plugin implementation } ``` -------------------------------- ### getPosition Source: https://github.com/endigo/flutter_pdfview/blob/master/README.md Gets the current scroll position of the PDF view relative to its origin. ```APIDOC ## getPosition ### Description Get the position of the top left of the PDF with respect to the origin (top left of PDFView). ### Method Controller Method ### Parameters None ### Return `Future` - The current scroll position. ``` -------------------------------- ### PDFView Constructor and Parameters Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/01-pdfview-widget.md This snippet details the constructor for the PDFView widget and its associated parameters. It outlines how to initialize the widget with file paths or data, configure callbacks for various events like rendering, page changes, and errors, and customize gesture handling and visual properties. ```APIDOC ## PDFView Widget ### Description The `PDFView` widget is a stateful Flutter widget designed to display PDF documents natively on iOS and Android platforms. It offers extensive configuration options for displaying PDFs, handling user interactions, and responding to various events during the PDF lifecycle. ### Constructor ```dart const PDFView({ Key? key, this.filePath, this.pdfData, this.onViewCreated, this.onRender, this.onPageChanged, this.onError, this.onPageError, this.onLinkHandler, this.onLoadComplete, this.onDraw, this.gestureRecognizers, this.enableSwipe = true, this.swipeHorizontal = false, this.showScrollIndicators = false, this.password, this.nightMode = false, this.autoSpacing = true, this.pageFling = true, this.pageSnap = true, this.enableAntialiasing = true, this.useBestQuality = true, this.enableRenderDuringScale = true, this.thumbnailRatio = 0.8, this.fitEachPage = true, this.defaultPage = 0, this.fitPolicy = FitPolicy.WIDTH, this.preventLinkNavigation = false, this.backgroundColor, this.maxZoom = 4.0, this.minZoom = 1.0, }) ``` ### Parameters | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | `filePath` | String? | * | null | File path to local PDF document. Either `filePath` or `pdfData` must be provided. Supports file:// URIs and http(s):// remote URLs | | `pdfData` | Uint8List? | * | null | Binary PDF document data. Either `filePath` or `pdfData` must be provided | | `onViewCreated` | PDFViewCreatedCallback? | No | null | Callback invoked once the PDFView is created. Receives a `PDFViewController` for controlling the view | | `onRender` | RenderCallback? | No | null | Callback invoked after PDF rendering completes. Receives the total page count | | `onPageChanged` | PageChangedCallback? | No | null | Callback invoked when the displayed page changes. Receives current page index and total page count | | `onError` | ErrorCallback? | No | null | Callback invoked when a general error occurs during PDF loading or rendering | | `onPageError` | PageErrorCallback? | No | null | Callback invoked when a specific page fails to render. Android-only; not supported on iOS | | `onLinkHandler` | LinkHandlerCallback? | No | null | Callback invoked when a PDF link is clicked. Receives the link URI as a string | | `onLoadComplete` | LoadCompleteCallback? | No | null | Callback invoked when PDF document finishes loading completely | | `onDraw` | DrawCallback? | No | null | Callback invoked during draw operations. Receives PDF X offset, Y offset, and scale (zoom) level | | `gestureRecognizers` | Set>? | No | null | Custom gesture recognizers to handle pointer events. Allows coordination with other gestures (e.g., ListView scrolling) | | `enableSwipe` | bool | No | true | Whether swiping gestures change pages. On iOS with pageFling=true, enables vertical continuous scrolling | | `swipeHorizontal` | bool | No | false | Whether swiping is horizontal (left/right) versus vertical (up/down) | | `showScrollIndicators` | bool | No | false | Whether to show scroll bars or handles. On iOS with pageFling=true, scroll indicators are hidden | | `password` | String? | No | null | Password for encrypted PDF documents. Ignored for unencrypted documents | | `nightMode` | bool | No | false | Android-only. Whether to invert colors for dark theme rendering | | `autoSpacing` | bool | No | true | Whether to automatically add spacing between rendered pages | | `pageFling` | bool | No | true | Whether page navigation uses fling/page-view gestures. On iOS, enables page view controller for page-based navigation | | `pageSnap` | bool | No | true | Android-only. Whether the view snaps to a page after scrolling | | `enableAntialiasing` | bool | No | true | Android-only. Whether to use antialiasing for smoother text rendering | | `useBestQuality` | bool | No | true | Android-only. Improves render quality at the cost of performance | | `enableRenderDuringScale` | bool | No | true | Android-only. Whether to render during pinch-zoom gestures for smoother zooming | | `thumbnailRatio` | double? | No | 0.8 | Android-only. Ratio for internal PDF thumbnail rendering | | `fitEachPage` | bool | No | true | Deprecated: will be removed in next version | | `defaultPage` | int | No | 0 | Initial page to display (zero-based index) | | `fitPolicy` | FitPolicy | No | FitPolicy.WIDTH | Android-only. How to fit PDF pages: WIDTH, HEIGHT, or BOTH | | `preventLinkNavigation` | bool | No | false | Whether to prevent automatic link navigation. When true, links are reported via `onLinkHandler` instead of opening immediately | | `backgroundColor` | Color? | No | null | Background color of the PDF view. Receives a Flutter Color object | | `maxZoom` | double | No | 4.0 | Maximum zoom level for pinch-zoom gestures | | `minZoom` | double | No | 1.0 | Minimum zoom level. Value of 1.0 represents fit-to-page | ``` -------------------------------- ### Invoke Method Channel (iOS) Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/07-method-channel-protocol.md Example of invoking a method channel from the iOS native side to Dart. ```objective-c [channel invokeMethod:name arguments:args] ``` -------------------------------- ### iOS FLTPDFViewFlutterPlugin Entry Point Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/README.md The entry point for the FLTPDFViewFlutterPlugin on iOS, responsible for plugin initialization and managing platform view creation. ```objective-c @interface FLTPDFViewFlutterPlugin : NSObject @end ``` -------------------------------- ### Get Current Page Index Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/07-method-channel-protocol.md Retrieves the zero-based index of the current page. Returns an integer or null. ```dart invokeMethod('currentPage') ``` -------------------------------- ### Handle Platform-Specific Settings Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/09-errors-and-exceptions.md Illustrates updating PDFView settings, emphasizing the need to check for valid setting keys on Android to avoid UNKNOWN errors. ```dart // Ensure setting exists before updating final validSettings = { 'enableSwipe': true, 'pageFling': false, 'maxZoom': 3.0, }; // Only update known settings to avoid errors ``` -------------------------------- ### Get Integer Parameter Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/04-android-platform-implementation.md Retrieves an integer value from a map of parameters. Defaults to 0 if the key is not present. ```java private int getInt(Map params, String key) ``` -------------------------------- ### Get Current PDF Page Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/02-pdf-view-controller.md Retrieves the index of the currently displayed page. Remember that the index is zero-based. ```dart Future getCurrentPage() ``` ```dart final currentPage = await pdfViewController.getCurrentPage(); print('Viewing page ${(currentPage ?? 0) + 1}'); ``` -------------------------------- ### Set Initial Fit Policy (Android) Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/08-configuration-and-parameters.md Configure the initial page scaling policy for Android. Options include fitting by width, height, or both. This is ignored on iOS. ```dart final FitPolicy fitPolicy = FitPolicy.WIDTH ``` -------------------------------- ### Callback Type Aliases Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/README.md Documentation for all 7 callback type aliases, specifying their parameters, expected timing, execution order, and null handling. ```dart typedef OnPageChangedCallback = void Function(int page, int totalPages); typedef OnErrorCallback = void Function(dynamic error); // ... other callback types ``` -------------------------------- ### Update PDFView Settings Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/08-configuration-and-parameters.md Demonstrates how to obtain a PDFViewController and later use it to update specific runtime settings like page fling behavior. Ensure the controller is initialized before calling `_updateSettings`. ```dart // Get controller late PDFViewController _controller; PDFView( onViewCreated: (controller) { _controller = controller; }, ) // Later, update settings void togglePageFling() async { // Note: Can only update specific settings final newSettings = Map(); newSettings['pageFling'] = !currentPageFlingState; await _controller._updateSettings( _PDFViewSettings(pageFling: !currentPageFlingState) ); } ``` -------------------------------- ### Get String Parameter Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/04-android-platform-implementation.md Retrieves a string value from a map of parameters. Returns an empty string if the key is not present. ```java private String getString(Map params, String key) ``` -------------------------------- ### Get Page Count Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/07-method-channel-protocol.md Retrieves the total number of pages in the PDF document. Returns an integer or null if no page is loaded. ```dart invokeMethod('pageCount') ``` -------------------------------- ### Run All Tests Source: https://github.com/endigo/flutter_pdfview/blob/master/CLAUDE.md Execute all tests in the project to ensure code integrity. ```bash flutter test ``` -------------------------------- ### Get PDF Scroll Position Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/02-pdf-view-controller.md Retrieves the current scroll offset (X and Y coordinates) of the PDF view in logical pixels. ```dart Future getPosition() ``` ```dart final position = await pdfViewController.getPosition(); print('Scroll position: x=${position.dx}, y=${position.dy}'); ``` -------------------------------- ### PDFViewController Methods Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/README.md Documentation for all public methods of the PDFViewController, including signatures, parameter and return type details, and common usage patterns. ```dart final PDFViewController _pdfViewController = PDFViewController(); // Example of calling a method _pdfViewController.setPage(5); _pdfViewController.zoom(1.5); ``` -------------------------------- ### applySettings Method Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/04-android-platform-implementation.md Applies various settings to the PDF view, such as swipe enablement, night mode, and zoom limits. Throws IllegalArgumentException for unknown settings. ```Java void applySettings(Map settings) ``` -------------------------------- ### Get Scale Method Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/06-ios-platform-implementation.md Retrieves the current zoom scale factor of the PDF view. This is a direct access to the `scaleFactor` property of the PDFView. ```objc - (void)getScale:(FlutterMethodCall *)call result:(FlutterResult)result ``` -------------------------------- ### Initialize PDFView with File Path Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/08-configuration-and-parameters.md Use this snippet to load a PDF from a local file path or a URI. Ensure the path is absolute or correctly resolved from assets. This parameter cannot be changed after initialization. ```dart PDFView( filePath: '/sdcard/Documents/file.pdf', ) ``` -------------------------------- ### Get Boolean Parameter Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/04-android-platform-implementation.md Retrieves a boolean value from a map of parameters. Returns true only if the key exists and its value is Boolean true. ```java private boolean getBoolean(Map params, String key) ``` -------------------------------- ### Get PDF Page Count Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/02-pdf-view-controller.md Retrieves the total number of pages in the PDF document. Use this to understand the document's length. ```dart Future getPageCount() ``` ```dart final pages = await pdfViewController.getPageCount(); print('PDF has $pages pages'); ``` -------------------------------- ### Initialize PDFView with PDF Data Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/08-configuration-and-parameters.md Load a PDF directly from binary data (Uint8List) in memory. This is useful for PDFs fetched from the network, databases, or dynamically generated content. Either filePath or pdfData must be provided. ```dart final bytes = await rootBundle.load('assets/document.pdf'); PDFView( pdfData: bytes.buffer.asUint8List(), ) ``` -------------------------------- ### Use DrawCallback Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/03-types-and-enums.md Example of using the onDraw callback to update state variables with the current scroll and zoom information, and displaying the zoom level. ```dart PDFView( onDraw: (xOffset, yOffset, scale) { setState(() { _xOffset = xOffset; _yOffset = yOffset; _scale = scale; }); }, ) // In build: Text('Zoom: ${_scale.toStringAsFixed(2)}x') ``` -------------------------------- ### Platform View Creation Parameters Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/07-method-channel-protocol.md This map defines the configuration options passed from Dart to native code when creating a platform view. Ensure all keys and value types match the expected structure. ```dart Map { 'filePath': String?, 'pdfData': Uint8List?, 'enableSwipe': bool, 'swipeHorizontal': bool, 'showScrollIndicators': bool, 'password': String?, 'nightMode': bool, 'autoSpacing': bool, 'pageFling': bool, 'pageSnap': bool, 'enableAntialiasing': bool, 'useBestQuality': bool, 'enableRenderDuringScale': bool, 'thumbnailRatio': double?, 'defaultPage': int, 'fitPolicy': String, // "FitPolicy.WIDTH" | "FitPolicy.HEIGHT" | "FitPolicy.BOTH" 'preventLinkNavigation': bool, 'backgroundColor': int?, // ARGB color as 32-bit int 'maxZoom': double, 'minZoom': double, } ``` -------------------------------- ### Basic PDFView Widget Usage Source: https://github.com/endigo/flutter_pdfview/blob/master/README.md This snippet demonstrates the basic usage of the PDFView widget to display a PDF file. It includes common properties for controlling swipe gestures, spacing, and rendering callbacks. Ensure the 'filePath' is correctly set and necessary platform dependencies are met. ```dart PDFView( filePath: path, enableSwipe: true, swipeHorizontal: true, autoSpacing: false, pageFling: false, showScrollIndicators: true, backgroundColor: Colors.grey, onRender: (_pages) { setState(() { pages = _pages; isReady = true; }); }, onError: (error) { print(error.toString()); }, onPageError: (page, error) { print('$page: ${error.toString()}'); }, onViewCreated: (PDFViewController pdfViewController) { _controller.complete(pdfViewController); }, onPageChanged: (int page, int total) { print('page change: $page/$total'); }, onLoadComplete: (int? pages) { print('# of pages: $pages'); }, onDraw: (double xOffset, double yOffset, double scale) { print('onDraw'); }, ) ``` -------------------------------- ### FLTPDFViewController Constructor Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/06-ios-platform-implementation.md Initializes the FLTPDFViewController with frame, view identifier, arguments, and a Flutter binary messenger. It sets up the PDF view, parses background color, and establishes a method channel for communication. ```APIDOC ## FLTPDFViewController Constructor ### Description Initializes the FLTPDFViewController with frame, view identifier, arguments, and a Flutter binary messenger. It sets up the PDF view, parses background color, and establishes a method channel for communication. ### Method Signature ```objc - (instancetype)initWithFrame:(CGRect)frame viewIdentifier:(int64_t)viewId arguments:(id _Nullable)args binaryMessenger:(NSObject *)messenger ``` ### Parameters - **frame** (CGRect) - The frame for the view. - **viewId** (int64_t) - The unique identifier for the view. - **args** (id _Nullable) - Optional arguments for initialization, including background color. - **messenger** (NSObject *) - The binary messenger for communication. ``` -------------------------------- ### Set Default Initial Page Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/08-configuration-and-parameters.md Specify which page to display when the PDF first loads. This is a zero-based index, so 0 represents the first page. The value must be less than the total page count. ```dart final int defaultPage = 0 ``` -------------------------------- ### Get Float Parameter with Default Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/04-android-platform-implementation.md Retrieves a float value from a map of parameters, using a provided default value if the key is not present or the value is not a number. ```java private float getFloat(Map params, String key, float defaultValue) ``` -------------------------------- ### Loading PDF from Binary Data Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/SUMMARY.txt Demonstrates loading PDF content directly from binary data (Uint8List). Useful when the PDF is not stored as a file. ```dart Uint8List pdfBytes = await loadPdfBytes(); // Implement this function PDFView( pdfBytes: pdfBytes, ) ``` -------------------------------- ### Get Current Scroll Position Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/07-method-channel-protocol.md Retrieves the current scroll position (xOffset, yOffset) in logical pixels. An error is expected on iOS if the PDFView is not ready. ```dart invokeMethod('getPosition') ``` -------------------------------- ### FLTPDFViewController Constructor Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/06-ios-platform-implementation.md Initializes the FLTPDFViewController, setting up the view, parsing arguments like background color, and establishing the method channel for communication with Flutter. ```Objective-C - (instancetype)initWithFrame:(CGRect)frame viewIdentifier:(int64_t)viewId arguments:(id _Nullable)args binaryMessenger:(NSObject *)messenger ``` -------------------------------- ### getCurrentPage Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/02-pdf-view-controller.md Gets the index of the currently displayed page. The index is zero-based. Returns a Future that resolves to the current page index or null if an error occurs. ```APIDOC ## getCurrentPage ### Description Returns the currently displayed page (zero-based index). ### Method Future ### Returns `Future` — Current page index (0-based), or null on error ### Example ```dart final currentPage = await pdfViewController.getCurrentPage(); print('Viewing page ${(currentPage ?? 0) + 1}'); ``` ``` -------------------------------- ### Validation Before Operation Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/09-errors-and-exceptions.md Validate user input or operation parameters before executing them to prevent errors. This example checks if the requested page number is within the valid range. ```dart void navigateToPage(int page) async { final pageCount = await controller.getPageCount(); if (page < 0 || page >= (pageCount ?? 0)) { showErrorDialog('Invalid page: $page'); return; } await controller.setPage(page); } ``` -------------------------------- ### Manage KVO Observation Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/06-ios-platform-implementation.md Starts and stops Key-Value Observing (KVO) for the scroll view's contentOffset. This is essential for triggering onDraw callbacks when the user scrolls. ```objc - (void)startObserving ``` ```objc - (void)stopObserving ``` -------------------------------- ### PDF Viewer with Status Overlay Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/SUMMARY.txt Demonstrates displaying status information (like page loading progress) over the PDF viewer. Uses callback for status updates. ```dart String status = "Loading..."; PDFView( filePath: "path/to/your/document.pdf", onRender: (_pages) { status = "Rendered $_pages pages"; }, onViewCreated: (PDFViewController controller) { // Use controller for further actions }, onError: (error) { status = "Error: $error"; }, ) // Display status text elsewhere in your UI ``` -------------------------------- ### Retry on Page Error Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/09-errors-and-exceptions.md Handle individual page rendering errors and implement a retry mechanism. This example tracks failed pages and attempts to reload the PDFView after a delay. ```dart Set failedPages = {}; PDFView( onPageError: (page, error) { failedPages.add(page ?? 0); print('Page ${(page ?? 0) + 1} failed: $error'); if (failedPages.length < 5) { // Retry failed page Future.delayed(Duration(seconds: 2), () { controller.reload(); }); } }, ) ``` -------------------------------- ### Handle View Not Ready Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/09-errors-and-exceptions.md Ensures the PDF view is ready by waiting for it to load before calling controller methods like getPosition(). ```dart // Ensure PDF is loaded before using controller await Future.delayed(Duration(milliseconds: 500)); final position = await controller.getPosition(); ``` -------------------------------- ### Get Current Zoom Level Source: https://github.com/endigo/flutter_pdfview/blob/master/_autodocs/07-method-channel-protocol.md Retrieves the current zoom level of the PDF view. A value of 1.0 indicates fit to page. Defaults to 1.0 if the value is null. ```dart invokeMethod('getScale') ``` -------------------------------- ### Format Code Source: https://github.com/endigo/flutter_pdfview/blob/master/CLAUDE.md Format all Dart code in the project according to standard style guidelines. ```bash dart format . ```