insertText method

int insertText(
  1. Point point,
  2. String text, {
  3. double fontSize = 11,
  4. String fontName = 'Helvetica',
  5. List<double>? color,
  6. double rotate = 0,
})

Insert text at a point.

Equivalent to PyMuPDF's shape.insert_text().

Implementation

int insertText(
  Point point,
  String text, {
  double fontSize = 11,
  String fontName = 'Helvetica',
  List<double>? color,
  double rotate = 0,
}) {
  final c = color ?? [0, 0, 0];
  final colorStr =
      c.length == 3 ? '${_f(c[0])} ${_f(c[1])} ${_f(c[2])} rg' : '0 0 0 rg';

  final lines = text.split('\n');
  final leading = fontSize * 1.2;

  _content.writeln('q');
  _content.writeln('BT');
  _content.writeln('/$fontName ${_f(fontSize)} Tf');
  _content.writeln(colorStr);
  _content.writeln('${_f(leading)} TL');
  _content.writeln('${_f(point.x)} ${_f(point.y)} Td');

  for (int i = 0; i < lines.length; i++) {
    final escaped = lines[i]
        .replaceAll(r'\', r'\\')
        .replaceAll('(', r'\(')
        .replaceAll(')', r'\)');
    if (i == 0) {
      _content.writeln('($escaped) Tj');
    } else {
      _content.writeln("T* ($escaped) '");
    }
  }

  _content.writeln('ET');
  _content.writeln('Q');
  totalContents++;

  return lines.length;
}