I am trying to implement a file preview printing functionality in Flutter Web. My current approach creates a Blob from file bytes, generates a temporary URL using createObjectUrlFromBlob, and loads it into an IFrameElement. However, the challenge is invoking the print dialog for the file content instead of the entire current page.
Here is my current implementation:
class PrintFileHelper {
static void showPrintDialog({
required String fileName,
required List<int> bytes,
required String mimeType,
}) {
if (bytes.isEmpty) {
print('bytes empty.');
return;
}
try {
final blob = html.Blob([bytes], mimeType);
final url = html.Url.createObjectUrlFromBlob(blob);
final iframe = html.IFrameElement()
..src = url
..style.border = 'none'
..style.height = '0'
..style.width = '0'
..style.display = 'none';
html.document.body?.append(iframe);
iframe.onLoad.listen((_) {
final contentWindow = iframe.contentWindow;
if (contentWindow != null) {
try {
html.window.print();
} catch (e) {
print('print ERROR: $e');
}
} else {
print('contentWindow null.');
}
html.document.body?.children.remove(iframe);
html.Url.revokeObjectUrl(url);
});
} catch (e) {
print('create file error: $e');
}
}
}
The problem is that html.window.print() only prints the current page, and there doesn’t seem to be a straightforward way to invoke print() for the content loaded in the iframe.
The contentWindow.print() method doesn’t seem to be accessible for iframes in Dart/Flutter Web.
Is there a way to directly print the content loaded in the iframe without printing the entire page?
How can I implement this functionality properly in Flutter Web?