7 Replies - 30277 Views - Last Post: 07 May 2008 - 09:05 PM 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

Save richTextBox contents to a txt file to print

Posted 05 May 2008 - 07:30 AM

I asked a different question about this same program but could not get it working properly. I am trying a different approach now, since I have spent hours and hours working on it without finding the solution.

I want the program to use a print dialog box to print the contents of my richTextBox. That is all. No formatting, etc.

Is there a way to save the contents of a richTextBox to a file automatically (the user won't have to see or do anything, it just happens) when the user clicks the print button...and then print the file?

Here is my code that doesn't work, which I want to automatically save the contents of the richTextBox to a file and print that file using the print dialog box.

It brings up the print dialog box and prints a blank page.


 public delegate void PrintPageEventHandler(Object sender,PrintPageEventArgs e);

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

		private void button1_Click(object sender, EventArgs e)
		{

			// Create a SaveFileDialog to request a path and file name to save to.
			SaveFileDialog saveFile1 = new SaveFileDialog();


					// Initialize the SaveFileDialog to specify the RTF extension for the file.
			saveFile1.DefaultExt = "*.rtf";
			saveFile1.Filter = "RTF Files|*.rtf";
	
			   // Save the contents of the RichTextBox into the file.
				richTextBox1.SaveFile(saveFile1.FileName = mypdoc.ToString(), RichTextBoxStreamType.PlainText);
		  
			try
			{
			 
				myprintdlg.Document = mypdoc;
			 
				if (myprintdlg.ShowDialog() == DialogResult.OK)
					mypdoc.Print();
			}
		   
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
		}




The error I get is 'Empty path name is not legal.'
for this line:
richTextBox1.SaveFile(saveFile1.FileName, RichTextBoxStreamType.PlainText);

What would be the path name to save the file to? And how do I get it back out, to print the file?










Will this code save the file? If so, how do I get it to print?

		private void Save(string file, string data)
		{
			StreamWriter writer = new StreamWriter(file);
			writer.Write(data);
			writer.Close();
		}
		private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
		{
			DialogResult result = saveFileDialog1.ShowDialog();

			string file = saveFileDialog1.FileName.ToString();
			string data = richTextBox1.Text;
			Save(file, data);
		}
		}


This post has been edited by OliveOyl3471: 05 May 2008 - 08:00 AM


Is This A Good Question/Topic? 0
  • +

Replies To: Save richTextBox contents to a txt file to print

#2 killnine  Icon User is offline

  • D.I.C Head

Reputation: 19
  • View blog
  • Posts: 161
  • Joined: 12-February 07

Re: Save richTextBox contents to a txt file to print

Posted 05 May 2008 - 08:15 AM

The issue that you are having is that you are performing an operation within the argument:

			   // Save the contents of the RichTextBox into the file.
				richTextBox1.SaveFile(saveFile1.FileName = mypdoc.ToString(), RichTextBoxStreamType.PlainText);
		  


Rather, you should be saving the path to a variable, so you can use it in the instance for saving the file and in the instance for printing the file:



Also, I dont think your file is printing because you aren't giving it any data to print. Typically you give give the print object a stream to print. I would search on MSDN for syntax for PrintDocument:
http://msdn.microsof...ntdocument.aspx
Was This Post Helpful? 1

#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: Save richTextBox contents to a txt file to print

Posted 05 May 2008 - 08:59 AM

The issue that you are having is that you are performing an operation within the argument:

Do you mean this...?
= mypdoc.ToString()


I also tried omitting it.

Could you show me an example of saving the path to a variable?

What would be the path name to save the file to?

Do you mean that I should include this:
 streamToPrint = new StreamReader
			  ("C:\\My Documents\\MyFile.txt");


with "C:\\My Documents\\MyFile.txt" as the path name?

This post has been edited by OliveOyl3471: 05 May 2008 - 09:03 AM

Was This Post Helpful? 0
  • +
  • -

#4 OliveOyl3471  Icon User is offline

  • Everybody's crazy but me!
  • member icon

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

Re: Save richTextBox contents to a txt file to print

Posted 05 May 2008 - 09:18 AM

Is this what you meant?

// Save the contents of the RichTextBox into the file.
		   
			richTextBox1.SaveFile("C:\\My Documents\\MyFile.txt");
			try
			{
				StreamReader streamToPrint = new StreamReader("C:\\My Documents\\MyFile.txt");

				try
				{

					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;
			Font printFont = new Font("Arial", 10);
			StreamReader streamToPrint = new StreamReader("C:\\My Documents\\MyFile.txt");
		   
			// 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;
		}


now it gives an error:
'Could not find a part of the path 'C:\My Documents\MyFile.txt'.'

for this line:
richTextBox1.SaveFile("C:\\My Documents\\MyFile.txt");



btw...sorry for all the different code I posted but it is helping me search and find the solution.
NOW I have changed the path name to a path on my computer (Vista does not have a My Documents).
And the file will save...and print the contents of the textbox, BUT now the print dialog box does not come up! It is supposed to come up.

This post has been edited by OliveOyl3471: 05 May 2008 - 09:43 AM

Was This Post Helpful? 0
  • +
  • -

#5 Jayman  Icon User is offline

  • Student of Life
  • member icon

Reputation: 418
  • View blog
  • Posts: 9,532
  • Joined: 26-December 05

Re: Save richTextBox contents to a txt file to print

Posted 05 May 2008 - 09:45 AM

You might want to try the following tutorial.

How to print the content of a RichTextBox control by using Visual C# .NET or Visual C# 2005
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: Save richTextBox contents to a txt file to print

Posted 05 May 2008 - 10:15 AM

Thank you Jayman. I will check it out. Meanwhile...

Here is the solution I finally came up with. It's probably not exactly right since the only computer it will work on is this one.
If I had a more generic file path it would be better, or if I did not have to save it to a file but could print directly from the textbox...or possibly use the same file I loaded into the textbox.

Anyway this program works:


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;
using System.IO;


namespace Final7
{
	public partial class Form1 : Form
	{
		public Form1()
		{
			InitializeComponent();
		}

		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);
		}

		PrintDialog PrintDialog1 = new PrintDialog();
		PrintDocument pd = new PrintDocument();


		private void button1_Click(object sender, EventArgs e)
		{

			// Save the contents of the RichTextBox into a text file
				richTextBox1.SaveFile("C:\\Users\\George and Tam\\Documents\\MyFile.txt", RichTextBoxStreamType.PlainText);
			//this is probably not right since it will only work on a Vista computer with the same username
			//however, it does work on this computer :)

				PrintDialog1.Document = pd;
				DialogResult result = PrintDialog1.ShowDialog();

			
				pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
				// If the result is OK then print the document.
				if (result == DialogResult.OK)
				{
					StreamReader streamToPrint = new StreamReader("C:\\Users\\George and Tam\\Documents\\MyFile.txt");

					pd.Print();
				}
		}

		// 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;
			Font printFont = new Font("Arial", 10);
			StreamReader streamToPrint = new StreamReader("C:\\Users\\George and Tam\\Documents\\MyFile.txt");

			// 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;
		}
	}
}



This post has been edited by OliveOyl3471: 05 May 2008 - 10:17 AM

Was This Post Helpful? 0
  • +
  • -

#7 thor78  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 1
  • View blog
  • Posts: 121
  • Joined: 06-May 08

Re: Save richTextBox contents to a txt file to print

Posted 07 May 2008 - 06:49 PM

The reason it only works on your computer is because you hard coded the My Document path. Use this instead:
string MyDocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);


This post has been edited by thor78: 07 May 2008 - 06:55 PM

Was This Post Helpful? 0
  • +
  • -

#8 OliveOyl3471  Icon User is offline

  • Everybody's crazy but me!
  • member icon

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

Re: Save richTextBox contents to a txt file to print

Posted 07 May 2008 - 09:05 PM

View Postthor78, on 7 May, 2008 - 06:49 PM, said:

The reason it only works on your computer is because you hard coded the My Document path. Use this instead:
string MyDocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);



That is what I wanted to do, but it gives this error:
Access to the path 'C:\Users\George and Tam\Documents' is denied.
at this line:
richTextBox1.SaveFile(MyDocs, RichTextBoxStreamType.PlainText);

This computer has Vista, so maybe that is the problem?

I don't really need the answer now, since the class is over, but I would still like to know how to do this the right way.
Thanks :)

I am going to ask one of my professors how this is supposed to be done. Hopefully she will have the answer.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1