pdf_preview.dart 13.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
/*
 * Copyright (C) 2017, David PHAM-VAN <dev.nfet.net@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import 'package:flutter/material.dart';
import 'package:pdf/pdf.dart';
import 'package:pdf/widgets.dart' as pw;

import '../callback.dart';
import '../printing.dart';
import '../printing_info.dart';
import 'action_bar_theme.dart';
import 'actions.dart';
import 'controller.dart';
import 'custom.dart';

export 'custom.dart';
export 'page.dart' show PdfPreviewPageData;

/// Flutter widget that uses the rasterized pdf pages to display a document.
class PdfPreview extends StatefulWidget {
  /// Show a pdf document built on demand
  const PdfPreview({
    super.key,
    required this.build,
    this.initialPageFormat,
    this.allowPrinting = true,
    this.allowSharing = true,
    this.maxPageWidth,
    this.canChangePageFormat = true,
    this.canChangeOrientation = true,
    this.canDebug = true,
    this.actions,
    this.pageFormats = _defaultPageFormats,
    this.onError,
    this.onPrinted,
    this.onPrintError,
    this.onShared,
    this.scrollViewDecoration,
    this.pdfPreviewPageDecoration,
    this.pdfFileName,
    this.useActions = true,
    this.pages,
    this.dynamicLayout = true,
    this.shareActionExtraBody,
    this.shareActionExtraSubject,
    this.shareActionExtraEmails,
    this.previewPageMargin,
    this.padding,
    this.shouldRepaint = false,
    this.loadingWidget,
    this.onPageFormatChanged,
    this.dpi,
    this.actionBarTheme = const PdfActionBarTheme(),
    this.enableScrollToPage = false,
    this.onZoomChanged,
  }) : _pagesBuilder = null;

  /// Build a custom layout.
  ///
  /// ```dart
  /// PdfPreview.builder(
  ///   build: (format) => _generatePdf(format, title),
  ///   pagesBuilder: (context, pages) => SingleChildScrollView(
  ///     child: Wrap(
  ///       spacing: 8,
  ///       runSpacing: 8,
  ///       children: [
  ///         for (final page in pages)
  ///           Container(
  ///             color: Colors.white,
  ///             child: Image(
  ///               image: page.image,
  ///               width: 300,
  ///             ),
  ///           )
  ///       ],
  ///     ),
  ///   ),
  /// )
  /// ```
  const PdfPreview.builder({
    super.key,
    required this.build,
    this.initialPageFormat,
    this.allowPrinting = true,
    this.allowSharing = true,
    this.maxPageWidth,
    this.canChangePageFormat = true,
    this.canChangeOrientation = true,
    this.canDebug = true,
    this.actions,
    this.pageFormats = _defaultPageFormats,
    this.onError,
    this.onPrinted,
    this.onPrintError,
    this.onShared,
    this.scrollViewDecoration,
    this.pdfPreviewPageDecoration,
    this.pdfFileName,
    this.useActions = true,
    this.pages,
    this.dynamicLayout = true,
    this.shareActionExtraBody,
    this.shareActionExtraSubject,
    this.shareActionExtraEmails,
    this.previewPageMargin,
    this.padding,
    this.shouldRepaint = false,
    this.loadingWidget,
    this.onPageFormatChanged,
    this.dpi,
    this.actionBarTheme = const PdfActionBarTheme(),
    required CustomPdfPagesBuilder pagesBuilder,
    this.enableScrollToPage = false,
    this.onZoomChanged,
  }) : _pagesBuilder = pagesBuilder;

  static const _defaultPageFormats = <String, PdfPageFormat>{
    'A4': PdfPageFormat.a4,
    'Letter': PdfPageFormat.letter,
  };

  /// Called when a pdf document is needed
  final LayoutCallback build;

  /// Pdf page format asked for the first display
  final PdfPageFormat? initialPageFormat;

  /// Add a button to print the pdf document
  final bool allowPrinting;

  /// Add a button to share the pdf document
  final bool allowSharing;

  /// Allow disable actions
  final bool useActions;

  /// Maximum width of the pdf document on screen
  final double? maxPageWidth;

  /// Add a drop-down menu to choose the page format
  final bool canChangePageFormat;

  /// Add a switch to change the page orientation
  final bool canChangeOrientation;

  /// Add a switch to show debug view
  final bool canDebug;

  /// Additional actions to add to the widget
  final List<Widget>? actions;

  /// List of page formats the user can choose
  final Map<String, PdfPageFormat> pageFormats;

  /// Widget to display if the PDF document cannot be displayed
  final Widget Function(BuildContext context, Object error)? onError;

  /// Called if the user prints the pdf document
  final void Function(BuildContext context)? onPrinted;

  /// Called if an error creating the Pdf occurred
  final void Function(BuildContext context, dynamic error)? onPrintError;

  /// Called if the user shares the pdf document
  final void Function(BuildContext context)? onShared;

  /// Decoration of scrollView
  final Decoration? scrollViewDecoration;

  /// Decoration of PdfPreviewPage
  final Decoration? pdfPreviewPageDecoration;

  /// Name of the PDF when sharing. It must include the extension.
  final String? pdfFileName;

  /// Pages to display. Default will display all the pages.
  final List<int>? pages;

  /// Request page re-layout to match the printer paper and margins.
  /// Mitigate an issue with iOS and macOS print dialog that prevent any
  /// channel message while opened.
  final bool dynamicLayout;

  /// email subject when email application is selected from the share dialog
  final String? shareActionExtraSubject;

  /// extra text to share with Pdf document
  final String? shareActionExtraBody;

  /// list of email addresses which will be filled automatically if the email application
  /// is selected from the share dialog.
  /// This will work only for Android platform.
  final List<String>? shareActionExtraEmails;

  /// margin for the document preview page
  ///
  /// defaults to [EdgeInsets.only(left: 20, top: 8, right: 20, bottom: 12)],
  final EdgeInsets? previewPageMargin;

  /// padding for the pdf_preview widget
  final EdgeInsets? padding;

  /// Force repainting the PDF document
  final bool shouldRepaint;

  /// Custom loading widget to use that is shown while PDF is being generated.
  /// If null, a [CircularProgressIndicator] is used instead.
  final Widget? loadingWidget;

  /// The page format has changed
  final ValueChanged<PdfPageFormat>? onPageFormatChanged;

  /// The rendering dots per inch resolution
  /// If not provided, this value is calculated.
  final double? dpi;

  /// The style of actions bar.
  final PdfActionBarTheme actionBarTheme;

  /// clients can pass this builder to render
  /// their own pages.
  final CustomPdfPagesBuilder? _pagesBuilder;

  /// Whether scroll to page functionality enabled.
  final bool enableScrollToPage;

  /// The zoom mode has changed
  final ValueChanged<bool>? onZoomChanged;

  @override
  PdfPreviewState createState() => PdfPreviewState();
}

class PdfPreviewState extends State<PdfPreview> {
  final previewWidget = GlobalKey<PdfPreviewCustomState>();
  late PdfPreviewData previewData;

  /// Printing subsystem information
  PrintingInfo? info;

  var infoLoaded = false;

  PdfPageFormat computeActualPageFormat() {
    var format = previewData.pageFormat;
    final pages = previewWidget.currentState?.pages ?? const [];
    final dpi = previewWidget.currentState?.dpi ?? PdfPageFormat.inch;

    if (!widget.canChangePageFormat && pages.isNotEmpty) {
      format = PdfPageFormat(
        pages.first.width * PdfPageFormat.inch / dpi,
        pages.first.height * PdfPageFormat.inch / dpi,
        marginAll: 5 * PdfPageFormat.mm,
      );
    }

    return format;
  }

  @override
  void initState() {
    previewData = PdfPreviewData(
      buildDocument: widget.build,
      pageFormats: widget.pageFormats.isNotEmpty
          ? widget.pageFormats
          : PdfPreview._defaultPageFormats,
      initialPageFormat: widget.initialPageFormat,
      onComputeActualPageFormat: computeActualPageFormat,
    );

    previewData.addListener(() {
      if (mounted) {
        setState(() {});
      }
      widget.onPageFormatChanged?.call(previewData.pageFormat);
    });

    super.initState();
  }

  @override
  void dispose() {
    previewData.dispose();
    super.dispose();
  }

  @override
  void didUpdateWidget(covariant PdfPreview oldWidget) {
    if (oldWidget.build != widget.build ||
        widget.shouldRepaint ||
        widget.pageFormats != oldWidget.pageFormats) {
      previewData = PdfPreviewData(
        buildDocument: widget.build,
        pageFormats: widget.pageFormats.isNotEmpty
            ? widget.pageFormats
            : PdfPreview._defaultPageFormats,
        initialPageFormat: previewData.pageFormat,
        onComputeActualPageFormat: computeActualPageFormat,
      );
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  void didChangeDependencies() {
    if (!infoLoaded) {
      infoLoaded = true;
      Printing.info().then((PrintingInfo printingInfo) {
        if (!mounted) {
          return;
        }
        setState(() {
          info = printingInfo;
        });
      });
    }

    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final iconColor = theme.primaryIconTheme.color ?? Colors.white;

    final actions = <Widget>[];

    if (widget.useActions && widget.allowPrinting && info?.canPrint == true) {
      actions.add(
        PdfPrintAction(
          jobName: widget.pdfFileName,
          dynamicLayout: widget.dynamicLayout,
          onPrinted: widget.onPrinted == null
              ? null
              : () => widget.onPrinted!(context),
          onPrintError: widget.onPrintError == null
              ? null
              : (dynamic error) => widget.onPrintError!(context, error),
        ),
      );
    }

    if (widget.useActions && widget.allowSharing && info?.canShare == true) {
      actions.add(
        PdfShareAction(
          filename: widget.pdfFileName,
          onShared: widget.onPrinted == null
              ? null
              : () => widget.onPrinted!(context),
          subject: widget.shareActionExtraSubject,
          emails: widget.shareActionExtraEmails,
          body: widget.shareActionExtraBody,
        ),
      );
    }

    if (widget.useActions && widget.canChangePageFormat) {
      actions.add(
        PdfPageFormatAction(
          pageFormats: widget.pageFormats,
        ),
      );
    }

    if (widget.useActions && widget.canChangeOrientation) {
      // ignore: prefer_const_constructors
      actions.add(PdfPageOrientationAction());
    }

    widget.actions?.forEach(actions.add);

    assert(() {
      if (actions.isNotEmpty && widget.canDebug) {
        actions.add(
          Switch(
            activeColor: Colors.red,
            value: pw.Document.debug,
            onChanged: (bool value) {
              setState(() {
                pw.Document.debug = value;
              });
              previewWidget.currentState?.raster();
            },
          ),
        );
      }

      return true;
    }());

    return PdfPreviewController(
      data: previewData,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Expanded(
            child: Builder(
              builder: (context) {
                final controller = PdfPreviewController.listen(context);
                return PdfPreviewCustom(
                  key: previewWidget,
                  build: controller.buildDocument,
                  loadingWidget: widget.loadingWidget,
                  maxPageWidth: widget.maxPageWidth,
                  onError: widget.onError,
                  padding: widget.padding,
                  pageFormat: controller.pageFormat,
                  pages: widget.pages,
                  pdfPreviewPageDecoration: widget.pdfPreviewPageDecoration,
                  previewPageMargin: widget.previewPageMargin,
                  scrollViewDecoration: widget.scrollViewDecoration,
                  shouldRepaint: widget.shouldRepaint,
                  pagesBuilder: widget._pagesBuilder,
                  dpi: widget.dpi,
                  enableScrollToPage: widget.enableScrollToPage,
                  onZoomChanged: widget.onZoomChanged,
                );
              },
            ),
          ),
          if (actions.isNotEmpty)
            IconTheme.merge(
              data: IconThemeData(
                color: widget.actionBarTheme.iconColor ?? iconColor,
              ),
              child: Material(
                elevation: widget.actionBarTheme.elevation,
                color:
                    widget.actionBarTheme.backgroundColor ?? theme.primaryColor,
                textStyle: widget.actionBarTheme.textStyle,
                child: SizedBox(
                  width: double.infinity,
                  height: widget.actionBarTheme.height,
                  child: SafeArea(
                    child: Wrap(
                      spacing: widget.actionBarTheme.actionSpacing,
                      alignment: widget.actionBarTheme.alignment,
                      runAlignment: widget.actionBarTheme.runAlignment,
                      crossAxisAlignment:
                          widget.actionBarTheme.crossAxisAlignment,
                      children: actions,
                    ),
                  ),
                ),
              ),
            ),
        ],
      ),
    );
  }
}