none
C# Print Textbox contents

    Question

  • Hi, I have a textbox called richTextBox1. I would like to print the contents of this textbox, but am unsure how to. This is for a school project and I have done alot of research, but the web, nor my textbook has helped

    I would also like to be able to display the text in a print preview if the user wants to see a preview

    Help would be nice, Thanks.

    visual studio 2008

    Friday, January 18, 2013 12:14 AM

Answers

All replies

  • PrintDocument is the key to both printing and the print preview.

    PrintDocument: http://msdn.microsoft.com/en-us/library/system.drawing.printing.printdocument.aspx

    There is an example at the bottom of the page.

    PrintPreview: http://msdn.microsoft.com/en-us/library/274tyhz7.aspx

    This should be enough to get you started.  Please feel free to post additional questions if you get lost.


    It would be greatly appreciated if you would mark any helpful entries as helpful and if the entry answers your question, please mark it with the Answer link.

    • Marked as answer by jesushimself Saturday, January 19, 2013 3:37 AM
    Friday, January 18, 2013 2:00 AM
  • You can preview and print the RichTextBox.Text using the PrintPreviewDialog and the PrintDocument classes.  To print the RichTextBox.Rtf requires special code:  How to print the content of a RichTextBox control by using Visual C# .NET or Visual C# 2005
    Friday, January 18, 2013 3:00 AM
  • so how do i link these with a rich text box?
    Friday, January 18, 2013 3:48 AM
  • If you are speaking of the text printer, you could use something like the StringReader class: http://msdn.microsoft.com/en-us/library/system.io.stringreader.aspx

    So building on the example provided,

    streamToPrint = new StreamReader("C:\\My Documents\\MyFile.txt");
    

    would be replaced with something like:

    streamToPrint = new StringReader(richTextBox1.Text);


    It would be greatly appreciated if you would mark any helpful entries as helpful and if the entry answers your question, please mark it with the Answer link.

    Friday, January 18, 2013 4:00 AM
  • For John's solution, you will be creating a new control, which you will use instead of the original RichTextBox control.

    It would be greatly appreciated if you would mark any helpful entries as helpful and if the entry answers your question, please mark it with the Answer link.

    Friday, January 18, 2013 4:08 AM
  • Here is what I have, but it either gives me an error saying the file is not in my bin folder or it has illegal characters

            private void printToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                streamToPrint = new StreamReader(richTextBox1.Text);
                try
                {
                    printFont = new Font("Arial", 10);
                    PrintDocument pd = new PrintDocument();
                    pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
                    pd.Print();
                }
                finally
                {
                    streamToPrint.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

            private void pd_PrintPage(object sender, PrintPageEventArgs ev)
            {
                float linesPerPage = 0;
                float yPos = 0;
                int count = 0;
                float leftMargin = ev.MarginBounds.Left;
                float topMargin = ev.MarginBounds.Top;
                string line = null;

                // Calculate the number of lines per page.
                linesPerPage = ev.MarginBounds.Height /
                   printFont.GetHeight(ev.Graphics);

                // Print each line of the file. 
                while (count < linesPerPage &&
                   ((line = streamToPrint.ReadLine()) != null))
                {
                    yPos = topMargin + (count *
                       printFont.GetHeight(ev.Graphics));
                    ev.Graphics.DrawString(line, printFont, Brushes.Black,
                       leftMargin, yPos, new StringFormat());
                    count++;
                }

                // If more lines exist, print another page. 
                if (line != null)
                    ev.HasMorePages = true;
                else
                    ev.HasMorePages = false;
            }
    Friday, January 18, 2013 4:37 AM
  • That would be because you forgot to change StreamReader to StringReader as I indicated in my previous post, so your code is trying to open a file with whatever text happened to be in your richTextBox1.

    It would be greatly appreciated if you would mark any helpful entries as helpful and if the entry answers your question, please mark it with the Answer link.

    Friday, January 18, 2013 4:41 AM
  • Now I am getting an error Error:   1    Cannot implicitly convert type 'System.IO.StringReader' to 'System.IO.StreamReader'    F:\ICS4U\ISU\ISU\Form1.cs    499    29    ISU

    private void printToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                streamToPrint = new StringReader(richTextBox1.Text);
                try
                {
                    printFont = new Font("Arial", 10);
                    PrintDocument pd = new PrintDocument();
                    pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
                    pd.Print();
                }
                finally
                {
                    streamToPrint.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

    Friday, January 18, 2013 1:54 PM
  • and also for the print preview, how do i link it with the richtextbox? mydocument does not exist and richtextbox1.text cannot be converted
    Friday, January 18, 2013 1:59 PM
  • Here is the example customized for printing from a string, rather than a file:

      private System.Windows.Forms.Button printButton;
      private Font printFont;
      private StringReader streamToPrint;
      private const string textToPrint = "Here is some text to print";
    
      public Form1()
      {
       // The Windows Forms Designer requires the following call.
       InitializeComponent();
      
       this.printButton = new System.Windows.Forms.Button();
    
       printButton.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
       printButton.Location = new System.Drawing.Point(0, 0);
       printButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
       printButton.TabIndex = 0;
       printButton.Text = "Print the text.";
       printButton.Size = new System.Drawing.Size(136, 40);
       printButton.Click += new System.EventHandler(printButton_Click);
    
       this.Controls.Add(printButton);
      }
    
      // The Click event is raised when the user clicks the Print button. 
      private void printButton_Click(object sender, EventArgs e)
      {
       try
       {
        streamToPrint = new StringReader(textToPrint);
        
        try
        {
         printFont = new Font("Arial", 10);
         PrintDocument pd = new PrintDocument();
         pd.PrintPage += new PrintPageEventHandler
            (this.pd_PrintPage);
         pd.Print();
        }
        finally
        {
         streamToPrint.Close();
        }
       }
       catch (Exception ex)
       {
        MessageBox.Show(ex.Message);
       }
      }
    
      // The PrintPage event is raised for each page to be printed. 
      private void pd_PrintPage(object sender, PrintPageEventArgs ev)
      {
       float linesPerPage = 0;
       float yPos = 0;
       int count = 0;
       float leftMargin = ev.MarginBounds.Left;
       float topMargin = ev.MarginBounds.Top;
       string line = null;
    
       // Calculate the number of lines per page.
       linesPerPage = ev.MarginBounds.Height /
          printFont.GetHeight(ev.Graphics);
    
       // Print each line of the file. 
       while (count < linesPerPage &&
          ((line = streamToPrint.ReadLine()) != null))
       {
        yPos = topMargin + (count *
           printFont.GetHeight(ev.Graphics));
        ev.Graphics.DrawString(line, printFont, Brushes.Black,
           leftMargin, yPos, new StringFormat());
        count++;
       }
    
       // If more lines exist, print another page. 
       if (line != null)
        ev.HasMorePages = true;
       else
        ev.HasMorePages = false;
      }
     }
    


    It would be greatly appreciated if you would mark any helpful entries as helpful and if the entry answers your question, please mark it with the Answer link.

    Friday, January 18, 2013 8:52 PM
  • and also for the print preview, how do i link it with the richtextbox? mydocument does not exist and richtextbox1.text cannot be converted

    And now for an example with preview:

      private Button printButton;
      private Button previewButton;
      private Font printFont;
      private StringReader streamToPrint;
      private const string textToPrint = "Here is some text to print";
    
      public Form1()
      {
       // The Windows Forms Designer requires the following call.
       InitializeComponent();
    
       this.printButton = new System.Windows.Forms.Button();
    
       printButton.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
       printButton.Location = new System.Drawing.Point(0, 0);
       printButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
       printButton.TabIndex = 0;
       printButton.Text = "Print the text.";
       printButton.Size = new System.Drawing.Size(136, 40);
       printButton.Click += new System.EventHandler(printButton_Click);
    
       this.Controls.Add(printButton);
    
       this.previewButton = new System.Windows.Forms.Button();
    
       previewButton.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
       previewButton.Location = new System.Drawing.Point(0, 45);
       previewButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
       previewButton.TabIndex = 0;
       previewButton.Text = "Preview the text.";
       previewButton.Size = new System.Drawing.Size(136, 40);
       previewButton.Click += new System.EventHandler(previewButton_Click);
    
       this.Controls.Add(previewButton);
      }
    
      private void printButton_Click(object sender, EventArgs e)
      {
       try
       {
        streamToPrint = new StringReader(textToPrint);
    
        try
        {
         printFont = new Font("Arial", 10);
         PrintDocument pd = new PrintDocument();
         pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
         pd.Print();
        }
        finally
        {
         streamToPrint.Close();
        }
       }
       catch (Exception ex)
       {
        MessageBox.Show(ex.Message);
       }
      }
    
      private void previewButton_Click(object sender, EventArgs e)
      {
       try
       {
        streamToPrint = new StringReader(textToPrint);
    
        try
        {
         printFont = new Font("Arial", 10);
         PrintDocument pd = new PrintDocument();
         pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
    
         PrintPreviewDialog previewDialog = new PrintPreviewDialog();
         previewDialog.Document = pd;
         previewDialog.ShowDialog();
        }
        finally
        {
         streamToPrint.Close();
        }
       }
       catch (Exception ex)
       {
        MessageBox.Show(ex.Message);
       }
      }
    
      // The PrintPage event is raised for each page to be printed. 
      private void pd_PrintPage(object sender, PrintPageEventArgs ev)
      {
       float linesPerPage = 0;
       float yPos = 0;
       int count = 0;
       float leftMargin = ev.MarginBounds.Left;
       float topMargin = ev.MarginBounds.Top;
       string line = null;
    
       // Calculate the number of lines per page.
       linesPerPage = ev.MarginBounds.Height /
          printFont.GetHeight(ev.Graphics);
    
       // Print each line of the file. 
       while (count < linesPerPage &&
          ((line = streamToPrint.ReadLine()) != null))
       {
        yPos = topMargin + (count * printFont.GetHeight(ev.Graphics));
        ev.Graphics.DrawString(line, printFont, Brushes.Black, leftMargin, yPos, new StringFormat());
        count++;
       }
    
       // If more lines exist, print another page. 
       if (line != null)
        ev.HasMorePages = true;
       else
        ev.HasMorePages = false;
      }
     }


    It would be greatly appreciated if you would mark any helpful entries as helpful and if the entry answers your question, please mark it with the Answer link.

    Friday, January 18, 2013 9:02 PM
  • Error 1 Cannot implicitly convert type 'System.IO.StringReader' to 'System.IO.StreamReader' N:\ICS4U\ISU\ISU\Form1.cs 501 33 ISU

                    streamToPrint = new StringReader(richTextBox1.Text);

    Error 2 Cannot implicitly convert type 'System.IO.StringReader' to 'System.IO.StreamReader' N:\ICS4U\ISU\ISU\Form1.cs 560 33 ISU

                    streamToPrint = new StringReader(richTextBox1.Text);



    Friday, January 18, 2013 10:12 PM
  • Didn't change the definition of streamToPrint to:

      private StringReader streamToPrint;
    

    as outlined in the examples that I provided.  I have tested both of these examples.

    It would be greatly appreciated if you would mark any helpful entries as helpful and if the entry answers your question, please mark it with the Answer link.

    Friday, January 18, 2013 10:43 PM
  • Thank You!

    This has been soo much help!

    Saturday, January 19, 2013 3:37 AM
  • Your welcome and enjoy the coding experience.

    It would be greatly appreciated if you would mark any helpful entries as helpful and if the entry answers your question, please mark it with the Answer link.

    Saturday, January 19, 2013 3:40 AM