How to draw Unicode text in a PDF file using Google Fonts package in Flutter?
The Syncfusion® Flutter PDF library allows you to draw Unicode text in a PDF document using Google fonts package in Flutter. The Google fonts package fetches the font files via http at runtime and caches it in the application’s file system. In this article, we have used that cached files to render the Unicode text in a PDF document.
Steps to draw Unicode text using Google fonts package in a PDF document programmatically
- Create a new Flutter application project.
1.1.Open Visual Studio Code (After installing the Dart and Flutter extensions as stated in this setup editor page)
1.2.Click View -> Command Palette…
1.3.Type Flutter and choose Flutter: New 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 the pub once you trigger the flutter pub get a comment or Get packages option from the Visual Studio Code.
dependencies: syncfusion_flutter_pdf: ^19.1.55-beta
Import the following 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( 'Draw Text, Generate PDF', style: TextStyle(color: Colors.white), ), style: ButtonStyle( backgroundColor: MaterialStateProperty.resolveWith( (states) => Colors.blue)), onPressed: generatePdf, ) ], ), ), ); }
- Use the following code to get the fonts from Google Fonts package.
4.1.Add the following dependencies in your pubspec.yaml file.
google_fonts: ^2.0.0 path_provider: ^2.0.1
4.2.Import the following packages in your main.dart file.
import 'dart:io'; import 'package:google_fonts/google_fonts.dart'; import 'package:path_provider/path_provider.dart';
4.3.Add the following code to _getFont function to get the font from the Google Fonts package.
Future<PdfFont> getFont(TextStyle style) async { //Get the external storage directory Directory directory = await getApplicationSupportDirectory(); //Create an empty file to write the font data File file = File('${directory.path}/${style.fontFamily}.ttf'); List<int>? fontBytes; //Check if entity with the path exists if (file.existsSync()) { fontBytes = await file.readAsBytes(); } if (fontBytes != null && fontBytes.isNotEmpty) { //Return the google font return PdfTrueTypeFont(fontBytes, 12); } else { //Return the default font return PdfStandardFont(PdfFontFamily.helvetica, 12); } }
- Add the following code to the _generatePdf function to draw text in the PDF document programmatically.
Future<void> generatePdf() async { //Create the PDF document PdfDocument document = PdfDocument(); //Add a page PdfPage page = document.pages.add(); //Set the font PdfFont font = await getFont(GoogleFonts.lato()); //Draw a text page.graphics.drawString('Hello World', font, brush: PdfBrushes.black, bounds: Rect.fromLTWH(0, 0, 200, 30)); //Save the document List<int> bytes = document.save(); //Dispose the document document.dispose(); }
- Use the following code to save and launch the generated PDF file.
6.1.Add the following dependencies in your pubspec.yaml file.
open_file: ^3.1.0 #Open source library to launch the PDF file in mobile devices
6.2.Import the following packages in your main.dart file.
import 'package:open_file/open_file.dart';
6.3.Include the following code snippet in the _generatePdf method to open the PDF document in the mobile‘s default application (any PDF Viewer).
//Get the external storage directory Directory directory = (await getApplicationDocumentsDirectory())!; //Get the directory path String path = directory.path; //Create an empty file to write the PDF data File file = File('$path/output.pdf'); //Write the PDF data await file.writeAsBytes(bytes, flush: true); //Open the PDF document in mobile OpenFile.open('$path/output.pdf');
- Run the sample using the flutter run command. This will draw Unicode text in the PDF document using Google Fonts package. After the application launches, you will get the PDF document as follows.
A complete working sample can be downloaded from DrawUnicodeTextUsingGoogleFonts.zip
Take a moment to peruse the documentation, where you can find other options like drawing right-to-left text, consuming TrueType fonts, Standards fonts, and CJK fonts. Also, the features like headers and footers, bookmarks, tables, hyperlink PDF documents, and more with code examples.
Conclusion
I hope you enjoyed learning about how to draw Unicode text in a PDF file using Google Fonts package in Flutter.
You can refer to our PDF feature tour page to know about its other groundbreaking feature representations. You can also explore our documentation 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!