Как распечатать форму Windows - PullRequest
1 голос
/ 14 ноября 2011

Я создал адресную книгу WinForm на C # и хотел бы знать, как напечатать ее в виде текстового файла, как мне это сделать?

Я отобразил все в DataGridView, я хотел быв идеале - просто печатать информацию в таблице в виде текста.

Ответы [ 4 ]

1 голос
/ 14 ноября 2011

ты можешь попробовать вот так ...

[STAThread]
  static void Main() 
  {
    Application.Run(new PrintPreviewDialog());
  }

  private void btnOpenFile_Click(object sender, System.EventArgs e)
  {
    openFileDialog.InitialDirectory = @"c:\";
    openFileDialog.Filter = "Text files (*.txt)|*.txt|" +
            "All files (*.*)|*.*";
    openFileDialog.FilterIndex = 1;              //  1 based index

    if (openFileDialog.ShowDialog() == DialogResult.OK)
    {
      StreamReader reader = new StreamReader(openFileDialog.FileName);
      try
      {
        strFileName = openFileDialog.FileName;
        txtFile.Text = reader.ReadToEnd();
      }
      catch (Exception ex)
      {
        MessageBox.Show(ex.Message);
        return;
      }
      finally
      {
        reader.Close();
      }
    }
  }

  private void btnSaveFile_Click(object sender, System.EventArgs e)
  {
    SaveFileDialog sfd = new SaveFileDialog();
    sfd.InitialDirectory = @"c:\";
    sfd.Filter = "Text files (*.txt)|*.txt|" +
            "All files (*.*)|*.*";
    sfd.FilterIndex = 1;              //  1 based index

    if (strFileName != null)
      sfd.FileName = strFileName;
    else
      sfd.FileName = "*.txt";

    if (sfd.ShowDialog() == DialogResult.OK)
    {
      StreamWriter writer = new StreamWriter(strFileName,false);
      try
      {
        strFileName = sfd.FileName;
        writer.Write(txtFile.Text);
      }
      catch(Exception ex)
      {
        MessageBox.Show(ex.Message);
        return;
      }
      finally
      {
        writer.Close();
      }
    }
  }

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

  private void btnPageSetup_Click(object sender, System.EventArgs e)
  {
    PageSetupDialog psd = new PageSetupDialog();
    psd.Document = printDocument;
    psd.ShowDialog();
  }

  private void btnPrint_Click(object sender, System.EventArgs e)
  {
    PrintDialog pdlg = new PrintDialog();
    pdlg.Document = printDocument;

    if (pdlg.ShowDialog() == DialogResult.OK)
    {
      try
      {
        printDocument.Print();
      }
      catch(Exception ex)
      {
        MessageBox.Show("Print error: " + ex.Message);
      }
    }
  }

  private void btnPrintPreview_Click(object sender, System.EventArgs e)
  {
    PrintPreviewDialog ppdlg = new PrintPreviewDialog();
    ppdlg.Document = printDocument;
    ppdlg.ShowDialog();
  }

  private void pdPrintPage(object sender, PrintPageEventArgs e)
  {
    float linesPerPage = 0;
    float verticalOffset = 0;
    float leftMargin = e.MarginBounds.Left;
    float topMargin = e.MarginBounds.Top;
    int linesPrinted = 0;
    String strLine = null;

    linesPerPage = e.MarginBounds.Height / currentFont.GetHeight(e.Graphics);

    while (linesPrinted < linesPerPage &&
        ((strLine = stringReader.ReadLine())!= null ))
    {
      verticalOffset = topMargin + (linesPrinted * currentFont.GetHeight(e.Graphics));
      e.Graphics.DrawString(strLine, currentFont, Brushes.Black, leftMargin, verticalOffset);
      linesPrinted++;
    }

    if (strLine != null)
      e.HasMorePages = true;
    else
      e.HasMorePages = false;

  }

  private void pdBeginPrint(object sender, PrintEventArgs e)
  {
    stringReader = new StringReader(txtFile.Text);
    currentFont = txtFile.Font;
  }

  private void pdEndPrint(object sender, PrintEventArgs e)
  {
    stringReader.Close();
    MessageBox.Show("Done printing.");
  }
}
0 голосов
/ 14 ноября 2011

Вы должны дать более подробную информацию о том, что вы хотите сделать.

как вы собираетесь распечатать форму в виде текстового файла? Как преобразовать графику, например метки, кнопки и другие элементы управления, в текст?

то, что вы спрашиваете, возможно, и вы можете контролировать каждый аспект печатного контента как в графическом, так и в текстовом виде, посмотрите здесь как отправную точку:

Поддержка печати Windows Forms

0 голосов
/ 14 ноября 2011

Самый простой способ - создать текстовый файл и записать в него значения. Как это:

var textFile = File.CreateText("Address.txt");
textFile.WriteLine("Name: Fischermaen");
textFile.Close();
0 голосов
/ 14 ноября 2011

Предварительный просмотр и печать из приложения Windows Forms с использованием пространства имен .NET Printing http://msdn.microsoft.com/en-us/magazine/cc188767.aspx

Он немного староват (2003), но все еще выглядит подходящим.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...