7 Replies - 72061 Views - Last Post: 03 July 2009 - 02:49 AM Rate Topic: -----

#1 OliveOyl3471  Icon User is offline

  • Everybody's crazy but me!
  • member icon

Reputation: 134
  • View blog
  • Posts: 6,581
  • Joined: 11-July 07

use a print dialog box to print contents of a textbox

Posted 03 May 2008 - 12:07 PM

This program will allow the user to browse for a file and will load the file's contents into a rich text box. It will also open a print dialog box when the user clicks the print button. How do I get the contents of my text box sent to the printer?

 private void Form1_Load(object sender, EventArgs e)
		{
		

			// Create an OpenFileDialog object.
			OpenFileDialog openFile1 = new OpenFileDialog();

			// Initialize the OpenFileDialog to look for text files.
			openFile1.Filter = "Text Files|*.txt";

			// Check if the user selected a file from the OpenFileDialog.
			if (openFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK)

				// Load the contents of the file into a RichTextBox control.
				richTextBox1.LoadFile(openFile1.FileName,
				RichTextBoxStreamType.PlainText);
		}


		private void button1_Click(object sender, EventArgs e)
		{
			{	  
				// Create the print dialog object
				PrintDialog PrintDialog1 = new PrintDialog();
	// Declare the PrintDocument object.
	 System.Drawing.Printing.PrintDocument docToPrint = 
		new System.Drawing.Printing.PrintDocument();
	 // This method will set properties on the PrintDialog object and
	 // then display the dialog.
	   // Allow the user to choose the page range he or she would
		// like to print.
		PrintDialog1.AllowSomePages = true;

		// Show the help button.
		PrintDialog1.ShowHelp = true;

		// Set the Document property to the PrintDocument for 
		// which the PrintPage Event has been handled. To display the
		// dialog, either this property or the PrinterSettings property 
		// must be set 
		PrintDialog1.Document = docToPrint;

		DialogResult result = PrintDialog1.ShowDialog();

		// If the result is OK then print the document.
		if (result==DialogResult.OK)
		{
			docToPrint.Print();
		}

	}

			}

		}

		}

	



Is This A Good Question/Topic? 0
  • +

Replies To: use a print dialog box to print contents of a textbox

#2 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4354
  • View blog
  • Posts: 12,160
  • Joined: 18-April 07

Re: use a print dialog box to print contents of a textbox

Posted 03 May 2008 - 12:31 PM

There are a few threads out there that may help you with this. Printing in C# is just a matter of setting up a few dialog boxes, getting a canvas to draw on, setting up a printpage event to respond to printing requests and drawing and sending.

Here is a thread and a tutorial that can help...

C# - PrintPreviewDialog - Help

C# Tutorials - Printing in C# - By PsychoCoder

Good luck :)
Was This Post Helpful? 0
  • +
  • -

#3 OliveOyl3471  Icon User is offline

  • Everybody's crazy but me!
  • member icon

Reputation: 134
  • View blog
  • Posts: 6,581
  • Joined: 11-July 07

Re: use a print dialog box to print contents of a textbox

Posted 03 May 2008 - 06:42 PM

Thanks. I read both of those threads and tried to redo my program using parts of the code to get it to print...but I could not make it work.
As my program is, in the first message, it does print. But it prints a blank page.
I need to use the print dialog box and it does come up. The only thing I need to change (I think) is how to get the contents of the richTextBox to print.

Is it better to start with the design page and add a print dialog box from the tool box, or is it better to add it using code...or both?
When you double click the print dialog box on the form in design view, is it supposed to go to the code, like it does when you double click a button?

Please tell me how to do this...I tried but could not figure it out.
"So select your printdocument object, go to events and add a PrintPage event for it."

Do you mean highlight the printdocument object in the code, and then go to design view and go to events? I don't have a printdocument object in design view and I can't find events in code view.

This post has been edited by OliveOyl3471: 03 May 2008 - 06:49 PM

Was This Post Helpful? 0
  • +
  • -

#4 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4354
  • View blog
  • Posts: 12,160
  • Joined: 18-April 07

Re: use a print dialog box to print contents of a textbox

Posted 03 May 2008 - 06:49 PM

Have you setup a printpage event? If so, can we see it? This event is the event responsible for printing and is tied to the PrintDocument object. It will be the one that takes the content from the richedit and puts it on the page before printing. It does things like setup the margins, line height, lines per page etc.

Here is the link for it in case you don't have one setup...

Printdocument.PrintPage on MSDN

This is of course assuming you have a windows application and not doing a console application.

:)
Was This Post Helpful? 0
  • +
  • -

#5 OliveOyl3471  Icon User is offline

  • Everybody's crazy but me!
  • member icon

Reputation: 134
  • View blog
  • Posts: 6,581
  • Joined: 11-July 07

Re: use a print dialog box to print contents of a textbox

Posted 03 May 2008 - 10:14 PM

Yes, it is a Windows application.
I did this: Add a PrintDocument object to the form, and double click it.

I checked the site you linked (again).

Do you mean this:
public event PrintPageEventHandler PrintPage

I added that to my code but it gave a warning that the PrintPage event was not used.

I also tried adding some code that should execute whenever the printDocument1_PrintPage event occurs. But it did not execute, so I assume that means my printDocument1_PrintPage event does not occur, which is why my textbox contents do not print. When it prints the blank page, it must be simply printing the blank mypdoc that I created. (Which is exactly what I told it to do).

I really don't want to format the text but when I tried to omit that part it gave errors. The only thing the program has to do (that it doesn't do) is to print the contents of the rich textbox, using a print dialog box. It does not need to be formatted any certain way. Everything else works like it's supposed to.

private void Form1_Load(object sender, EventArgs e)
		{


			// Create an OpenFileDialog object.
			OpenFileDialog openFile1 = new OpenFileDialog();

			// Initialize the OpenFileDialog to look for text files.
			openFile1.Filter = "Text Files|*.txt";

			// Check if the user selected a file from the OpenFileDialog.
			if (openFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK)

				// Load the contents of the file into a RichTextBox control.
				richTextBox1.LoadFile(openFile1.FileName,
				RichTextBoxStreamType.PlainText);
		}



		PageSettings ps = new PageSettings();
		PrintDialog myprintdlg = new PrintDialog();
		PrintDocument mypdoc = new PrintDocument();


		private void button1_Click(object sender, EventArgs e)
		{
			try
			{
				mypdoc.DefaultPageSettings = ps;
			   
				myprintdlg.Document = mypdoc;

				if (myprintdlg.ShowDialog() == DialogResult.OK)
					mypdoc.Print();
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
		}
		private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
		{
				string str = richTextBox1.Text;
				int chars;
				int lines;
				Font f = new Font("Arial", 12);
				SolidBrush b = new SolidBrush(Color.Black);
				StringFormat strformat = new StringFormat();
				strformat.Trimming = StringTrimming.Word; 
				RectangleF myrect = new RectangleF(e.MarginBounds.Left,
				e.MarginBounds.Top, e.MarginBounds.Width, e.MarginBounds.Height);

				SizeF sz = new SizeF(e.MarginBounds.Width, e.MarginBounds.Height - f.GetHeight(e.Graphics));
				
				e.Graphics.MeasureString(str, f, sz, strformat, out chars, out lines); 
				string printstr = str.Substring(0, chars);
				e.Graphics.DrawString(printstr, f, b, myrect, strformat); 

				if (str.Length > chars)
				{
					str = str.Substring(chars);
					e.HasMorePages = true;
				}
				else
					e.HasMorePages = false;
			}
		}
}





Thank you so much for taking the time to help me. :)

This post has been edited by OliveOyl3471: 04 May 2008 - 03:22 PM

Was This Post Helpful? 0
  • +
  • -

#6 OliveOyl3471  Icon User is offline

  • Everybody's crazy but me!
  • member icon

Reputation: 134
  • View blog
  • Posts: 6,581
  • Joined: 11-July 07

Re: use a print dialog box to print contents of a textbox

Posted 04 May 2008 - 02:49 PM

I also tried this but it did not work right either.


using System;
using System.IO;
using System.Drawing;
using System.Drawing.Printing;
using System.Windows.Forms;


 public class PrintingExample : System.Windows.Forms.Form 
 {
	 private System.ComponentModel.Container components;
	 private System.Windows.Forms.Button printButton;
	 private Font printFont;
	 private StreamReader streamToPrint;
 
	public PrintingExample() : base() 
	{
	   // The Windows Forms Designer requires the following call.
	   InitializeComponent();
	}
 
	// The Click event is raised when the user clicks the Print button.
	private void printButton_Click(object sender, EventArgs e) 
	{
	   try 
	   {
		   streamToPrint = new StreamReader
			  ("C:\\My Documents\\MyFile.txt");
		   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;
	}
 
 
	// The Windows Forms Designer requires the following procedure.
	private void InitializeComponent() 
	{
	   this.components = new System.ComponentModel.Container();
	   this.printButton = new System.Windows.Forms.Button();
 
	   this.ClientSize = new System.Drawing.Size(504, 381);
	   this.Text = "Print Example";
 
	   printButton.ImageAlign = 
		  System.Drawing.ContentAlignment.MiddleLeft;
	   printButton.Location = new System.Drawing.Point(32, 110);
	   printButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
	   printButton.TabIndex = 0;
	   printButton.Text = "Print the file.";
	   printButton.Size = new System.Drawing.Size(136, 40);
	   printButton.Click += new System.EventHandler(printButton_Click);
 
	   this.Controls.Add(printButton);
	}
 
	// This is the main entry point for the application.
	public static void Main(string[] args) 
	{
	   Application.Run(new PrintingExample());
	}
 }



here, someone asked the same question, but it is in VB.
Do you know how to convert this from VB to C#?
http://it.gps678.com...4787e0ac7d.html


or is this similar to what I need?
// C#
private void button1_Click(object sender, System.EventArgs e)
{
   // The print document 'myDocument' used below
   // is merely for an example.
   // You will have to specify your own print document.
   printPreviewDialog1.Document = myDocument;
   printPreviewDialog1.ShowDialog();
}


C# Note Be sure that the necessary code to wire up the event handler is present. In this case, it would be similar to the following:
this.button1.Click += new System.EventHandler(this.button1_Click);



Please, please, if you know how to do this please just tell me!
Thanks
:)

This post has been edited by OliveOyl3471: 04 May 2008 - 07:15 PM

Was This Post Helpful? 0
  • +
  • -

#7 OliveOyl3471  Icon User is offline

  • Everybody's crazy but me!
  • member icon

Reputation: 134
  • View blog
  • Posts: 6,581
  • Joined: 11-July 07

Re: use a print dialog box to print contents of a textbox

Posted 05 May 2008 - 06:49 AM

Since I have the print dialog box working, and it will print a blank page (as I told it to do) the only problem I still have is how to get the textbox contents to print. I wonder if I can save it to a file and then print that file?
Was This Post Helpful? 0
  • +
  • -

#8 D.Ginzbourg  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 03-July 09

Re: use a print dialog box to print contents of a textbox

Posted 03 July 2009 - 02:49 AM

View PostOliveOyl3471, on 3 May, 2008 - 11:07 AM, said:

This program will allow the user to browse for a file and will load the file's contents into a rich text box. It will also open a print dialog box when the user clicks the print button. How do I get the contents of my text box sent to the printer?

.
.
.
.
.


I tried it in Windows Application, and it says:

Error 1 Program 'C:\Documents and Settings\Administrator\My Documents\Visual Studio 2008\Projects\WindowsFormsApplication1\WindowsFormsApplication1\obj\Debug\WindowsFormsApplication1.exe' does not contain a static 'Main' method suitable for an entry point WindowsFormsApplication1

Im using Visual Studio 2008 Pro.
I am new in Windows Application (learned basic Console Applications at highschool).
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1