I am trying to fill the fields of a template in .rtf format with the values I get from a database. The template (template.rtf) is formatted as follows:
My name is @name, and I am @age years old.
And in the function (written in c#) I do the following:
protected void function(object sender, EventArgs e)
{
// Obtenemos los datos y los asignamos a variables
Response.ContentType = "text/rtf";
Response.Headers.Add("Content-Disposition", "attachment; filename=\"documento.rtf\"");
var f = new StringBuilder(System.IO.File.ReadAllText(Server.MapPath("~/ruta/plantilla.rtf")));
f.Replace("@nombre", nombre); // nombre = "Óscar"
f.Replace("@edad", edad); // edad = "20"
Response.Write(f);
Response.End();
}
The whole process works correctly, I have the problem when inserting text with special characters, as in the example that I just passed ( nombre = "Óscar"
), since the resulting document is as follows:
My name is Óscar, and I am 20 years old.
How can i fix this?
You must do three things. On the one hand, when reading the file
rtf
make sure you read it asUTF-8
:On the other, make sure of the same in the
Response
:And finally, check that the file
rtf
is not already encoded asANSI
instead ofUTF-8
.Due to the impossibility of modifying the encoding of the template, I chose to encode the characters before writing them in it. As follows:
Now I send each text string to the function
codificarString
which in turn sends each character to the functioncodificarChar
, returning the corresponding character encoded to be readable inANSI
:This is how it is written correctly: