Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert font to string and back again

i have an application where my user changes font and font color for different labels etc and they save it to a file but i need to be able to convert the font of the specified label to a string to be written to file, and then when they open that file my program will convert that string back into a font object. How can this be done? I haven't found anywhere that shows how it can be done.

thank you

bael

like image 956
jay_t55 Avatar asked Feb 05 '10 14:02

jay_t55


3 Answers

It is easy to go back and forth from a font to a string and back with the System.Drawing.FontConverter class. For example:

        var cvt = new FontConverter();
        string s = cvt.ConvertToString(this.Font);
        Font f = cvt.ConvertFromString(s) as Font;
like image 63
Hans Passant Avatar answered Sep 18 '22 04:09

Hans Passant


You can serialize the font class to a file.

See this MSDN article for details of how to do so.

To serialize:

private void SerializeFont(Font fn, string FileName)
{
  using(Stream TestFileStream = File.Create(FileName))
  {
    BinaryFormatter serializer = new BinaryFormatter();
    serializer.Serialize(TestFileStream, fn);
    TestFileStream.Close();
  }
}

And to deserialize:

private Font DeSerializeFont(string FileName)
{
    if (File.Exists(FileName))
    {
        using(Stream TestFileStream = File.OpenRead(FileName))
        {
            BinaryFormatter deserializer = new BinaryFormatter();
            Font fn = (Font)deserializer.Deserialize(TestFileStream);
            TestFileStream.Close();
        }
        return fn;
    }
    return null;
}
like image 4
Oded Avatar answered Sep 21 '22 04:09

Oded


Quite simple really if you want to make it readable in the file:

class Program
{
    static void Main(string[] args)
    {
        Label someLabel = new Label();
        someLabel.Font = new Font("Arial", 12, FontStyle.Bold | FontStyle.Strikeout | FontStyle.Italic);

        var fontString = FontToString(someLabel.Font);
        Console.WriteLine(fontString);
        File.WriteAllText(@"D:\test.txt", fontString);

        var loadedFontString = File.ReadAllText(@"D:\test.txt");

        var font = StringToFont(loadedFontString);
        Console.WriteLine(font.ToString());

        Console.ReadKey();
    }

    public static string FontToString(Font font)
    {
        return font.FontFamily.Name + ":" + font.Size + ":" + (int)font.Style;
    }

    public static Font StringToFont(string font)
    {
        string[] parts = font.Split(':');
        if (parts.Length != 3)
            throw new ArgumentException("Not a valid font string", "font");

        Font loadedFont = new Font(parts[0], float.Parse(parts[1]), (FontStyle)int.Parse(parts[2]));
        return loadedFont;
    }
}

Otherwise serialization is the way to go.

like image 2
Codesleuth Avatar answered Sep 21 '22 04:09

Codesleuth