Reputation: 106
I am trying to generate Pdf in flutter with pdf package in flutter Web. while doing so I found a solution for flutter web with this code ..
Uint8List bytes = await pdf.save() ;
final blob = html.Blob([bytes], 'application/pdf');
final url = html.Url.createObjectUrlFromBlob(blob);
html.window.open(url, "_blank");
html.Url.revokeObjectUrl(url);
this code worked fine in local host but is not running in web hosting . please help
Upvotes: 2
Views: 10006
Reputation: 11
My first answer was deleted, so I'll repost it.
To download files look this one: https://stackoverflow.com/a/60614367/18386517.
If you want to just open PDFs files inside your app try the pdfx package. Here is an example:
import 'dart:async';
import 'dart:typed_data';
import 'package:pdfx/pdfx.dart';
import 'package:flutter/material.dart';
class PdfLabPage extends StatefulWidget {
final String name;
final FutureOr<Uint8List> content;
const PdfLabPage({Key? key, required this.name, required this.content}) : super(key: key);
@override
State<PdfLabPage> createState() => _PdfLabPageState();
}
class _PdfLabPageState extends State<PdfLabPage> {
late PdfControllerPinch pdfController;
@override
void initState() {
pdfController = PdfControllerPinch(
document: PdfDocument.openData(widget.content)
);
super.initState();
}
@override
void dispose() {
pdfController.dispose();
super.dispose();
}
Widget pdfView() => PdfViewPinch(
controller: pdfController ,
onDocumentLoaded: (msg) {print(msg.toString());},
onDocumentError: (error) { print(error.toString());}
);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.name),
),
body:
Center(
child: pdfView(),
),
);
}
}
I got the content of the PDF file from the web using:
var url = "..."
final file = await http.get(Uri.parse(url));
final content = file.bodyBytes;
But you can load from assets (Android, Ios, MacOs, Web):
final document = await PdfDocument.openAsset('assets/sample.pdf')
From file (Android, Ios, MacOs):
final document = await PdfDocument.openFile('path/to/file/on/device')
From data (Android, Ios, MacOs, Web):
final document = await PdfDocument.openData((FutureOr<Uint8List>) data)
Upvotes: 1