private static void WriteString(StringToken stringToken, Stream outputStream) { outputStream.WriteByte(StringStart); if (stringToken.EncodedWith == StringToken.Encoding.Iso88591) { // iso 88591 (or really PdfDocEncoding in non-contentstream circumstances shouldn't // have these chars but seems like internally this isn't obeyed (see: // CanCreateDocumentInformationDictionaryWithNonAsciiCharacters test) and it may // happen during parsing as well -> switch to unicode if (stringToken.Data.Any(x => x > 255)) { var data = new StringToken(stringToken.Data, StringToken.Encoding.Utf16BE).GetBytes(); outputStream.Write(data, 0, data.Length); } else { int ei; for (var i = 0; i < stringToken.Data.Length; i++) { var c = (int)stringToken.Data[i]; if (c == (int)'(' || c == (int)')') // wastes a little space if escaping not needed but better than forward searching { outputStream.WriteByte((byte)'\\'); outputStream.WriteByte((byte)c); } else if ((ei = Array.IndexOf(EscapeNeeded, c)) > -1) { outputStream.WriteByte((byte)'\\'); outputStream.WriteByte((byte)Escaped[ei]); } else if (c < 32 || c > 126) // non printable { var b3 = c / 64; var b2 = (c - b3 * 64) / 8; var b1 = c % 8; outputStream.WriteByte((byte)'\\'); outputStream.WriteByte((byte)(b3 + '0')); outputStream.WriteByte((byte)(b2 + '0')); outputStream.WriteByte((byte)(b1 + '0')); } else { outputStream.WriteByte((byte)c); } } } } else { var bytes = stringToken.GetBytes(); outputStream.Write(bytes, 0, bytes.Length); } outputStream.WriteByte(StringEnd); WriteWhitespace(outputStream); }