How to draw images from a URL in a PDF using Flutter
The Syncfusion® Flutter PDF library is used to create, read, and edit PDF documents programmatically without Adobe dependencies. Using this library, you can draw images from a URL in a PDF document using Flutter.
Steps to draw images from a URL in a PDF document programmatically
-
Create a new Flutter application project.
- Open Visual Studio Code (After installing the Dart and Flutter extensions as stated in this setup editor page).
- Click View -> Command Palette.
- Type Flutter and choose Flutter: New Project.
- Enter the project name and press** Enter**.
- 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 the pub once you trigger the flutter pub to get comments. or the Get packages option from the Visual Studio code.
dependencies:
syncfusion_flutter_pdf: ^26.1.39
http: ^1.2.1
-
- Import the following package into your main.dart file.
import 'package:syncfusion_flutter_pdf/pdf.dart';
import 'package:http/http.dart' as http;
- Add the following code in lib/main.dart file to create a simple button.
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: _convertImageToPDF,
child: const Text('Convert image to PDF')),
],
),
),
);
}
- Include the following code in the _convertImageToPDF method to draw images from a URL in a PDF document.
Future<void> _convertImageToPDF() async {
//Create a PdfBitmap instance from the network image
List<int>? imageData = await await _downloadImage(
'https://cdn.syncfusion.com/content/images/products/dashboard-videos/syncfusion-videos-fb.png');
if (imageData != null) {
PdfBitmap image = PdfBitmap(imageData);
//Create a new PDF document
PdfDocument document = PdfDocument();
//Set the margins
document.pageSettings.margins.all = 0;
if (image.width > image.height) {
//Set page orientation
document.pageSettings.orientation = PdfPageOrientation.landscape;
}
//Set the page size as the image size
document.pageSettings.size =
Size(image.width.toDouble(), image.height.toDouble());
//Add a page to the document
PdfPage page = document.pages.add();
//Draw the image to the page
page.graphics.drawImage(
image,
Rect.fromLTWH(
0, 0, page.getClientSize().width, page.getClientSize().height));
//Save the document.
List<int> bytes = await document.save();
//Disposes the document
document.dispose();
//Save the file and launch/download.
SaveFile.saveAndLaunchFile(bytes, 'output.pdf');
}
}
- Add the following code in the lib/main.dart file to download image from existing URL.
Future<List<int>?> _downloadImage(String url) async {
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
return response.bodyBytes;
}
return null;
}
- Follow these steps to launch the generated PDF file on desktop, mobile, and web platforms.
Web
a. Create a new dart file named save_file_web.dart under the lib folder and import the following packages in save_file_web.dart file.
import 'dart:convert';
import 'dart:html';
b. Include the following code sample in save_file_web.dart file to open a PDF document on the Web.
class SaveFile {
static Future<void> saveAndLaunchFile(
List<int> bytes, String fileName) async {
AnchorElement(
href:
'data:application/octet-stream;charset=utf-16le;base64,${base64.encode(bytes)}')
..setAttribute('download', fileName)
..click();
}
}
Desktop and mobile:
a. Add the following dependencies to your pubspec.yaml file.
open_file: ^3.2.1
path_provider: ^2.0.11 #Open-source library to launch the PDF file on mobile devices
b. 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' as open_file;
import 'package:path_provider/path_provider.dart' as path_provider;
import 'package:path_provider_platform_interface/path_provider_platform_interface.dart';
c. Include the following code snippet in save_file_mobile_and_desktop.dart to open a PDF document in Desktop and Mobile.
class SaveFile {
///To save the pdf file in the device
static Future<void> saveAndLaunchFile(
List<int> bytes, String fileName) async {
//Get the storage folder location using path_provider package.
String? path;
if (Platform.isAndroid ||
Platform.isIOS ||
Platform.isLinux ||
Platform.isWindows) {
final Directory directory =
await path_provider.getApplicationSupportDirectory();
path = directory.path;
} else {
path = await PathProviderPlatform.instance.getApplicationSupportPath();
}
final File file =
File(Platform.isWindows ? '$path\\$fileName' : '$path/$fileName');
await file.writeAsBytes(bytes, flush: true);
if (Platform.isAndroid || Platform.isIOS) {
//Launch the file (used open_file package)
await open_file.OpenFile.open('$path/$fileName');
} else if (Platform.isWindows) {
await Process.run('start', <String>['$path\\$fileName'],
runInShell: true);
} else if (Platform.isMacOS) {
await Process.run('open', <String>['$path/$fileName'], runInShell: true);
} else if (Platform.isLinux) {
await Process.run('xdg-open', <String>['$path/$fileName'],
runInShell: true);
}
}
}
- Run the sample using the flutter run command. After the application launches, you will get a PDF document as follows.
A complete working sample can be downloaded from network_image_instead_of_asset_in_flutter.zip.
Take a moment to peruse the documentation, where you will find other options like RTF to PDF conversion, XPS to PDF conversion, PDF to image conversion, HTML to MHTML, HTML to SVG, and partial webpage to SVG, etc.
Click here to explore the rich set of Syncfusion Essential® PDF features.
Conclusion
I hope you enjoyed learning about how to load and draw web images in a Flutter PDF document.
You can refer to our Flutter DataTable feature tour page to know about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our Flutter DataTable example to understand how to create and manipulate data.
For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion®, you can try our 30-day free trial to check out our other controls.
If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums, Direct-Trac, or feedback portal. We are always happy to assist you!