Конвертировать String в изображение и сохранить текстовый файл строки, как в Image - PullRequest
0 голосов
/ 18 января 2019

В приложении winform я конвертирую строку в изображение и хочу сохранить текстовый файл. В котором (текстовый файл) текст форматируется как изображение.

Это код для преобразования строки в изображение =>

private void DrawText(string text)
{
    textBox2.SelectAll();

    FontColor = Color.Black;
    FontBackColor =Color.White;

    FontName = "LinoScript";// richTextBox1.SelectionFont.Name;
    FontSize = 24; //Convert.ToInt16(richTextBox1.SelectionFont.Size);
    ImageHeight = 2630;
    ImageWidth = 1599;
    ImagePath = textBox1.Text.Trim() + numericUpDown1.Value.ToString()+".JPEG";

    //  ImagePath = @"D:\Test.JPEG"; //give the file name you want to export to as image
    ImageText = new Bitmap(ImageWidth, ImageHeight);
    ImageText.SetResolution(90,100);
    ImageGraphics = Graphics.FromImage(ImageText);
    MarginsBox m = new MarginsBox();
    //   printmap.SetResolution(dpi, dpi); // Set the resolution of our paper
    m.Top = 1 * 95; // Set a 1' margin, from the top
    m.Left = 1.25f * 95; // Set a 1.25' margin, from the left
    m.Bottom = ImageText.Height - m.Top; // 1', from the bottom
    m.Right = ImageText.Width - m.Left; // 1.25', from the right
    m.Width = ImageText.Width - (m.Left * 2); // Get the width of our working area
    m.Height = ImageText.Height - (m.Top * 2); // Get the height of our working area

    ImageFont = new Font(FontName, FontSize);

    ImagePointF = new PointF(5, 5);
    BrushForeColor = new SolidBrush(FontColor);
    BrushBackColor = new SolidBrush(Color.White);
    StringFormat drawFormat = new StringFormat();
    ImageGraphics.FillRectangle(BrushBackColor, 0, 0, ImageWidth,ImageHeight);
    //ImageGraphics.DrawString(text, ImageFont, BrushForeColor, ImagePointF);

    ImageGraphics.DrawString(text, ImageFont, BrushForeColor, new RectangleF(m.Left, m.Top, m.Width, m.Height),drawFormat);
    SaveMyFile(text);
    //Draw a byte and create image file
    string outputFileName = ImagePath;
    using (MemoryStream memory = new MemoryStream())
    {
        using (FileStream fs = new FileStream(outputFileName, FileMode.Create, FileAccess.ReadWrite))
        {
            ImageText.Save(memory,  ImageFormat.Gif);
            byte[] bytes = memory.ToArray();
            fs.Write(bytes, 0, bytes.Length);
        }
    }
}

Я создаю текстовый файл так:

public void SaveMyFile(string datastring)
{
    StringFormat drawFormat = new StringFormat();
    TextWriter writer = new StreamWriter(@textBox1.Text.Trim() + numericUpDown1.Value.ToString() + "image.txt");
    writer.Write(datastring, drawFormat);
    writer.Close();  
}

Мне нужен файл .txt, в котором текстовый формат должен быть похож на сгенерированное изображение.

This is image, which is I am getting after code execution.

Мне нужен файл .txt, в котором текст должен выглядеть как строка за строкой, как в изображении.

Заранее спасибо

1 Ответ

0 голосов
/ 18 января 2019

Как я уже упоминал в своем комментарии, вы не можете установить шрифт, размер шрифта или поля в текстовом файле. Что можно и нельзя делать в текстовом файле: https://www.computerhope.com/issues/ch001872.htm Вы можете сделать это с помощью расширенного текстового файла (.rtf), например, так. Я использовал пакет nuget "DotNetRtfWriter".

using HooverUnlimited.DotNetRtfWriter;
...

public void SaveMyFile(string datastring)
{
    RtfDocument doc = new RtfDocument(
        HooverUnlimited.DotNetRtfWriter.PaperSize.Letter,
        PaperOrientation.Portrait,
        Lcid.English);

    doc.Margins[Direction.Top] = 1 * 72;
    doc.Margins[Direction.Left] = 1.25f * 72;
    doc.Margins[Direction.Bottom] = 1 * 72;
    doc.Margins[Direction.Right] = 1.25f * 72;

    doc.SetDefaultFont("LinoScript");
    RtfParagraph para = doc.AddParagraph();
    RtfCharFormat format = para.AddCharFormat();
    format.FontSize = 24;
    para.SetText(datastring);
    doc.Save(@textBox1.Text.Trim() + numericUpDown1.Value.ToString() + "image.rtf");
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...