Articles in this section
Category / Section

How to combine multiple PDF documents using create template method in Flutter?

5 mins read

The Flutter PDF library is used to create, read, and edit PDF documents programmatically without Adobe dependencies. Using this library, you can combine multiple PDF documents using create Template method using Flutter.

Steps to combine multiple PDF documents using create template method programmatically

  1. Create a new Flutter application project.

    1. Open Visual Studio Code (After installing the Dart and Flutter extensions as stated in this setup editor page).
    2. Click View -> Command Palette.flut-2323_img1.png
    3. Type Flutter and choose Flutter: New Project.flut-2323_img3.png
    4. Enter the project name and press** Enter**.
    5. Now, choose the location of the project.
  2. 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: ^25.1.39
  1. Import the following package in your main.dart file.
import 'package:syncfusion_flutter_pdf/pdf.dart';
  1. 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: combinePDF, child: const Text('Combine PDF')),
         ],
       ),
     ),
   );
 }
  1. Include the following code sample in the combinePDF method to combine multiple PDF documents.
Future<void> combinePDF() async {
   List<String> files = ["Invoice.pdf", "Input.pdf"];
   // Create a new PDF document.
   PdfDocument newDocument = PdfDocument();
   PdfSection? section;
   for (String file in files) {
     // Load the PDF document.
     PdfDocument loadedDocument =
         PdfDocument(inputBytes: await _readData(file));
     // Export the pages to the new document.
     for (int index = 0; index < loadedDocument.pages.count; index++) {
       // Get the page template.
       PdfTemplate template = loadedDocument.pages[index].createTemplate();
       // Create a new section if the page settings are different.
       if (section == null || section.pageSettings.size != template.size) {
         section = newDocument.sections!.add();
         section.pageSettings.size = template.size;
         section.pageSettings.margins.all = 0;
       }

       // Draw the page template to the new document.
       section.pages
           .add()
           .graphics
           .drawPdfTemplate(template, const Offset(0, 0));
     }

     // Dispose the loaded document.
     loadedDocument.dispose();
   }
   //Save the document.
   List<int> bytes = await newDocument.save();
   //Disposes the document
   newDocument.dispose();
   //Save the file and launch/download.
   SaveFile.saveAndLaunchFile(bytes, 'output.pdf');
 }
  1. Use the following code to load the PDF file in the Flutter project.

a. Add the following code in your pubspec.yaml file.

flutter:
# To add assets to your application, add an assets section, like this:
assets:
  - assets/

b. Import the following package in your main.dart file.

import 'package:flutter/services.dart';

c. Add the following code in the lib/main.dart file to read the existing PDF file.

Future<List<int>> _readData(String name) async {
final ByteData data = await rootBundle.load('assets/$name');
return data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
}
  1. 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 in 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';
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 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 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');
}
}
  1. Run the sample using the flutter run command. After the application launches, you will get a PDF document as follows.Screenshot (1405).png

A complete working sample can be downloaded from combine_multiple_PDF.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 combine multiple PDF documents using create template method in Flutter.

You can refer to our Flutter PDF 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 PDF 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!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied