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

Flutter Web生成PDF在新标签页显示字节乱码问题求助

Flutter Web 生成PDF并在新标签页正常展示的解决方案

问题分析

你当前的saveAndLaunchFile方法仅创建了PdfController和PdfView组件,但在Flutter Web环境下,这种方式无法直接在新标签页渲染PDF,反而会输出原始字节数据,导致显示乱码。正确思路是利用浏览器的Blob和URL API处理PDF字节流。

修正后的代码实现

步骤1:保留PDF生成逻辑(无需大幅改动)

Future<void> createPDF() async{
    final PdfDocument document = PdfDocument(); 

    document.pages.add().graphics.drawString(
        'Hello World!', PdfStandardFont(PdfFontFamily.helvetica, 20),
        brush: PdfSolidBrush(PdfColor(0, 0, 0)),
        bounds: Rect.fromLTWH(20, 60, 150, 30));

    List<int> bytes = await document.save();
    document.dispose();

    saveAndLaunchFile(bytes, 'NewConfig.pdf');
  }

步骤2:重写saveAndLaunchFile方法(适配Web环境)

import 'dart:html' as html;
import 'dart:typed_data';

Future<void> saveAndLaunchFile(List<int> bytes, String fileName) async {
  // 将字节转为Uint8List
  final Uint8List pdfBytes = Uint8List.fromList(bytes);
  
  // 创建Blob对象,指定PDF的MIME类型
  final html.Blob blob = html.Blob([pdfBytes], 'application/pdf');
  
  // 生成Blob的临时URL
  final String url = html.Url.createObjectUrlFromBlob(blob);
  
  // 在新标签页打开URL,浏览器会自动用内置阅读器渲染PDF
  html.window.open(url, '_blank');
  
  // 手动释放URL资源(可选,浏览器会自动回收,手动处理更规范)
  html.Url.revokeObjectUrl(url);
}

关键说明

  • 引入dart:html包:这是Flutter Web操作浏览器API的核心依赖,用于创建Blob和管理临时URL。
  • 指定MIME类型:application/pdf告诉浏览器识别文件类型,触发内置PDF阅读器渲染,而非直接显示字节。
  • 利用window.open:直接打开Blob URL后,浏览器会自动提供打印、下载、关闭等原生功能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 06:31:05