Suitably encode the string $str for output in the File object $pdf (the exact format may depend on the version of $pdf).
Prinicipally,
encode certain characters in hex if the version is greater than 1.1.