rasterizeText static method

Future<UPdfRaster?> rasterizeText(
  1. String text, {
  2. required double width,
  3. required double height,
  4. double fontSize = 14,
  5. Color color = const Color(0xFF000000),
  6. bool rtl = false,
  7. String? fontFamily,
  8. double pixelRatio = 2.5,
  9. TextAlign align = TextAlign.start,
})

Implementation

static Future<UPdfRaster?> rasterizeText(
  String text, {
  required double width,
  required double height,
  double fontSize = 14,
  Color color = const Color(0xFF000000),
  bool rtl = false,
  String? fontFamily,
  double pixelRatio = 2.5,
  TextAlign align = TextAlign.start,
}) async {
  if (text.isEmpty || width <= 0 || height <= 0) return null;
  try {
    final int pixelWidth = (width * pixelRatio).round().clamp(1, 4096);
    final int pixelHeight = (height * pixelRatio).round().clamp(1, 4096);
    final ui.ParagraphBuilder builder = ui.ParagraphBuilder(
      ui.ParagraphStyle(
        fontSize: fontSize * pixelRatio,
        fontFamily: fontFamily,
        textDirection: rtl ? TextDirection.rtl : TextDirection.ltr,
        textAlign: align,
      ),
    );
    builder.pushStyle(ui.TextStyle(color: color, fontSize: fontSize * pixelRatio));
    builder.addText(text);
    final ui.Paragraph paragraph = builder.build();
    paragraph.layout(ui.ParagraphConstraints(width: pixelWidth.toDouble()));
    final ui.PictureRecorder recorder = ui.PictureRecorder();
    final Canvas canvas = Canvas(recorder);
    canvas.drawParagraph(paragraph, Offset.zero);
    final ui.Picture picture = recorder.endRecording();
    final ui.Image image = await picture.toImage(pixelWidth, pixelHeight);
    picture.dispose();
    final ByteData? data = await image.toByteData();
    image.dispose();
    if (data == null) return null;
    return UPdfRaster(data.buffer.asUint8List(), pixelWidth, pixelHeight);
  } on Object {
    return null;
  }
}