### PDFx Package Installation and Setup Source: https://pub.dev/packages/pdfx Instructions for adding the pdfx dependency to your Flutter project and running setup tools for web and Windows. ```APIDOC ## Installation In your flutter project add the dependency: ```dart flutter pub add pdfx ``` ## Web Setup For web, run the following tool to automatically add the pdfjs library (CDN) in `index.html`: ```bash flutter pub run pdfx:install_web ``` ## Windows Setup For Windows, run the following tool to automatically add an override for the pdfium version property in `CMakeLists.txt`: ```bash flutter pub run pdfx:install_windows ``` ``` -------------------------------- ### Main Application Widget Setup Source: https://pub.dev/packages/pdfx/example This code sets up the main application widget, configuring the MaterialApp with themes and determining which page to display based on the platform. It imports necessary packages for Flutter UI, platform detection, and specific example pages. ```dart import 'package:flutter/material.dart'; import 'package:pdfx_example/pinch.dart'; import 'package:pdfx_example/simple.dart'; import 'package:universal_platform/universal_platform.dart'; void main() => runApp(const MyApp()); class MyApp extends StatefulWidget { const MyApp({Key? key}) : super(key: key); @override State createState() => _MyAppState(); } class _MyAppState extends State { @override Widget build(BuildContext context) => MaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData(primaryColor: Colors.white), darkTheme: ThemeData.dark(), home: UniversalPlatform.isWindows ? const SimplePage() : const PinchPage(), ); } ``` -------------------------------- ### Install web support Source: https://pub.dev/packages/pdfx Automatically add the required pdfjs library to your index.html for web support. ```bash flutter pub run pdfx:install_web ``` -------------------------------- ### Install windows support Source: https://pub.dev/packages/pdfx Automatically configure the pdfium version property in your CMakeLists.txt file. ```bash flutter pub run pdfx:install_windows ``` -------------------------------- ### Install pdfx dependency Source: https://pub.dev/packages/pdfx Add the package to your Flutter project. ```bash flutter pub add pdfx ``` -------------------------------- ### Basic Usage Example Source: https://pub.dev/packages/pdfx Demonstrates how to use PdfControllerPinch and PdfViewPinch for interactive PDF viewing, and PdfController and PdfView for simpler viewing. ```APIDOC ## Usage Example ```dart import 'package:pdfx/pdfx.dart'; // For interactive PDF viewing with pinch-to-zoom (not supported on Windows) final pdfPinchController = PdfControllerPinch( document: PdfDocument.openAsset('assets/sample.pdf'), ); PdfViewPinch( controller: pdfPinchController, ); // For simple PDF viewing with a single render (quality may decrease on zoom) final pdfController = PdfController( document: PdfDocument.openAsset('assets/sample.pdf'), ); PdfView( controller: pdfController, ); ``` ``` -------------------------------- ### Install Network File Dependency Source: https://pub.dev/packages/pdfx Add the internet_file package to support network-based PDF loading. ```bash flutter pub add internet_file ``` -------------------------------- ### Initialize PDF Viewers Source: https://pub.dev/packages/pdfx Setup controllers and display PDF documents using either the pinch-zoom or standard viewer. ```dart import 'package:pdfx/pdfx.dart'; final pdfPinchController = PdfControllerPinch( document: PdfDocument.openAsset('assets/sample.pdf'), ); // Pdf view with re-render pdf texture on zoom (not loose quality on zoom) // Not supported on windows PdfViewPinch( controller: pdfPinchController, ); //-- or --// final pdfController = PdfController( document: PdfDocument.openAsset('assets/sample.pdf'), ); // Simple Pdf view with one render of page (loose quality on zoom) PdfView( controller: pdfController, ); ``` -------------------------------- ### Install pdfx via Terminal Source: https://pub.dev/packages/pdfx/install Use this command in your terminal to add the pdfx package to your Flutter project. ```bash $ flutter pub add pdfx ``` -------------------------------- ### Document Control and Information Source: https://pub.dev/packages/pdfx Examples of how to open new documents, control page navigation, and retrieve document information like current page and total pages. ```APIDOC ## Document Control and Information ### Opening a New Document ```dart pdfController.openDocument(PdfDocument.openAsset('assets/sample.pdf')); ``` ### Page Control ```dart // Jump to a specific page pdfController.jumpTo(3); // Animate to a specific page _pdfController.animateToPage(3, duration: Duration(milliseconds: 250), curve: Curves.ease); // Animate to the next page _pdfController.nextPage(duration: Duration(milliseconds: 250), curve: Curves.easeIn); // Animate to the previous page _pdfController.previousPage(duration: Duration(milliseconds: 250), curve: Curves.easeOut); // Get document progress (0.0 - start, 1.0 - end) _pdfController.documentProgress; ``` ### Additional PDF Info ```dart // Actual showed page pdfController.page; // Count of all pages in document pdfController.pagesCount; ``` ``` -------------------------------- ### Analyze deprecated scale method Source: https://pub.dev/packages/pdfx/score Example of a deprecated scale method call identified during static analysis. ```dart ╷ 970 │ return matrix.clone()..scale(clampedScale); │ ^^^^^ ╵ ``` -------------------------------- ### Analyze deprecated translate method Source: https://pub.dev/packages/pdfx/score Example of a deprecated translate method call identified during static analysis. ```dart ╷ 862 │ ..translate( │ ^^^^^^^^^ ╵ ``` -------------------------------- ### Implement Custom Builders Source: https://pub.dev/packages/pdfx Define custom widget builders and transition logic for PdfViewPinch and PdfView components. ```dart // Need static methods for builders arguments class SomeWidget { static Widget builder( BuildContext context, PdfViewPinchBuilders builders, PdfLoadingState state, WidgetBuilder loadedBuilder, PdfDocument? document, Exception? loadingError, ) { final Widget content = () { switch (state) { case PdfLoadingState.loading: return KeyedSubtree( key: const Key('pdfx.root.loading'), child: builders.documentLoaderBuilder?.call(context) ?? const SizedBox(), ); case PdfLoadingState.error: return KeyedSubtree( key: const Key('pdfx.root.error'), child: builders.errorBuilder?.call(context, loadingError!) ?? Center(child: Text(loadingError.toString())), ); case PdfLoadingState.success: return KeyedSubtree( key: Key('pdfx.root.success.${document!.id}'), child: loadedBuilder(context), ); } }(); final defaultBuilder = builders as PdfViewPinchBuilders; final options = defaultBuilder.options; return AnimatedSwitcher( duration: options.loaderSwitchDuration, transitionBuilder: options.transitionBuilder, child: content, ); } static Widget transitionBuilder(Widget child, Animation animation) => FadeTransition(opacity: animation, child: child); static PhotoViewGalleryPageOptions pageBuilder( BuildContext context, Future pageImage, int index, PdfDocument document, ) => PhotoViewGalleryPageOptions( imageProvider: PdfPageImageProvider( pageImage, index, document.id, ), minScale: PhotoViewComputedScale.contained * 1, maxScale: PhotoViewComputedScale.contained * 3.0, initialScale: PhotoViewComputedScale.contained * 1.0, heroAttributes: PhotoViewHeroAttributes(tag: '${document.id}-$index'), ); } PdfViewPinch( controller: pdfPinchController, builders: PdfViewPinchBuilders( options: const DefaultBuilderOptions( loaderSwitchDuration: const Duration(seconds: 1), transitionBuilder: SomeWidget.transitionBuilder, ), documentLoaderBuilder: (_) => const Center(child: CircularProgressIndicator()), pageLoaderBuilder: (_) => const Center(child: CircularProgressIndicator()), errorBuilder: (_, error) => Center(child: Text(error.toString())), builder: SomeWidget.builder, ), ) PdfView( controller: pdfController, builders: PdfViewBuilders( // All from `PdfViewPinch` and: pageBuilder: SomeWidget.pageBuilder, ), ); ``` -------------------------------- ### Custom Builders Source: https://pub.dev/packages/pdfx Explains how to use custom builders for various states (loading, error, success) and page building in PdfView and PdfViewPinch. ```APIDOC ## Custom Builders This section details how to implement custom builders for `PdfView` and `PdfViewPinch` to control the UI for different loading states and page rendering. ### `PdfViewPinchBuilders` and `PdfViewBuilders` These classes allow you to define custom widgets for: - `documentLoaderBuilder`: Widget shown while the document is loading. - `pageLoaderBuilder`: Widget shown while a page is loading. - `errorBuilder`: Widget shown when an error occurs during loading. - `builder`: A static method to construct the main content widget. - `pageBuilder`: A static method to configure how each page is built (specific to `PdfView`). ### Example Usage ```dart // Static methods for builders arguments class SomeWidget { static Widget builder( BuildContext context, PdfViewPinchBuilders builders, PdfLoadingState state, WidgetBuilder loadedBuilder, PdfDocument? document, Exception? loadingError, ) { // ... implementation to switch between loading, error, and success states ... return AnimatedSwitcher( duration: options.loaderSwitchDuration, transitionBuilder: options.transitionBuilder, child: content, ); } static Widget transitionBuilder(Widget child, Animation animation) => FadeTransition(opacity: animation, child: child); static PhotoViewGalleryPageOptions pageBuilder( BuildContext context, Future pageImage, int index, PdfDocument document, ) => PhotoViewGalleryPageOptions( imageProvider: PdfPageImageProvider( pageImage, index, document.id, ), minScale: PhotoViewComputedScale.contained * 1, maxScale: PhotoViewComputedScale.contained * 3.0, initialScale: PhotoViewComputedScale.contained * 1.0, heroAttributes: PhotoViewHeroAttributes(tag: '${document.id}-$index'), ); } // PdfViewPinch Example PdfViewPinch( controller: pdfPinchController, builders: PdfViewPinchBuilders( options: const DefaultBuilderOptions( loaderSwitchDuration: const Duration(seconds: 1), transitionBuilder: SomeWidget.transitionBuilder, ), documentLoaderBuilder: (_) => const Center(child: CircularProgressIndicator()), pageLoaderBuilder: (_) => const Center(child: CircularProgressIndicator()), errorBuilder: (_, error) => Center(child: Text(error.toString())), builder: SomeWidget.builder, ), ) // PdfView Example PdfView( controller: pdfController, builders: PdfViewBuilders( // All from `PdfViewPinch` and: pageBuilder: SomeWidget.pageBuilder, ), ); ``` ``` -------------------------------- ### Configure PdfViewPinch with Builders Source: https://pub.dev/packages/pdfx/changelog Use the builders argument to customize the loading, error, and transition states of the PdfViewPinch widget. ```dart PdfViewPinch( builders: PdfViewPinchBuilders( options: const DefaultBuilderOptions( loaderSwitchDuration: const Duration(seconds: 1), transitionBuilder: SomeWidget.transitionBuilder, ), documentLoaderBuilder: (_) => const Center(child: CircularProgressIndicator()), pageLoaderBuilder: (_) => const Center(child: CircularProgressIndicator()), errorBuilder: (_, error) => Center(child: Text(error.toString())), builder: SomeWidget.builder, ), ) ``` -------------------------------- ### Handle PDF callbacks Source: https://pub.dev/packages/pdfx Listen to document loading and page change events. ```dart PdfView( controller: pdfController, onDocumentLoaded: (document) {}, onPageChanged: (page) {}, ); ``` -------------------------------- ### Custom Renderer Options Source: https://pub.dev/packages/pdfx Demonstrates how to provide a custom renderer function to the PdfView widget for controlling how each page is rendered. ```APIDOC ## Custom Renderer Options This section shows how to customize the rendering of PDF pages using the `renderer` property of the `PdfView` widget. ### Usage Provide a function to the `renderer` parameter that accepts a `PdfPage` object and returns a widget representing the rendered page. You can control properties like `width`, `height`, `format`, and `backgroundColor`. ```dart PdfView( controller: pdfController, renderer: (PdfPage page) => page.render( width: page.width * 2, height: page.height * 2, format: PdfPageImageFormat.jpeg, backgroundColor: '#FFFFFF', ), ); ``` ``` -------------------------------- ### Configure Custom Renderer Options Source: https://pub.dev/packages/pdfx Define custom rendering parameters such as resolution, format, and background color for a PdfView. ```dart PdfView( controller: pdfController, renderer: (PdfPage page) => page.render( width: page.width * 2, height: page.height * 2, format: PdfPageImageFormat.jpeg, backgroundColor: '#FFFFFF', ), ); ``` -------------------------------- ### PdfView and PdfViewPinch API Source: https://pub.dev/packages/pdfx Describes the parameters for PdfView and PdfViewPinch widgets, including controller, callbacks, and customization options. ```APIDOC ## PdfView & PdfViewPinch Parameters | Parameter | Description | PdfViewPinch / PdfView | |-------------------|---------------------------------------------------|------------------------| | controller | Pages control. See page control and additional pdf info | + / + | | onPageChanged | Called whenever the page in the center of the viewport changes. See Document callbacks | + / + | | onDocumentLoaded | Called when a document is loaded. See Document callbacks | + / + | | onDocumentError | Called when a document loading error. Exception is passed in the attributes | + / + | | builders | Set of pdf view builders. See Custom builders | + / + | | scrollDirection | Page turning direction | + / + | | reverse | Reverse scroll direction, useful for RTL support | - / + | | renderer | Custom PdfRenderer options. See custom renderer options | - / + | | pageSnapping | Set to false for mouse wheel scroll on web | - / + | | physics | How the widgets should respond to user input | - / + | | padding | Padding for the every page. | + / - | | minScale | The minimum document zoom scale. | + / - | | maxScale | The maximum document zoom scale. | + / - ``` -------------------------------- ### Open PDF document Source: https://pub.dev/packages/pdfx Update the controller to display a different PDF document. ```dart pdfController.openDocument(PdfDocument.openAsset('assets/sample.pdf')); ``` -------------------------------- ### Document Callbacks and Page Number Display Source: https://pub.dev/packages/pdfx Shows how to implement callbacks for document loading and page changes, and how to display the current page number and total page count. ```APIDOC ## Document Callbacks and Page Number Display ### Implementing Callbacks ```dart PdfView( controller: pdfController, onDocumentLoaded: (document) { // Handle document loaded event }, onPageChanged: (page) { // Handle page changed event }, onDocumentError: (error) { // Handle document error event }, ); ``` ### Displaying Page Number and Count ```dart PdfPageNumber( controller: _pdfController, builder: (_, state, loadingState, pagesCount) => Container( alignment: Alignment.center, child: Text( '$page/${pagesCount ?? 0}', style: const TextStyle(fontSize: 22), ), ), ) ``` ``` -------------------------------- ### PdfViewBuilders and PdfViewPinchBuilders API Source: https://pub.dev/packages/pdfx Details the builders available for customizing the appearance and behavior of PDF views. ```APIDOC ## PdfViewBuilders & PdfViewPinchBuilders Parameters | Parameter | Description | PdfViewPinchBuilders / PdfViewBuilders | |---------------------|---------------------------------|----------------------------------------| | options | Additional options for builder | + / + | | documentLoaderBuilder | Widget showing when pdf document loading | + / + | | pageLoaderBuilder | Widget showing when pdf page loading | + / + | | errorBuilder | Show document loading error message | + / + | | builder | Root view builder for animate pdf loading state | + / + | | pageBuilder | Callback called to render a widget for each page. See custom page builder | - / + ``` -------------------------------- ### Open Network PDF Documents Source: https://pub.dev/packages/pdfx Load a PDF document from a remote URL using the internet_file package. ```dart import 'package:internet_file/internet_file.dart'; PdfDocument.openData(InternetFile.get('https://github.com/ScerIO/packages.flutter/raw/fd0c92ac83ee355255acb306251b1adfeb2f2fd6/packages/native_pdf_renderer/example/assets/sample.pdf')) ``` -------------------------------- ### Add pdfx to pubspec.yaml Source: https://pub.dev/packages/pdfx/install Manually add this dependency to your pubspec.yaml file to include the package in your project. ```yaml dependencies: pdfx: ^2.9.2 ``` -------------------------------- ### Open Local PDF Documents Source: https://pub.dev/packages/pdfx Open PDF documents from assets, files, or data sources. ```dart // From assets (Android, Ios, MacOs, Web) final document = await PdfDocument.openAsset('assets/sample.pdf') // From file (Android, Ios, MacOs) final document = await PdfDocument.openFile('path/to/file/on/device') // From data (Android, Ios, MacOs, Web) final document = await PdfDocument.openData((FutureOr) data) ``` -------------------------------- ### PdfController and PdfControllerPinch API Source: https://pub.dev/packages/pdfx Details the parameters available for PdfController and PdfControllerPinch, used for managing PDF documents and pages. ```APIDOC ## PdfController & PdfControllerPinch Parameters | Parameter | Description | Default | |------------------|-------------------------------------------|---------| | document | The document to be displayed | - | | initialPage | The page to show when first creating the [PdfView] | 1 | | viewportFraction | The fraction of the viewport that each page should occupy. | 1.0 | ``` -------------------------------- ### Import pdfx in Dart Source: https://pub.dev/packages/pdfx/install Include this import statement at the top of your Dart files to access the pdfx library functionality. ```dart import 'package:pdfx/pdfx.dart'; ``` -------------------------------- ### Access PDF document info Source: https://pub.dev/packages/pdfx Retrieve current page index and total page count. ```dart // Actual showed page pdfController.page; // Count of all pages in document pdfController.pagesCount; ``` -------------------------------- ### Control PDF navigation Source: https://pub.dev/packages/pdfx Methods for jumping to specific pages or animating through the document. ```dart // Jump to specified page pdfController.jumpTo(3); // Animate to specified page _pdfController.animateToPage(3, duration: Duration(milliseconds: 250), curve: Curves.ease); // Animate to next page _pdfController.nextPage(duration: Duration(milliseconds: 250), curve: Curves.easeIn); // Animate to previous page _pdfController.previousPage(duration: Duration(milliseconds: 250), curve: Curves.easeOut); // Get document progrees 0.0 - start, 1.0 - end _pdfController.documentProgress; ``` -------------------------------- ### Render PDF Page Source: https://pub.dev/packages/pdfx Renders a specific PDF page into an image with configurable dimensions, format, and background. ```APIDOC ## Render PDF Page ### Description Render a PDF page to an image format. Note that some parameters like background color and cropRect are not supported on Web. ### Parameters #### Request Body - **width** (int) - Required - Rendered image width resolution - **height** (int) - Required - Rendered image height resolution - **format** (PdfPageImageFormat) - Optional - Compression format (PNG, JPEG, WEBP). Default: PdfPageImageFormat.PNG - **backgroundColor** (String) - Optional - Background fill color for JPEG. Default: '#ffffff' - **cropRect** (Rect) - Optional - Crop rectangle for the rendered image ### Request Example { "width": 1000, "height": 1000, "format": "PdfPageImageFormat.JPEG", "backgroundColor": "#ffffff" } ``` -------------------------------- ### Render PDF Page to Image Source: https://pub.dev/packages/pdfx Renders a PDF page into an image with specified dimensions, format, and background color. Note that certain parameters like background color and cropRect are not supported on Web. ```dart final pageImage = page.render( // rendered image width resolution, required width: page.width * 2, // rendered image height resolution, required height: page.height * 2, // Rendered image compression format, also can be PNG, WEBP* // Optional, default: PdfPageImageFormat.PNG // Web not supported format: PdfPageImageFormat.JPEG, // Image background fill color for JPEG // Optional, default '#ffffff' // Web not supported backgroundColor: '#ffffff', // Crop rect in image for render // Optional, default null // Web not supported cropRect: Rect.fromLTRB(left, top, right, bottom), ); ``` -------------------------------- ### Access PDF Page Source: https://pub.dev/packages/pdfx Retrieve a specific page from an opened document by its index. ```dart final page = document.getPage(pageNumber); // Starts from 1 ``` -------------------------------- ### Listen to Page Changes Source: https://pub.dev/packages/pdfx/changelog Use ValueListenableBuilder to reactively update UI elements based on the current page number from the controller. ```dart ValueListenableBuilder( valueListenable: controller.pageListenable, builder: (context, actualPageNumber, child) => Text(actualPageNumber.toString()), ) ``` -------------------------------- ### Close PDF Document Source: https://pub.dev/packages/pdfx Release resources by closing the document instance. ```dart document.close(); ``` -------------------------------- ### Monitor PDF Loading State Source: https://pub.dev/packages/pdfx/changelog Track the loading state of a PDF document to display appropriate UI components like progress indicators or error messages. ```dart ValueListenableBuilder( valueListenable: controller.loadingState, builder: (context, loadingState, loadingState) => (){ switch (loadingState) { case PdfLoadingState.loading: return const CircularProgressIndicator(); case PdfLoadingState.error: return const Text('Pdf load error'); case PdfLoadingState.success: return const Text('Pdf loaded'); } }(), ) ``` -------------------------------- ### PdfDocument API Source: https://pub.dev/packages/pdfx Details on opening, accessing, and closing PDF documents using the PdfDocument class. ```APIDOC ## PdfDocument API This section covers the `PdfDocument` class, including its properties and methods for opening, managing, and closing PDF documents. ### Properties - **sourceName** (String): Needed for the `toString` method. Contains a method for opening a document (file, data, or asset). - **id** (String): Document unique ID. Generated when opening the document. - **pagesCount** (int): Total number of pages in the document. Starts from 1. - **isClosed** (bool): Indicates if the document has been closed. ### Opening Documents **Local Document Open:** * **From Assets (Android, iOS, macOS, Web):** ```dart final document = await PdfDocument.openAsset('assets/sample.pdf'); ``` * **From File (Android, iOS, macOS):** ```dart final document = await PdfDocument.openFile('path/to/file/on/device'); ``` * **From Data (Android, iOS, macOS, Web):** ```dart final document = await PdfDocument.openData((FutureOr) data); ``` **Network Document Open:** Install the `internet_file` package: ```bash flutter pub add internet_file ``` Then use it to open documents from a URL: ```dart import 'package:internet_file/internet_file.dart'; final document = PdfDocument.openData(InternetFile.get('https://example.com/path/to/your/document.pdf')); ``` ### Opening a Page To get a specific page from the document: ```dart final page = document.getPage(pageNumber); // pageNumber starts from 1 ``` ### Closing a Document It's important to close the document when it's no longer needed to free up resources: ```dart document.close(); ``` ``` -------------------------------- ### Display PDF Page Numbers Source: https://pub.dev/packages/pdfx/changelog The PdfPageNumber widget displays the current page and total page count, handling null states during document loading. ```dart PdfPageNumber( controller: _pdfController, // When `loadingState != PdfLoadingState.success` `pagesCount` equals null_ builder: (_, state, loadingState, pagesCount) => Container( alignment: Alignment.center, child: Text( '$page/${pagesCount ?? 0}', style: const TextStyle(fontSize: 22), ), ), ) ``` -------------------------------- ### Close PDF Page Source: https://pub.dev/packages/pdfx Closes a PDF page to free resources. This is mandatory on Android to prevent application crashes when opening new pages. ```dart page.close(); ``` -------------------------------- ### Close PDF Page Source: https://pub.dev/packages/pdfx Closes a PDF page to free up resources. This is critical on Android to prevent application crashes. ```APIDOC ## Close PDF Page ### Description Closes the page instance. It is mandatory to call this method before opening a new page on Android to avoid potential crashes. ### Method POST ### Endpoint /page/close ### Request Example { "action": "close" } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.