0

I'm attempting to convert a text file to an image using a certain font (Courier New). The problem I'm having is that the font is fixed width, but the text is not being rendered that way on the image. Here's the code I'm currently using

var fontName = textToImageSection.GetString("FontName", "Courier New");
var fontSize = textToImageSection.GetInt("FontSize", 12);
textFont = new Font(fontName, fontSize);

var sf = new StringFormat(StringFormatFlags.MeasureTrailingSpaces);
sf.Trimming = StringTrimming.Character;
var text = File.ReadAllText(textFile.Path);
var image = new Bitmap(1, 1);
var textSize = new Size();
using (var g = Graphics.FromImage(image))
    textSize = g.MeasureString(text, textFont, int.MaxValue, sf).ToSize();
image = new Bitmap(image, textSize);
using (var g = Graphics.FromImage(image))
{
    g.Clear(Color.White);
    //g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
    g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
    g.DrawString(text, textFont, Brushes.Black, borderLeft, borderTop, sf);
}

image.SaveAsTiff(path);

I've been trying different values for TextRenderingHint without much luck and palying around with the StringFormat.

Here's the resulting image

enter image description here

Here's the text in Notepad++ displayed with Courier New Font

enter image description here

juharr
  • 31,741
  • 4
  • 58
  • 93
  • 1
    it would be nice if you add some sample of the image you're generating, and the one you want to achieve. – Paulo Santos Jun 02 '11 at 13:26
  • 2
    From where does the `textFont` variable come? – Jay Jun 02 '11 at 13:27
  • @Jay, it's read from a config file and is currently set to "Courier New". – juharr Jun 02 '11 at 13:42
  • @Paulo I cannot post the current data I'm working with because it contains PHI, but I can mock something up. – juharr Jun 02 '11 at 13:43
  • @Paulo Updated with an image and the text file as seen in Notepad++ with the same font. – juharr Jun 02 '11 at 13:56
  • The most likely problem is that you're not creating the font correctly. Where is the code that creates the font after reading from the configuration file. – Jim Mischel Jun 02 '11 at 14:03
  • @Jim It was a font problem. I had tried Courier Regular and it was defaulting to Microsoft Sans Serif instead. When I went back to Courier New it was working. Thanks. – juharr Jun 02 '11 at 14:16

0 Answers0