You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter Web如何调用Chrome打印弹窗打印指定图片?

解决方案:仅打印指定图片(Flutter Web)

既然你已经成功将Widget转为图片(Uint8List格式),可以直接利用浏览器原生API实现仅打印该图片的需求,步骤如下:

  1. 将捕获到的图片数据转换为浏览器可识别的Data URL
  2. 创建临时DOM元素承载图片,设置打印专属样式
  3. 调用浏览器打印功能,完成后清理临时元素

修改你的代码如下:

import 'dart:html' as html;
import 'dart:typed_data';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:login_example/presentation/component/custom_input.dart';
import 'package:login_example/presentation/component/loading_button.dart';
import 'package:widgets_to_image/widgets_to_image.dart';

class ApplicationExapmle extends StatelessWidget {
  const ApplicationExapmle({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final WidgetsToImageController controller = WidgetsToImageController();

    return WidgetsToImage(
      controller: controller,
      child: Column(
        children: [
          const Center(child: Text("test")),
          const SizedBox(height: 20),
          Center(child: CustomInput(controller: TextEditingController())),
          LoadingButton(
            onTap: () async {
              Uint8List? image = await controller.capture();
              if (image == null) return;

              // 1. 将Uint8List转为Data URL
              final base64Image = base64Encode(image);
              final dataUrl = 'data:image/png;base64,$base64Image';

              // 2. 创建临时图片元素和全屏容器
              final img = html.ImageElement()
                ..src = dataUrl
                ..style.maxWidth = '100%'
                ..style.maxHeight = '100vh';

              final container = html.DivElement()
                ..style.position = 'fixed'
                ..style.top = '0'
                ..style.left = '0'
                ..style.width = '100%'
                ..style.height = '100%'
                ..style.backgroundColor = 'white'
                ..style.display = 'flex'
                ..style.justifyContent = 'center'
                ..style.alignItems = 'center'
                ..append(img);

              // 添加到页面body
              html.document.body?.append(container);

              // 3. 调用打印,完成后强制清理临时元素
              try {
                await html.window.print();
              } finally {
                container.remove();
              }
            },
            textButton: "打印图片",
          )
        ],
      ),
    );
  }
}

关键说明:

  • 引入dart:html直接操作浏览器DOM,这是Flutter Web特有的能力
  • 临时容器设置全屏白色背景,避免打印时出现透明区域或页面其他内容
  • 图片设置maxWidth和maxHeight确保在打印页面内自适应尺寸
  • 使用try/finally保证无论打印成功还是用户取消,都会移除临时元素,避免污染页面

你之前用printing库没达成需求,大概率是因为默认配置会打印整个页面内容,而上述方法直接聚焦目标图片,更贴合你的场景。

内容的提问来源于stack exchange,提问作者Jvictororiz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 17:25:22