printDocument method

Future<void> printDocument()

Implementation

Future<void> printDocument() async {
  final document = pdfDocument;
  if (!enablePrintAction || document == null) {
    return;
  }

  try {
    final data = await document.getDataDart();
    final blob = html.Blob(<Object>[data], 'application/pdf');

    if (_printObjectUrl != null) {
      liPdfViewerBrowserBridge.revokeObjectUrl(_printObjectUrl!);
    }
    _printFrame?.remove();

    _printObjectUrl = liPdfViewerBrowserBridge.createObjectUrlFromBlob(blob);
    _printFrame = html.IFrameElement()
      ..id = 'liPdfViewerPrintFrame'
      ..name = 'liPdfViewerPrintFrame'
      ..src = _printObjectUrl
      ..style.display = 'none';

    html.document.body?.append(_printFrame!);
    _afterPrintSubscription?.cancel();
    _afterPrintSubscription = html.window.on['afterprint'].listen((_) {
      _disposePrintArtifacts();
    });

    await _printFrame!.onLoad.first;
    try {
      dynamic targetFrame = _printFrame?.contentWindow;
      if (targetFrame == null) {
        final frames = js_util.getProperty(html.window, 'frames');
        targetFrame = js_util.getProperty(frames, 'liPdfViewerPrintFrame');
      }
      if (targetFrame == null) {
        throw StateError('Print frame is not available.');
      }
      liPdfViewerBrowserBridge.printWindow(targetFrame);
    } catch (error) {
      _setError('Failed to print PDF: $error');
    }
  } catch (error) {
    _setError('Failed to prepare PDF printing: $error');
  }
}