How to Insert a Page from Another PDF in Flutter
The Flutter PDF library is used to create, read, and edit PDF documents programmatically without Adobe dependencies. Using this library, you can insert a page from another PDF document using Flutter.
Steps to convert an image to 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 pub once you trigger the flutter pub get command or use the Get packages option from Visual Studio Code.
dependencies:
syncfusion_flutter_pdf: ^24.2.7
- Import the following package into your main.dart file.
import 'package:syncfusion_flutter_pdf/pdf.dart';
- Add the following code to 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>[
ElevatedButton(
onPressed: _insertPdf,
child: const Text('Create PDF'),
)
],
),
),
);
}
- Include the following code sample in the _insertPdf method to insert a page from another PDF document.
Future<void> _insertPdf() async {
// Load the existing PDF document
final PdfDocument sourceDocument =
PdfDocument(inputBytes: await _readPdfDocumentData('barcode.pdf'));
// Get the page if you want to insert another PDF.
PdfPage page = sourceDocument.pages[0];
// Create the page as a template.
PdfTemplate template = page.createTemplate();
// Load the target document.
PdfDocument destDocument =
PdfDocument(inputBytes: await _readPdfDocumentData('invoice.pdf'));
// Add a new page to the document.
PdfPage destPage = destDocument.pages.add();
// Draw the template on the new page.
destPage.graphics
.drawPdfTemplate(template, const Offset(0, 0), destPage.size);
// Save the document.
List<int> bytes = await destDocument.save();
// Dispose of both documents.
destDocument.dispose();
sourceDocument.dispose();
// Save the file and launch/download.
SaveFile.saveAndLaunchFile(bytes, 'output.pdf');
}
- Use the following code to load a PDF in the Flutter project.
a. Add the following code to your pubspec.yaml file.
flutter:
# To add assets to your application, add an assets section, like this:
assets:
- assets/pdf/
b. Import the following package into your main.dart file.
import 'package:flutter/services.dart';
c. Add the following code to the lib/main.dart file to read the existing PDF file.
Future<List<int>> _readPdfDocumentData(String name) async {
final ByteData data = await rootBundle.load('assets/pdf/$name');
return data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
- Follow these steps to launch the generated PDF file on desktop, mobile, and web platforms.
Web
a. 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;
b. 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:
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 into the save_file_mobile_and_desktop.dart file.
import 'dart:io';
import 'package:open_file/open_file.dart';
import 'package:path_provider/path_provider.dart';
c. Include the following code snippet in save_file_mobile_and_desktop.dart to open a PDF document on 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 the PDF data.
File file = File('$path/$fileName');
// Write the PDF data.
await file.writeAsBytes(bytes, flush: true);
// Open a PDF document on mobile.
OpenFile.open('$path/$fileName');
}
}
- Run the sample using the flutter run command. This will insert a page from another PDF document. After the application launches, you will get a PDF document as follows.
A complete working sample can be downloaded from insertPageFromAnotherPDF.zip.
Take a moment to peruse the documentation, where you can find other options like removing pages from a PDF document. Also, features like extract or find text from PDF documents with code examples.