plainText static method

String plainText(
  1. List<PdfTextItem> items
)

Joins the items into running text, inserting breaks when the baseline changes and spaces when there is a horizontal gap.

It is a convenience heuristic, not a layout analysis: columns, tables and rotated text come out scrambled.

Implementation

static String plainText(List<PdfTextItem> items) {
  final buffer = StringBuffer();
  PdfTextItem? previous;
  for (final item in items) {
    if (item.text.isEmpty) continue;
    if (previous != null) {
      final size = math.max(item.renderedFontSize, 1.0);
      final sameLine = (previous.origin.y - item.origin.y).abs() < size * 0.5;
      if (!sameLine) {
        buffer.write('\n');
      } else {
        final gap = item.bounds.left - previous.bounds.right;
        final needsSpace = gap > size * 0.2 &&
            !buffer.toString().endsWith(' ') &&
            !item.text.startsWith(' ');
        if (needsSpace) buffer.write(' ');
      }
    }
    buffer.write(item.text);
    previous = item;
  }
  return buffer.toString();
}