To Generate PDF documents in Flutter can be achieved through several packages. Here are a few popular ones:
- pdf: This package provides a simple way to create and manipulate PDF documents in Dart.
- syncfusion_flutter_pdf: This package provides a comprehensive set of features for generating and manipulating PDF documents. https://pub.dev/packages/syncfusion_flutter_pdf The also have a lot of widget components thay may be used for free up until a moment you have enough money to pay them back https://www.syncfusion.com/sales/communitylicense
Here’s an example using the pdf package to generate a simple PDF:
First, add the following dependency to your pubspec.yaml
file:
dependencies:
pdf: ^3.11.3
Then, run flutter pub get
to install the package.
Now, you can use the following code to generate a PDF:
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:pdf/widgets.dart' as pw;
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) => MaterialApp(
home: MyHomePage(),
);
}
class MyHomePage extends StatelessWidget {
const MyHomePage({super.key});
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
title: Text('Generate PDF'),
),
body: Center(
child: ElevatedButton(
onPressed: () async {
final pdf = pw.Document();
pdf.addPage(pw.Page(
build: (context) {
return pw.Column(
children: [
pw.Text('Hello, World!',
style: pw.TextStyle(fontSize: 24)),
pw.SizedBox(height: 20),
pw.Text('This is a sample PDF generated by Flutter.',
style: pw.TextStyle(fontSize: 18)),
],
);
},
));
final bytes = await pdf.save();
saveAndShareFile(bytes, 'sample.pdf');
},
child: Text('Generate PDF'),
),
),
);
void saveAndShareFile(List<int> bytes, String filename) async {
final file = await File(filename).create();
await file.writeAsBytes(bytes);
if (kDebugMode) {
print('PDF saved to $filename');
}
}
}
This code will generate a simple PDF with two lines of text and save it to the device’s storage. The saveAndShareFile
function is used to create a file and write the PDF bytes to it.
Another Packages that may be mentioned here are:
- printing. This package allows you to print documents, including generating PDFs. It is a common in all printing to pdf on all operating systems, office software, etc – to have the feature “print to PDF“.
- flutter_pdfview: This package allows you to view PDFs in your Flutter app.
If you need to render HTML, not PDFs, you could read how to do it here: https://programtom.com/dev/2024/12/28/flutter-html/