I'm developing a windows application with Flutter which generates a pdf-document. The software is using the Dart/Flutter library pdf 3.10.7 to build the documents. My goal is to use a custom font in the pdf, so I wrote the code as shown in the documentation of the library (the example code "To use a TrueType font" on the website):
final Uint8List fontData1 =
File('assets/OpenSans-Regular.ttf').readAsBytesSync();
final openSansRegular = pw.Font.ttf(fontData1.buffer.asByteData());
final fontData2 = File('assets/OpenSans-Bold.ttf').readAsBytesSync();
final openSansBold = pw.Font.ttf(fontData2.buffer.asByteData());
This is my pubspec.yaml
File:
assets:
- assets/
And my fonts are included like this:
My software works without any error in the debug-mode in Android Studio.
However when I build the Release version with flutter build windows
I get this error when using the application:
PathNotFoundException: Cannot open file, path = 'assets/OpenSans-Bold.ttf' (OS Error: The System cannot find the path specified.
, errno = 3)
You need to use rootBundle
from flutter/services.dart
if you want access to your assets:
import 'package:flutter/services.dart' show rootBundle;
final ByteData fontData1 = await rootBundle.load('assets/OpenSans-Regular.ttf');
While your approach might work in debug mode, you should definitely use AssetBundle
to load your assets. Also, note that this directly returns a ByteData
object so no conversion from Uint8List
is needed anymore.
For more info on how to add assets, please visit the docs.