How to draw a circular shape image in PDF document using Syncfusion Flutter PDF Library?
The Flutter PDF is a Flutter PDF library used to create, read, and edit PDF documents. Using this library, you can draw the image in a circular shape in the PDF document.
Steps to draw a circular shape image on PDF programmatically:
- Create a new Flutter application project.
1.1. Open Visual Studio Code (after installing the Dart and Flutter extensions as stated in the setup editor page).
1.2. Click View -> Command Palette…
1.3. Type Flutter and choose Flutter: New Application Project.
1.4. Enter the project name and press the Enter button.
1.5. Now choose the location of the project.
- Add the following code in your pubspec.yaml file to install the Syncfusion® Flutter PDF package in your application. It will be automatically downloaded from Pub once you trigger the flutter pub get command or the Get packages option from Visual Studio Code.
dependencies: syncfusion_flutter_pdf: ^20.3.49
- Import the following syncfusion_flutter_pdf package in your main.dart file.
import 'package:syncfusion_flutter_pdf/pdf.dart';
- Add the following code in the lib/main.dart file to create a simple button.
@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ TextButton( child: Text( 'Generate PDF', style: TextStyle(color: Colors.white), ), style: ButtonStyle( backgroundColor: MaterialStateProperty.resolveWith( (states) => Colors.blue)), onPressed: drawImage, ) ], ), ), ); }
- Add the following code to the drawImage method to draw a circular shape image on the PDF document programmatically.
Future<void> drawImage() async { // Create a new PDF document. PdfDocument document = PdfDocument(); // Add the page and get the graphics. PdfGraphics graphics = document.pages.add().graphics; // Set clip to the graphics to make a circular shape. graphics.save(); // Save the graphics before adding the clip. // Create path and set clip. graphics.setClip( path: PdfPath()..addEllipse(Rect.fromLTWH(107, 50, 300, 300))); // Draw an image. graphics.drawImage(PdfBitmap(await _readImageData('photo.jpg')), Rect.fromLTWH(107, 50, 300, 300)); // Restore the graphics. graphics.restore(); // Save and dispose the document. List<int> bytes = await document.save(); document.dispose(); // Save the file and launch/download. SaveFile.saveAndLaunchFile(bytes, 'output.pdf'); }
- Include the following code to read the image data from the folder where it is saved. Here we have named our folder assets.
Future<List<int>> _readImageData(String name) async { final ByteData data = await rootBundle.load('assets/$name'); return data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes); }
- Before that, mention the input image in the assets section of the pubspec.yaml file as stated below.
# To add assets to your application, add an assets section, like this: assets: - assets/photo.jpg
- Follow the steps to save and launch the generated PDF file.
Web:
8.1.Add the web
package as a dependency in your pubspec.yaml
file. Then, create a new Dart file named save_file_web.dart
. Finally, add the following code to implement the file download functionality using the web
package.
import 'dart:convert';
import 'package:web/web.dart' as web;
8.2. To enable file saving and initiate downloads in a Flutter web environment, use the following code within the saveAndLaunchFile
method.
// Function to save and launch a file for download in a web environment
Future<void> saveAndLaunchFile(List<int> bytes, String fileName) async {
final web.HTMLAnchorElement anchor =
web.document.createElement('a') as web.HTMLAnchorElement
..href = "data:application/octet-stream;base64,${base64Encode(bytes)}"
..style.display = 'none'
..download = fileName;
// Insert the new element into the DOM
web.document.body!.appendChild(anchor);
// Initiate the download
anchor.click();
// Clean up the DOM by removing the anchor element
web.document.body!.removeChild(anchor);
}
Desktop and Mobile:
8.3. Add the following dependencies in your pubspec.yaml file.
path_provider: ^2.0.11 open_file: ^3.2.1 # Open-source library to launch the PDF file in mobile devices
8.4. Create a new Dart file named save_file_mobile_and_desktop.dart under the lib folder and import the following packages in save_file_mobile_and_desktop.dart file.
import 'dart:io'; import 'package:open_file/open_file.dart'; import 'package:path_provider/path_provider.dart';
8.5. Include the following code snippet in save_file_mobile_and_desktop.dart to open the PDF document in Desktop and Mobile.
class SaveFile {
static Future<void> saveAndLaunchFile(
List<int> bytes, String fileName) async {
// Get external storage directory
Directory directory = await getApplicationSupportDirectory();
// Get directory path
String path = directory.path;
// Create an empty file to write PDF data
File file = File('$path/$fileName');
// Write PDF data
await file.writeAsBytes(bytes, flush: true);
// Open the PDF document in mobile
OpenFile.open('$path/$fileName');
}
}
- Run the sample using the flutter run command. This will create a circular shape image on the PDF document. After the application launches, you will get the PDF document as follows.
A complete working sample can be downloaded from circular_shape_image.zip.
Conclusion
I hope you enjoyed learning about how to draw a circular shape image in PDF document using Syncfusion® Flutter PDF Library.
Take a moment to peruse the documentation for working with images. You can find other options like inserting images into the PDF document, applying transparency, and rotating images in the PDF document.