replaceFields method

void replaceFields(
  1. PdfDocument doc,
  2. Map<String, String> fieldValues
)

Replace placeholders after specific field labels

Implementation

void replaceFields(PdfDocument doc, Map<String, String> fieldValues) {
  for (var obj in doc.objects) {
    if (obj.content.contains("Tj") || obj.content.contains("TJ")) {
      final regex = RegExp(r'\((.*?)\)\s*Tj', dotAll: true);

      obj.content = obj.content.replaceAllMapped(regex, (match) {
        final original = match.group(1)!; // text inside (...)
        var updated = original;

        for (var entry in fieldValues.entries) {
          final label = entry.key;
          final value = entry.value;

          // If the text line contains the label + placeholder
          if (updated.contains(label) && updated.contains(".........")) {
            // Replace only the dots with the value
            updated = updated.replaceFirst(RegExp(r'\.+'), value);
          }
        }

        return "(${updated}) Tj";
      });
    }
  }
}