printing_web.dart 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. /*
  2. * Copyright (C) 2017, David PHAM-VAN <dev.nfet.net@gmail.com>
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import 'dart:async';
  17. import 'dart:html' as html;
  18. import 'dart:html';
  19. import 'dart:js' as js;
  20. import 'dart:js_util';
  21. import 'dart:typed_data';
  22. import 'dart:ui';
  23. import 'package:flutter/foundation.dart';
  24. import 'package:flutter_web_plugins/flutter_web_plugins.dart';
  25. import 'package:image/image.dart' as im;
  26. import 'package:pdf/pdf.dart';
  27. import 'src/callback.dart';
  28. import 'src/interface.dart';
  29. import 'src/mutex.dart';
  30. import 'src/pdfjs.dart';
  31. import 'src/printer.dart';
  32. import 'src/printing_info.dart';
  33. import 'src/raster.dart';
  34. /// Print plugin targeting Flutter on the Web
  35. class PrintingPlugin extends PrintingPlatform {
  36. /// Registers this class as the default instance of [PrintingPlugin].
  37. static void registerWith(Registrar registrar) {
  38. PrintingPlatform.instance = PrintingPlugin();
  39. }
  40. static const String _scriptId = '__net_nfet_printing_s__';
  41. static const String _frameId = '__net_nfet_printing__';
  42. final String _staticRoot = js.context['STATIC_ROOT']!.toString();
  43. static const _pdfJsVersion = 'js';
  44. final _loading = Mutex();
  45. bool get _hasPdfJsLib => js.context.callMethod('eval', <String>[
  46. 'typeof pdfjsLib !== "undefined" && pdfjsLib.GlobalWorkerOptions.workerSrc!="";'
  47. ]);
  48. Future<void> _initPlugin() async {
  49. await _loading.acquire();
  50. if (!_hasPdfJsLib) {
  51. final script = ScriptElement()
  52. ..type = 'text/javascript'
  53. ..async = true
  54. ..src = '$_staticRoot$_pdfJsVersion/pdf.min.js';
  55. assert(document.head != null);
  56. document.head!.append(script);
  57. await script.onLoad.first;
  58. if (js.context['pdfjsLib'] == null) {
  59. // In dev, requireJs is loaded in
  60. final require = js.JsObject.fromBrowserObject(js.context['require']);
  61. require.callMethod('config', <dynamic>[
  62. js.JsObject.jsify({
  63. 'paths': {
  64. 'pdfjs-dist/build/pdf': '$_staticRoot$_pdfJsVersion/pdf.min',
  65. 'pdfjs-dist/build/pdf.worker':
  66. '$_staticRoot$_pdfJsVersion/pdf.worker.min',
  67. }
  68. })
  69. ]);
  70. final completer = Completer<void>();
  71. js.context.callMethod('require', <dynamic>[
  72. js.JsObject.jsify(
  73. ['pdfjs-dist/build/pdf', 'pdfjs-dist/build/pdf.worker']),
  74. (dynamic app) {
  75. js.context['pdfjsLib'] = app;
  76. completer.complete();
  77. }
  78. ]);
  79. await completer.future;
  80. }
  81. js.context['pdfjsLib']['GlobalWorkerOptions']['workerSrc'] =
  82. '$_staticRoot$_pdfJsVersion/pdf.worker.min.js';
  83. }
  84. _loading.release();
  85. }
  86. @override
  87. Future<PrintingInfo> info() async {
  88. await _initPlugin();
  89. return PrintingInfo(
  90. canPrint: true,
  91. canShare: true,
  92. canRaster: _hasPdfJsLib,
  93. );
  94. }
  95. @override
  96. Future<bool> layoutPdf(
  97. Printer? printer,
  98. LayoutCallback onLayout,
  99. String name,
  100. PdfPageFormat format,
  101. bool dynamicLayout,
  102. bool usePrinterSettings,
  103. ) async {
  104. late Uint8List result;
  105. try {
  106. result = await onLayout(format);
  107. } catch (e, s) {
  108. InformationCollector? collector;
  109. assert(() {
  110. collector = () sync* {
  111. yield StringProperty('PageFormat', format.toString());
  112. };
  113. return true;
  114. }());
  115. FlutterError.reportError(FlutterErrorDetails(
  116. exception: e,
  117. stack: s,
  118. stackFilter: (input) => input,
  119. library: 'printing',
  120. context: ErrorDescription('while generating a PDF'),
  121. informationCollector: collector,
  122. ));
  123. rethrow;
  124. }
  125. if (result.isEmpty) {
  126. return false;
  127. }
  128. final String userAgent = js.context['navigator']['userAgent'];
  129. final isChrome = js.context['chrome'] != null;
  130. final isSafari = js.context['safari'] != null &&
  131. !userAgent.contains(RegExp(r'Version/14\.1\.'));
  132. final isMobile = userAgent.contains('Mobile');
  133. final isFirefox = userAgent.contains('Firefox');
  134. // Chrome, Safari, and Firefox on a desktop computer
  135. if ((isChrome || isSafari || isFirefox) && !isMobile) {
  136. final completer = Completer<bool>();
  137. final pdfFile = html.Blob(
  138. <Uint8List>[result],
  139. 'application/pdf',
  140. );
  141. final pdfUrl = html.Url.createObjectUrl(pdfFile);
  142. final html.HtmlDocument doc = js.context['document'];
  143. final script =
  144. doc.getElementById(_scriptId) ?? doc.createElement('script');
  145. script.setAttribute('id', _scriptId);
  146. script.setAttribute('type', 'text/javascript');
  147. script.innerText =
  148. '''function ${_frameId}_print(){var f=document.getElementById('$_frameId');f.focus();f.contentWindow.print();}''';
  149. doc.body!.append(script);
  150. final frame = doc.getElementById(_frameId) ?? doc.createElement('iframe');
  151. if (isFirefox) {
  152. // Set the iframe to be is visible on the page (guaranteed by fixed position) but hidden using opacity 0, because
  153. // this works in Firefox. The height needs to be sufficient for some part of the document other than the PDF
  154. // viewer's toolbar to be visible in the page
  155. frame.setAttribute('style',
  156. 'width: 1px; height: 100px; position: fixed; left: 0; top: 0; opacity: 0; border-width: 0; margin: 0; padding: 0');
  157. } else {
  158. // Hide the iframe in other browsers
  159. frame.setAttribute(
  160. 'style',
  161. 'visibility: hidden; height: 0; width: 0; position: absolute;',
  162. // 'height: 400px; width: 600px; position: absolute; z-index: 1000',
  163. );
  164. }
  165. frame.setAttribute('id', _frameId);
  166. frame.setAttribute('src', pdfUrl);
  167. final stopWatch = Stopwatch();
  168. html.EventListener? load;
  169. load = (html.Event event) {
  170. frame.removeEventListener('load', load);
  171. Timer(Duration(milliseconds: isSafari ? 500 : 0), () {
  172. try {
  173. stopWatch.start();
  174. js.context.callMethod('${_frameId}_print');
  175. stopWatch.stop();
  176. completer.complete(true);
  177. } catch (e) {
  178. assert(() {
  179. // ignore: avoid_print
  180. print('Error: $e');
  181. return true;
  182. }());
  183. completer.complete(_getPdf(result));
  184. }
  185. });
  186. };
  187. frame.addEventListener('load', load);
  188. doc.body!.append(frame);
  189. final res = await completer.future;
  190. // If print() is synchronous
  191. if (stopWatch.elapsedMilliseconds > 1000) {
  192. frame.remove();
  193. script.remove();
  194. }
  195. return res;
  196. }
  197. return _getPdf(result);
  198. }
  199. @override
  200. Future<bool> sharePdf(
  201. Uint8List bytes,
  202. String filename,
  203. Rect bounds,
  204. String? subject,
  205. String? body,
  206. List<String>? emails,
  207. ) async {
  208. return _getPdf(bytes, filename: filename);
  209. }
  210. Future<bool> _getPdf(Uint8List bytes, {String? filename}) async {
  211. final pdfFile = html.Blob(
  212. <Uint8List>[bytes],
  213. 'application/pdf',
  214. );
  215. final pdfUrl = html.Url.createObjectUrl(pdfFile);
  216. final html.HtmlDocument doc = js.context['document'];
  217. final link = html.AnchorElement(href: pdfUrl);
  218. if (filename != null) {
  219. link.download = filename;
  220. } else {
  221. link.target = '_blank';
  222. }
  223. doc.body?.append(link);
  224. link.click();
  225. link.remove();
  226. return true;
  227. }
  228. @override
  229. Future<Uint8List> convertHtml(
  230. String html,
  231. String? baseUrl,
  232. PdfPageFormat format,
  233. ) {
  234. throw UnimplementedError();
  235. }
  236. @override
  237. Future<List<Printer>> listPrinters() {
  238. throw UnimplementedError();
  239. }
  240. @override
  241. Future<Printer> pickPrinter(
  242. Rect bounds,
  243. ) {
  244. throw UnimplementedError();
  245. }
  246. @override
  247. Stream<PdfRaster> raster(
  248. Uint8List document,
  249. List<int>? pages,
  250. double dpi,
  251. ) async* {
  252. await _initPlugin();
  253. final t = PdfJs.getDocument(Settings()..data = document);
  254. try {
  255. final d = await promiseToFuture<PdfJsDoc>(t.promise);
  256. final numPages = d.numPages;
  257. final html.CanvasElement canvas =
  258. js.context['document'].createElement('canvas');
  259. final context = canvas.getContext('2d') as html.CanvasRenderingContext2D?;
  260. final _pages =
  261. pages ?? Iterable<int>.generate(numPages, (index) => index);
  262. for (final i in _pages) {
  263. final page = await promiseToFuture<PdfJsPage>(d.getPage(i + 1));
  264. try {
  265. final viewport =
  266. page.getViewport(Settings()..scale = dpi / PdfPageFormat.inch);
  267. canvas.height = viewport.height.toInt();
  268. canvas.width = viewport.width.toInt();
  269. final renderContext = Settings()
  270. ..canvasContext = context!
  271. ..viewport = viewport;
  272. await promiseToFuture<void>(page.render(renderContext).promise);
  273. // Convert the image to PNG
  274. final completer = Completer<void>();
  275. final blob = await canvas.toBlob();
  276. final data = BytesBuilder();
  277. final r = FileReader();
  278. r.readAsArrayBuffer(blob);
  279. r.onLoadEnd.listen(
  280. (ProgressEvent e) {
  281. data.add(r.result as List<int>);
  282. completer.complete();
  283. },
  284. );
  285. await completer.future;
  286. yield _WebPdfRaster(
  287. canvas.width!,
  288. canvas.height!,
  289. data.toBytes(),
  290. );
  291. } finally {
  292. page.cleanup();
  293. }
  294. }
  295. } finally {
  296. t.destroy();
  297. }
  298. }
  299. }
  300. class _WebPdfRaster extends PdfRaster {
  301. _WebPdfRaster(
  302. int width,
  303. int height,
  304. this.png,
  305. ) : super(width, height, Uint8List(0));
  306. final Uint8List png;
  307. Uint8List? _pixels;
  308. @override
  309. Uint8List get pixels {
  310. if (_pixels == null) {
  311. final img = im.PngDecoder().decodeImage(png)!;
  312. _pixels = img.data.buffer.asUint8List();
  313. }
  314. return _pixels!;
  315. }
  316. @override
  317. Future<Image> toImage() async {
  318. final codec = await instantiateImageCodec(png);
  319. final frameInfo = await codec.getNextFrame();
  320. return frameInfo.image;
  321. }
  322. @override
  323. Future<Uint8List> toPng() async {
  324. return png;
  325. }
  326. }