Articles in this section
Category / Section

How to draw Unicode text in a PDF file using Google Fonts package in Flutter?

7 mins read

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

  1. 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…

Command Palette...

1.3.Type Flutter and choose Flutter: New Project.

Flutter - New Project

1.4.Enter the project name and press the Enter button.

1.5.Now choose the location of the project.

  1. 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';

 

  1. 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,
              )
            ],
          ),
        ),
      );
    }
    

 

  1. 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);
  }
}

 

  1. 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();
    }
    

 

  1. 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');
  1. 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.

Output image

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 forumsDirect-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 (1)
Please  to leave a comment
TA
Takuro

Thank you for the excellent instruction. This is helpful information. However, I can't understand how to create the TTF file data by the getFont method. There is no "writeAsBytes" statement. This means the TTF file is always empty.

In what cases is the following condition TRUE?

// Line 11 of getFont if (fontBytes != null && fontBytes.isNotEmpty) {

GK
Gowthamraj Kumar

Hi Takuro,

In the above KB documentation, we are getting the font from the Google fonts package in Flutter. The Google fonts package fetches the font files via HTTP at runtime and caches them in the application’s file system. In this article, we have used cached files to render the Unicode text in a PDF document. The reported problem is due to the Flutter Google fonts package being updated. And please make sure the device/emulator internet connectivity whether it is properly connected or not. If not, please connect to the internet and try the below code snippet on your end and let us know the result.

Please refer to the below code snippet,

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');
    if (!file.existsSync()) {
      List<FileSystemEntity> entityList = directory.listSync();
      for (FileSystemEntity entity in entityList) {
        if (entity.path.contains(style.fontFamily!)) {
          file = File(entity.path);
          break;
        }
      }
    }
    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);
    }
  }

We will update the changes in our documentation page.

Regards,

Gowthamraj K

Access denied
Access denied