pdfColorString function

PdfColor? pdfColorString(
  1. String? colorString
)

Implementation

PdfColor? pdfColorString(String? colorString) {
  if (colorString == null || colorString.isTotallyEmpty) return null;
  if (colorString.startsWith('#')) {
    return PdfColor.fromHex(colorString);
  }
  if (colorString.startsWith('0x')) {
    return PdfColor.fromInt(int.parse(colorString));
  }
  final RegExp regex =
      RegExp(r'rgb\((\d+)\s*?,\s*?(\d+)\s*?,\s*?(\d+)\s*?(,?\s*?(\d+)\s*?)\)');
  final RegExpMatch? match = regex.firstMatch(colorString);
  if (match == null) {
    return null;
  }
  if (match.groupCount < 3) {
    return null;
  }

  final String? redColor = match.group(1);
  final String? greenColor = match.group(2);
  final String? blueColor = match.group(3);
  final String? alphaColor = match.group(5);

  final int? red = redColor != null ? int.tryParse(redColor) : null;
  final int? green = greenColor != null ? int.tryParse(greenColor) : null;
  final int? blue = blueColor != null ? int.tryParse(blueColor) : null;
  final int alpha = int.tryParse(alphaColor ?? 'null') ?? 1;

  if (red == null || green == null || blue == null) {
    return null;
  }

  return PdfColor.fromInt(
    rgbaToHex(red, green, blue, opacity: alpha.toDouble()),
  );
}