Как я могу предварительно измерить строку перед печатью?

This is a sketch of the paper form Здравствуйте, я изучаю программирование на C # VS 2010 EE и создаю приложение для заполнения заранее распечатанной формы. Эта форма имеет несколько мест в разных координатах. Три коробки на бумаге представляют собой многострочные коробки размером 5 дюймов на 2 дюйма.

Я уже создал форму окна с одним текстовым полем для каждого места на бумажной форме.

Дело в том, что при вводе информации в эти многострочные текстовые поля мне нужно знать, сколько строк осталось на бумаге, чтобы ввести больше текста, а также, когда прекратить ввод, потому что в поле PrePrinted больше нет свободного места.

Я много искал, но все, что я нашел, касалось измерения на экране, что не соответствует окончательному результату на бумаге.

Другими словами, мне нужно знать, как узнать, каковы будут размеры строки на бумаге, пока она вводится в текстовые поля, и сравнить их с пространством, доступным в предварительно напечатанной форме, чтобы я мог остановиться до того, как это выходит за нижнюю границу прямоугольника на бумаге.

Первый прямоугольник на бумаге имеет ширину 5 дюймов и высоту 2 дюйма, начиная с « new RectangleF (60,0F, 200,0F, 560,0F, 200.0F) ». Я понимаю, что эти числа - сотые доли дюйма.

Все это с учетом того, что я не могу ограничить TextBoxes количеством символов, потому что не все символы занимают одно и то же пространство, например H! = I; M! = L; и т. Д.

Заранее благодарю вас за вашу помощь. Сегодня, 5 сентября 2011 г., на основе ваших комментариев и предложений я изменил код, чтобы использовать Graphics.MeasureString.

Это код, который у меня сейчас с Graphics.MeasureString и только одним richTextBox: Отлично работает из события printDocument1_PrintPage, , но я понятия не имею, как заставить его работать из события richTextBox1_TextChanged .

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;//Needed for the PrintDocument()
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Printing
{
  public partial class Form1 : Form
  {
    private Font printFont1;
    string strPrintText;

    public Form1()
    {
      InitializeComponent();
    }

    private void cmdPrint_Click(object sender, EventArgs e)
    {
      try
      {
        PrintDocument pdocument = new PrintDocument();
        pdocument.PrintPage += new PrintPageEventHandler
        (this.printDocument1_PrintPage);
        pdocument.Print();
      }
      catch (Exception ex)
      {
        MessageBox.Show(ex.Message);
      }
    }

    public void printDocument1_PrintPage (object sender,
      System.Drawing.Printing.PrintPageEventArgs e)
    {
      strPrintText = richTextBox1.Text.ToString();
      printFont1 = new Font("Times New Roman", 10); //I had to remove this line from the btnPrintAnexo1_Click
      Graphics g = e.Graphics;
      StringFormat format1 = new StringFormat();
      RectangleF rectfText;
      int iCharactersFitted, iLinesFitted;

      rectfText = new RectangleF(60.0F, 200.0F, 560.0F, 200.0F);
      // The following e.Graphics.DrawRectangle is
      // just for debuging with printpreview
      e.Graphics.DrawRectangle(new Pen(Color.Black, 1F),
        rectfText.X, rectfText.Y, rectfText.Width, rectfText.Height);

      format1.Trimming = StringTrimming.Word; //Word wrapping

      //The next line of code "StringFormatFlags.LineLimit" was commented so the condition "iLinesFitted > 12" could be taken into account by the MessageBox
// Use next line of code if you don't want to show last line, which will be clipped, in rectangleF
      //format1.FormatFlags = StringFormatFlags.LineLimit;

      //Don't use this next line of code. Some how it gave me a wrong linesFilled
      //g.MeasureString(strPrintText, font, rectfFull.Size, 
      //StringFormat.GenericTypographic, out iCharactersFitted, out iLinesFilled);

      //Use this one instead:
      //Here is where we get the quantity of characters and lines used 
      g.MeasureString(strPrintText, printFont1, rectfText.Size, format1, out iCharactersFitted, out iLinesFitted);

      if (strPrintText.Length == 0)
      {
        e.Cancel = true;
        return;
      }
      if (iLinesFitted > 12)
      {
        MessageBox.Show("Too many lines in richTextBox1.\nPlease reduce text entered.");
        e.Cancel = true;
        return;
      }

      g.DrawString(strPrintText, printFont1, Brushes.Black, rectfText, format1);
      g.DrawString("iLinesFilled = Lines in the rectangle: " + iLinesFitted.ToString(), printFont1, Brushes.Black,
        rectfText.X, rectfText.Height + rectfText.Y);
      g.DrawString("iCharactersFitted = Characters in the rectangle: " + iCharactersFitted.ToString(), printFont1, Brushes.Black,
        rectfText.X, rectfText.Height + rectfText.Y + printFont1.Height);
    }

    private void richTextBox1_TextChanged(object sender, EventArgs e)
    {
      //***I don’t know what to type here.*** 

        if (iLinesFitted == 13)
        {
            MessageBox.Show("Too many lines in richTextBox1.\nPlease erase some characters.");
        }
    }

      private void cmdPrintPreview_Click(object sender, EventArgs e)
    {
      printPreviewDialog1.ShowDialog();
    }

    private void printDocument1_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
    {
//      strPrintText = richTextBox1.Text;
    }
  }
}
6
задан Alex 5 September 2011 в 21:19
поделиться