LovinduLI
LovinduLI

Reputation: 439

How to change the font in a text widget in the flutter PDF library?

Currently I'm working on a project which has to create a PDF according to the data user provide. But I need to change the font of a text widget to a new font which has texts of two languages. But it doesn't work. I changed the fontFamily in the app theme section too. But the font didn't change in the PDF. But rest of the text changed. So how can I change the font in a text widget in flutter PDF library. This is the link to the library I use to create the pdf. https://pub.dev/packages/pdf

  Future<Uint8List> _generatePdf() async {
    String name = controllerName.text;
    String age;
    String complain = controllerComplain.text;
    String systolicPressure = controllerSystolicPressure.text;
    String diastolicPressure = controllerDiastolicPressure.text;
    String fullPressure = systolicPressure + "/" + diastolicPressure + " mmHg";

    // Creating the total age
    if (controllerAgeYears.text == '') {
    } else {
      age = controllerAgeYears.text + " years ";
    }
    if (controllerAgeMonths.text == '') {
    } else {
      age += controllerAgeMonths.text + ' Months';
    }
    // Choosing male or female to create the pdf
    String mOF = '';
    if (_isSelected[0] == true) {
      mOF = 'Male';
    } else {
      mOF = 'Female';
    }
    // Createing the pdf
    pdf.addPage(pw.MultiPage(
        pageFormat: PdfPageFormat.a5,
        margin: pw.EdgeInsets.all(32),      
        build: (pw.Context context) {
          return <pw.Widget>[
            pw.Text("Methsuwa Family Clinic",
                style: pw.TextStyle(fontSize: 22)),
            pw.Text("No: 607, Medamandiya, Panagoda, Homagama.",
                style: pw.TextStyle(fontSize: 10)),
            pw.Header(
              level: 0,
              child: pw.SizedBox(height: 2),
            ),
            pw.SizedBox(height: 5),
            pw.Text('Name: ' + name, style: pw.TextStyle(fontSize: 10)),
            pw.SizedBox(height: 3),
            pw.Text('Age: ' + age, style: pw.TextStyle(fontSize: 10)),
            pw.SizedBox(height: 3),
            pw.Text('Gender: ' + mOF, style: pw.TextStyle(fontSize: 10)),
            pw.SizedBox(height: 3),
            pw.Text('Complains: ' + complain,
                style: pw.TextStyle(fontSize: 10)),
            pw.SizedBox(height: 3),
            pw.Text('Blood Pressure: ' + fullPressure,
                style: pw.TextStyle(fontSize: 10)),
            pw.SizedBox(height: 6),
            pw.Table.fromTextArray(
                context: context,
                headerStyle: pw.TextStyle(fontSize: 10),
                cellStyle: pw.TextStyle(fontSize: 10),
                data: <List<String>>[
                  <String>['Drug', 'Amount', 'Days', 'When', 'Total'],
                  ..._data.map((msg) => [
                        msg["drug"],
                        msg["amount"],
                        msg["days"],
                        msg["when"],
                        msg["total"]
                      ])
                ]),
            pw.SizedBox(height: 6),
            pw.Table.fromTextArray(
                context: context,
                headerStyle: pw.TextStyle(fontSize: 10),
                cellStyle: pw.TextStyle(fontSize: 10),
                data: <List<String>>[
                  <String>['Investigations'],
                  ...selectedInvestigations.map((msg) => [msg["investigation"]])
                ]),
            pw.Text(
              'Daily:එදිනෙදා, BID:දිනකට දෙවරක්, TID:දිනකට තෙවරක්, QID:දිනකට සතරවරක්, QHS:නින්දට පෙර Q4h:සෑම පැය සතරකට වරක් Q4-6h:සෑම පැය සතරත් සයත් තුල  QWK:සෑම සතියකට වරක්',
              
            ),// I need to change the font in this text field. As you can see there are two languages
          ];
        }));

    pdfPrint = pdf;
    pdf = null;
    pdf = pw.Document();

    return pdfPrint.save();
  }

Upvotes: 6

Views: 7420

Answers (2)

Nicholas Bradley
Nicholas Bradley

Reputation: 41

https://github.com/DavBfr/dart_pdf/wiki/Fonts-Management

Using a font globally

It is possible to create a theme for the entire document. This way, all the elements in the document will use your specific font and you will have no issues with untrusted text sources, like user inputs.

In your pubspec.yaml add all the required fonts:

  assets:
    - assets/OpenSans-Regular.ttf
    - assets/OpenSans-Bold.ttf
    - assets/OpenSans-Italic.ttf
    - assets/OpenSans-BoldItalic.ttf

In your PDF generation function, create the document with a theme:

  base: Font.ttf(await rootBundle.load("assets/OpenSans-Regular.ttf")),
  bold: Font.ttf(await rootBundle.load("assets/OpenSans-Bold.ttf")),
  italic: Font.ttf(await rootBundle.load("assets/OpenSans-Italic.ttf")),
  boldItalic: Font.ttf(await rootBundle.load("assets/OpenSans-BoldItalic.ttf")),
);


var pdf = Document(
  theme: myTheme,
);

Upvotes: 1

LovinduLI
LovinduLI

Reputation: 439

I used this file to figure out how to use a custom font in a text widget of flutter pdf package.https://github.com/DavBfr/dart_pdf/blob/master/demo/lib/examples/resume.dart

First we have to define the font in a variable.

var font = await PdfGoogleFonts.abhayaLibreRegular();

Then we have to add it to the text widget as shown below.

pw.Text('Hello World', style: TextStyle(font: font));

Upvotes: 5

Related Questions