Category / Section
How to add watermark to PDF file in Syncfusion Flutter PDF?
7 mins read
The Flutter PDF library allows you to create, read and edit PDF documents programmatically without Adobe Dependencies. Using this library, you can add watermark to PDF document using Flutter.
Steps to add watermark to 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 the Enter button.
- 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 get a comment or Get packages option from the Visual Studio Code.
dependencies: syncfusion_flutter_pdf: ^20.3.49
- Import the following package in your main.dart file.
import 'package:syncfusion_flutter_pdf/pdf.dart';
- Add the following code in lib/main.dart file to create a simple button.
@override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( // Here we take the value from the MyHomePage object that was created by // the App.build method, and use it to set our appbar title. title: Text(widget.title), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ TextButton( child: Text( 'Add watermark', style: TextStyle(color: Colors.white), ), style: ButtonStyle( backgroundColor: MaterialStateProperty.resolveWith( (states) => Colors.blue)), onPressed: _addWatermarkToPDF, ) ], ), ), ); }
- Add the following code to the _addWatermarkToPDF function to add watermark to the PDF document programmatically.
Future<void> _addWatermarkToPDF() async{ //Load the PDF document PdfDocument document = PdfDocument(inputBytes: await _readDocumentData('input.pdf')); //Get first page from document PdfPage page = document.pages[0]; //Get page size Size pageSize = page.getClientSize(); //Set a standard font PdfFont font = PdfStandardFont(PdfFontFamily.helvetica, 40); //Measure the text Size size = font.measureString('Confidential'); //Create PDF graphics for the page PdfGraphics graphics = page.graphics; //Calculate the center point double x = pageSize.width / 2; double y = pageSize.height / 2; //Save the graphics state for the watermark text graphics.save(); //Tranlate the transform with the center point graphics.translateTransform(x, y); //Set transparency level for the text graphics.setTransparency(0.25); //Rotate the text to -40 Degree graphics.rotateTransform(-40); //Draw the watermark text to the desired position over the PDF page with red color graphics.drawString('Confidential', font, pen: PdfPen(PdfColor(255, 0, 0)), brush: PdfBrushes.red, bounds: Rect.fromLTWH( -size.width / 2, -size.height / 2, size.width, size.height)); //Restore the graphics graphics.restore(); //Save the document List<int> bytes = await document.save(); //Dispose the document document.dispose(); //Save the file and launch/download SaveFile.saveAndLaunchFile(bytes, 'output.pdf'); }
- Use the following code to load an existing PDF document in the Flutter project.
- Add the following code in your pubspec.yaml file.
flutter: # To add assets to your application, add an assets section, like this: assets: - assets/pdf/
- Import the following package in your main.dart file.
import 'package:flutter/services.dart';
- Add the following code in the lib/main.dart file to read the existing PDF document.
Future<List<int>> _readDocumentData(String name) async { final ByteData data = await rootBundle.load('assets/pdf/$name'); return data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes); }
- Follow the below steps to launch the generated PDF file on desktop, mobile, and web platforms.
Web:
- 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';
- Include the following code snippet in save_file_web.dart file to open the PDF document in 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:
- 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 in mobile devices
- 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';
- 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 add watermark to the PDF document page.
You can download the working sample from CreateWatermarkPDFSample.zip.
Take a moment to peruse the documentation, where you can find other options like adding image watermark in PDF document and features like images to PDF, Text to PDF, etc., with code examples.