使用Syncfusion Flutter PDF包时,如何让生成的PDF直接在浏览器打开?
如何在Chrome浏览器中直接打开Flutter Web生成的PDF?
我正在构建一个面向Chrome浏览器的Flutter Web应用,使用SyncFusion的Flutter PDF包生成PDF文件。现有代码可无报错生成简单报告并下载到浏览器,但希望生成的PDF能直接在浏览器中打开或询问用户是否打开。
原代码如下:
Future<void> createHoursReportPdf(DateTime reportDate) async { String reportTitle = "Hours Report for reportDate"; // Create a PDF document. PdfDocument document = PdfDocument(); // Add a page and draw text document.pages.add().graphics.drawString( reportTitle, PdfStandardFont(PdfFontFamily.helvetica, 20), brush: PdfSolidBrush(PdfColor(0, 0, 0)), bounds: const Rect.fromLTWH(20, 60, 600, 30)); // Save the document List<int> bytes = await document.save(); // Dispose the document document.dispose(); // Download the output file - Requires import 'dart:html'; AnchorElement( href: "data:application/octet-stream;charset=utf-16le;base64,${base64.encode(bytes)}") ..setAttribute("download", "output.pdf") ..click(); }
我尝试将..setAttribute("download", "output.pdf")改为..setAttribute("inline", "output.pdf"),但仅导致下载文件名为无PDF后缀的‘download’。
解决方案
要实现PDF在浏览器中直接打开,需要调整两个核心点:
- 修改资源的MIME类型为
application/pdf(而非application/octet-stream),告诉浏览器这是PDF文件 - 移除
download属性(该属性会强制触发下载),并通过合适的方式让浏览器处理内联预览
方法1:修改Data URI方式(适合小文件)
直接调整原代码中的AnchorElement部分:
// 替换原有的下载代码段 AnchorElement( href: "data:application/pdf;base64,${base64.encode(bytes)}" ) ..target = "_blank" // 在新标签页打开PDF ..click();
方法2:使用Blob URL(推荐,适合大文件)
这种方式性能更优,浏览器处理大文件时更稳定:
import 'dart:html' as html; Future<void> createHoursReportPdf(DateTime reportDate) async { // ... 前面的PDF生成代码保持不变 ... List<int> bytes = await document.save(); document.dispose(); // 生成Blob对象和对应的URL final blob = html.Blob([bytes], 'application/pdf'); final pdfUrl = html.Url.createObjectUrlFromBlob(blob); // 创建锚点并触发打开 final anchor = html.AnchorElement(href: pdfUrl) ..target = "_blank" ..click(); // 释放Blob URL资源,避免内存泄漏 html.Url.revokeObjectUrl(pdfUrl); }
关键说明
inline并非AnchorElement的合法属性,之前的尝试是错误的- 设置
target="_blank"会让Chrome在新标签页中打开PDF,浏览器会根据自身设置决定是直接预览还是询问用户操作 - Blob URL相比Data URI更适合大文件,不会因为过长的URI字符串导致性能问题
内容的提问来源于stack exchange,提问作者SqueezeOJ
相关产品推荐
相关产品推荐

