我正在尝试使用“ Pdf创建库”在Flutter应用程序中生成pdf。用其他语言生成pdf时会出现异常

时间:2019-08-24 14:29:26

标签: android pdf flutter dart

这是用于生成其他语言字体的pdf的代码:

final Uint8List fontData = File('fonts/shivaji05.ttf').readAsBytesSync();
final ttf = Font.ttf(fontData.buffer.asByteData());

这是我在文本中使用定义的字体的方式:

Text('साई बाबा', textScaleFactor: 2, style: new TextStyle(font: ttf)),

错误日志

E/flutter (26251): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)] Unhandled Exception: 'package:pdf/src/font.dart': Failed assertion: line 145 pos 14: 'false': 
E/flutter (26251): ---------------------------------------------
E/flutter (26251): Can not decode the string to Latin1.
E/flutter (26251): This font does not support Unicode characters.
E/flutter (26251): If you want to use strings other than Latin strings, use a TrueType (TTF) font instead.</i>

1 个答案:

答案 0 :(得分:2)

当尝试使用“ Pdf创建库”在Flutter应用程序中生成pdf时,我遇到了类似的错误。在生成pdf时,在源文本中带有单引号“”,“&#8217”。

错误代码

final String soutceString = 'My source text with " ’ "';

final Document pdf = Document(deflate: zlib.encode);

pdf.addPage(
    MultiPage(
       build: (Context context) => <Widget>[
            Paragraph(text: soutceString),
       ]
    )
);

错误日志

flutter: 'package:pdf/src/font.dart': Failed assertion: line 145 pos 14: 'false':
---------------------------------------------
Can not decode the string to Latin1.
This font does not support Unicode characters.
If you want to use strings other than Latin strings, use a TrueType (TTF) font instead. 

当我发现错误的符号时,我将其替换。

具有快速修复的代码


final String sourceString = 'My source text with " ’ "';

final Document pdf = Document(deflate: zlib.encode);

sourceString.replaceAll('’', '`'),

pdf.addPage(MultiPage(
   build: (Context context) => <Widget>[
            Paragraph(text: sourceString)
        ]
    )
);

但是我担心,将来会出现新的错误符号。我将arial.ttf字体添加到资产中(arial.ttf包含我的符号)并使用了它。 Adding assets

最适合我的情况

import 'package:flutter/services.dart' show rootBundle;



final String sourceString = 'My source text with " ’ "';

final Document pdf = Document(deflate: zlib.encode);

pdf.addPage(MultiPage(
     theme: Theme.withFont(
        base: Font.ttf(await rootBundle.load("assets/arial.ttf")),
        bold: Font.ttf(await rootBundle.load("assets/arial.ttf")),
        italic: Font.ttf(await rootBundle.load("assets/arial.ttf")),
        boldItalic: Font.ttf(await rootBundle.load("assets/arial.ttf")),
      ),
   build: (Context context) => <Widget>[
            Paragraph(text: sourceString)
          ]
    )
);