473,581 Members | 2,307 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Print Documents PrintDocument-- what am I doing wrong? Must besomething stupid

I am running out of printing paper trying to debug this...it has to be
trivial, but I cannot figure it out--can you? Why am I not printing
text, but just the initial string "howdy"?

On the screen, when I open a file, the entire contents of the file is
in fact being shown...so why can't I print it later? All of this code
I am getting from a book (Chris Sells) and the net. The solution is
to be found in the fact that stringbuilder is not retaining
information outside the 'using' bracket, despite the fact I made it
'global'.

Keyword search //!!! below to see where I think the problem lies.

RL

using System;
using System.Collecti ons.Generic;
using System.Componen tModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows. Forms;
using System.Diagnost ics;
namespace MyNameSpace1
{
public partial class MyForm : Form
{
string myPrintFilename ;
StringBuilder myGlobalStringB uilder; //!!! this is supposed
to be global to the form MyForm, right?

string strModified; // = String.Copy(str Original); //not used

public MyForm()
{
InitializeCompo nent();
myGlobalStringB uilder = new StringBuilder(" howdy"); //!!!
the only thing that gets printed is 'howdy'!

}

private void toolStripButton 1_Click(object sender, EventArgs
e)
{
Stream myStream;
OpenFileDialog openFileDialog1 = new OpenFileDialog( );
openFileDialog1 .Title = "Open text file";
openFileDialog1 .InitialDirecto ry = @"c:\";
openFileDialog1 .Filter = "txt files (*.txt)|*.txt|A ll
files (*.*)|*.*";

if (openFileDialog 1.ShowDialog() == DialogResult.OK )
{
try
{
if ((myStream = openFileDialog1 .OpenFile()) !=
null)
{
using (myStream)
{
StreamReader sr =
File.OpenText(o penFileDialog1. FileName);
string s = sr.ReadLine();
StringBuilder sb = new StringBuilder() ;
while (s != null)
{
sb.Append(s);
s = sr.ReadLine();

myGlobalStringB uilder.Append(s ); //!!! ??? Why is myGlobal not
appending here?
}
sr.Close();
textBox1.Text = sb.ToString(); //this
works, to show the file text on the screen textBox1

}
}
}
catch (Exception ex)
{
MessageBox.Show ("Error: could not read file from
disk (myStream); Err: " + ex.Message);
}
}
}

private void printToolStripB utton_Click(obj ect sender,
EventArgs e)
{
if (myPrintFilenam e != "")
{
this.printDocum ent1.DocumentNa me =
this.myPrintFil ename;

this.printDocum ent1.Print();
}
}

private void printDocument1_ PrintPage(objec t sender,
System.Drawing. Printing.PrintP ageEventArgs e)
{
//p. 292 Chris Sells
//draw to the e.Graphics object that wraps the print
target

Graphics g = e.Graphics;
using (Font font = new Font("Lucida Console", 48) )
{
string mylocalstring;

mylocalstring =
myGlobalStringB uilder.ToString (); //!!! only prints "Howdy"--the
initial string--never the appended string from myGlobalStringB uilder--
why?

if (myGlobalString Builder.Length != 0)
{
g.DrawString(my localstring, font, Brushes.Blue, 0,
0);
}
}

}
}
}

Aug 28 '08 #1
16 4510
raylopez99 <ra********@yah oo.comwrote:
I am running out of printing paper trying to debug this...it has to be
trivial, but I cannot figure it out--can you? Why am I not printing
text, but just the initial string "howdy"?
There's 4 things wrong with your code...
1. the variable myPrintFilename isn't being set to
openFileDialog1 .FileName 2. You are using Append when you should be
using AppendLine 3. You have the myGlobalStringB uilder after the
sr.ReadLine instead of after the sb.Append (which should be
sb.AppendLine) 4. You're using Lucinda 48, instead of something
smaller...
On the screen, when I open a file, the entire contents of the file is
in fact being shown...so why can't I print it later? All of this code
I am getting from a book (Chris Sells) and the net. The solution is
to be found in the fact that stringbuilder is not retaining
information outside the 'using' bracket, despite the fact I made it
'global'.

Keyword search //!!! below to see where I think the problem lies.

RL

using System;
using System.Collecti ons.Generic;
using System.Componen tModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows. Forms;
using System.Diagnost ics;

namespace MyNameSpace1
{
public partial class MyForm : Form
{
string myPrintFilename ;
StringBuilder myGlobalStringB uilder; //!!! this is supposed
to be global to the form MyForm, right?

string strModified; // = String.Copy(str Original); //not used

public MyForm()
{
InitializeCompo nent();
myGlobalStringB uilder = new StringBuilder(" howdy"); //!!!
the only thing that gets printed is 'howdy'!

}

private void toolStripButton 1_Click(object sender, EventArgs
e)
{
Stream myStream;
OpenFileDialog openFileDialog1 = new OpenFileDialog( );
openFileDialog1 .Title = "Open text file";
openFileDialog1 .InitialDirecto ry = @"c:\";
openFileDialog1 .Filter = "txt files (*.txt)|*.txt|A ll
files (*.*)|*.*";

if (openFileDialog 1.ShowDialog() == DialogResult.OK )
{
try
{
if ((myStream = openFileDialog1 .OpenFile()) !=
null)
{
using (myStream)
{
StreamReader sr =
File.OpenText(o penFileDialog1. FileName);
string s = sr.ReadLine();
StringBuilder sb = new StringBuilder() ;
while (s != null)
{
sb.Append(s);
s = sr.ReadLine();

myGlobalStringB uilder.Append(s ); //!!! ??? Why is myGlobal not
appending here?
}
sr.Close();
textBox1.Text = sb.ToString(); //this
works, to show the file text on the screen textBox1

}
}
}
catch (Exception ex)
{
MessageBox.Show ("Error: could not read file from
disk (myStream); Err: " + ex.Message);
}
}
}

private void printToolStripB utton_Click(obj ect sender,
EventArgs e)
{
if (myPrintFilenam e != "")
{
this.printDocum ent1.DocumentNa me =
this.myPrintFil ename;

this.printDocum ent1.Print();
}
}

private void printDocument1_ PrintPage(objec t sender,
System.Drawing. Printing.PrintP ageEventArgs e)
{
//p. 292 Chris Sells
//draw to the e.Graphics object that wraps the print
target

Graphics g = e.Graphics;
using (Font font = new Font("Lucida Console", 48) )
{
string mylocalstring;

mylocalstring =
myGlobalStringB uilder.ToString (); //!!! only prints "Howdy"--the
initial string--never the appended string from myGlobalStringB uilder--
why?

if (myGlobalString Builder.Length != 0)
{
g.DrawString(my localstring, font, Brushes.Blue, 0,
0);
}
}

}

}
}
--
J. Moreno
Aug 28 '08 #2
On Aug 28, 5:28*am, J. Moreno <pl...@newsread ers.comwrote:
raylopez99 <raylope...@yah oo.comwrote:
I am running out of printing paper trying to debug this...it has to be
trivial, but I cannot figure it out--can you? *Why am I not printing
text, but just the initial string "howdy"?

There's 4 things wrong with your code...
* *1. the variable myPrintFilename isn't being set to
* *openFileDialog 1.FileName 2. You are using Append when you should be
* *using AppendLine 3. You have the myGlobalStringB uilder after the
* * * sr.ReadLine instead of after the sb.Append (which should be
* *sb.AppendLine) 4. You're using Lucinda 48, instead of something
* *smaller...
There's one more here. This:

if ((myStream = openFileDialog1 .OpenFile()) !=
null)
{
using (myStream)
{
StreamReader sr =
File.OpenText(o penFileDialog1. FileName);
string s = sr.ReadLine();
StringBuilder sb = new StringBuilder() ;
while (s != null)
{
sb.Append(s);
s = sr.ReadLine();

myGlobalStringB uilder.Append(s ); //!!! ??? Why is myGlobal not
appending here?
}
sr.Close();
textBox1.Text = sb.ToString(); //this
works, to show the file text on the screen textBox1

}
}

Note how myStream is never actually used. Also, it is pointlessly
initialized outside the using-expression.
Aug 28 '08 #3
Set a breakpoint in printDocument1_ PrintPage, at the line where
"mylocalstr ing" is set. I believe you will see that the value is correct for
"myStringBuilde r". The lack of carriage returns will hide the fact that the
string is correct when printed. I believe it is going off the page. The
print document functions won't fix newlines, wrapping, etc. Also, you need
to worry about the next page when the text is long. Printing is very
complicated in .net, until you get the hang of it...

"raylopez99 " wrote:
I am running out of printing paper trying to debug this...it has to be
trivial, but I cannot figure it out--can you? Why am I not printing
text, but just the initial string "howdy"?

On the screen, when I open a file, the entire contents of the file is
in fact being shown...so why can't I print it later? All of this code
I am getting from a book (Chris Sells) and the net. The solution is
to be found in the fact that stringbuilder is not retaining
information outside the 'using' bracket, despite the fact I made it
'global'.

Keyword search //!!! below to see where I think the problem lies.

RL

using System;
using System.Collecti ons.Generic;
using System.Componen tModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows. Forms;
using System.Diagnost ics;
namespace MyNameSpace1
{
public partial class MyForm : Form
{
string myPrintFilename ;
StringBuilder myGlobalStringB uilder; //!!! this is supposed
to be global to the form MyForm, right?

string strModified; // = String.Copy(str Original); //not used

public MyForm()
{
InitializeCompo nent();
myGlobalStringB uilder = new StringBuilder(" howdy"); //!!!
the only thing that gets printed is 'howdy'!

}

private void toolStripButton 1_Click(object sender, EventArgs
e)
{
Stream myStream;
OpenFileDialog openFileDialog1 = new OpenFileDialog( );
openFileDialog1 .Title = "Open text file";
openFileDialog1 .InitialDirecto ry = @"c:\";
openFileDialog1 .Filter = "txt files (*.txt)|*.txt|A ll
files (*.*)|*.*";

if (openFileDialog 1.ShowDialog() == DialogResult.OK )
{
try
{
if ((myStream = openFileDialog1 .OpenFile()) !=
null)
{
using (myStream)
{
StreamReader sr =
File.OpenText(o penFileDialog1. FileName);
string s = sr.ReadLine();
StringBuilder sb = new StringBuilder() ;
while (s != null)
{
sb.Append(s);
s = sr.ReadLine();

myGlobalStringB uilder.Append(s ); //!!! ??? Why is myGlobal not
appending here?
}
sr.Close();
textBox1.Text = sb.ToString(); //this
works, to show the file text on the screen textBox1

}
}
}
catch (Exception ex)
{
MessageBox.Show ("Error: could not read file from
disk (myStream); Err: " + ex.Message);
}
}
}

private void printToolStripB utton_Click(obj ect sender,
EventArgs e)
{
if (myPrintFilenam e != "")
{
this.printDocum ent1.DocumentNa me =
this.myPrintFil ename;

this.printDocum ent1.Print();
}
}

private void printDocument1_ PrintPage(objec t sender,
System.Drawing. Printing.PrintP ageEventArgs e)
{
//p. 292 Chris Sells
//draw to the e.Graphics object that wraps the print
target

Graphics g = e.Graphics;
using (Font font = new Font("Lucida Console", 48) )
{
string mylocalstring;

mylocalstring =
myGlobalStringB uilder.ToString (); //!!! only prints "Howdy"--the
initial string--never the appended string from myGlobalStringB uilder--
why?

if (myGlobalString Builder.Length != 0)
{
g.DrawString(my localstring, font, Brushes.Blue, 0,
0);
}
}

}
}
}

Aug 28 '08 #4
On Aug 28, 5:57*am, Family Tree Mike
<FamilyTreeM... @discussions.mi crosoft.comwrot e:

No kidding FTM! Printing is indeed very complicated in .NET. In
fact, I'm giving up after this post! (assuming I don't get a reply
that fixes the below)

I just spent half a day doing various things trying to get print to
work. I finally got it to work--somewhat--but with one big caveat--
the print only prints one page! If it's more than one page of text,
you get an infinite loop (the pages just keep increasing, until you
hit cancel).

Below is the code, and where I think the infinite loop problem is--
I've keyword marked it with 'fooey' (see also // Infinite Loop? Why?)

Like I say, everything works fine, if the textbox has one page of text
in it or less.

I also tried setting up a temporary file and writing and reading from
it, but it's the same as reading from a textbox (but nevertheless I
left this code in below, commented out).

I appreciate you guys helping. Please don't spend too much time on
this--I've thrown in the towel--but I do believe the problem is in the
place marked "fooey" below--you are not 'consuming' your string
properly when using the method ".Substring " (this code was from an
example on the net--see the header)--and thus the string never
'decreases' so you always get a "e.HasMoreP ages = true;" condition,
rather than "= false".

If any of you pity a newbie, please upload a working example of a
simple print (no preview required) for printing from a textbox.

RL

//adapted from http://www.expresscomputeronline.com...hspace02.shtml
//main code from here
// an excellent example, too bad it doesn't work for me

// and from Chris Sells, Chapter 8, Printing in WinForms
//Chris Sells Chap 8 is very very simplistic--in retrospect I suspect
because printing is difficult and he didn't want to spend time on it
//

using System;
using System.Collecti ons.Generic;
using System.Componen tModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows. Forms;
using System.Diagnost ics;
using System.Drawing. Printing; //needed for print
namespace MyProgram1
{
public partial class MyPrintForm : Form
{
string myPrintFilename ;
StringBuilder myGlobalStringB uilder;
Font f;
SolidBrush b;
StringFormat strformat;
string printstr;
int intchars, intlines;

StreamReader reader;
public MyPrintForm()
{
InitializeCompo nent();
myGlobalStringB uilder = new StringBuilder() ;
strformat = new StringFormat();
FileNotSavedYet = true; //dirty file bool indicator—not
used

}

private void printToolStripB utton_Click(obj ect sender,
EventArgs e)
{
if (myPrintFilenam e != "")
{

this.printDocum ent1.DocumentNa me =
this.myPrintFil ename;

this.printDocum ent1.Print();
}

}

private void printDocument1_ PrintPage(objec t sender,
System.Drawing. Printing.PrintP ageEventArgs e)
{
////try writing textbox text to a file first! Make it
write to a temp file and read back.
////// //UPDATE: Not true,you still get an infinite loop
if you do this

//string path1 =
System.IO.Path. GetDirectoryNam e(System.Reflec tion.Assembly.G etExecutingAsse mbly().Location );
//string path2 = "\\temp12345432 1.txt"; //temporary file
name
//string path12 = path1 + path2; //local path + file name

//try
//{
// using (FileStream fs = new FileStream(path 12,
FileMode.Create )) //fs = new FileStream("tes t123454321.txt" ,
FileMode.OpenOr Create)
// {
// using (StreamWriter myWritter = new
StreamWriter(fs , System.Text.Enc oding.ASCII))
// {
// myWritter.Write (textBox1.Text) ;
// }
// }
//}
//catch(Exception ex)
//{
// MessageBox.Show (ex.Message);
//}

//string mylocalstring;

//try
//{
// reader = new StreamReader(pa th12);
//}
//catch (Exception ex)
//{
// MessageBox.Show ("reader err:" + ex.Message);
//}

//mylocalstring = reader.ReadToEn d();

RectangleF myrect = new
RectangleF(e.Ma rginBounds.Left ,e.MarginBounds .Top,
e.MarginBounds. Width,e.MarginB ounds.Height);
SizeF sz = new SizeF(e.MarginB ounds.Width,
e.MarginBounds. Height);

string mylocalstring = textBox1.Text; //also equivalent it
turns out--same thing!
//thus, no need to create and save a temporary file from the textBox1—
just use directly.

//mylocalstring = myGlobalStringB uilder.ToString ();
e.Graphics.Meas ureString(myloc alstring, f, sz, strformat,
out intchars, out intlines);

printstr = mylocalstring.S ubstring(0,intc hars);
e.Graphics.Draw String(printstr , f, b, myrect,strforma t);

if (mylocalstring. Length intchars)
{
mylocalstring = mylocalstring.S ubstring(intcha rs);//
problem here! fooey!
// Infinite Loop? Why?

// one idea: is mylocalstring being changed? note .Substring library
method here has only one parameter
//should .Substring method not have two parameters?
// Update: tried with ‘mylocalstring =
mylocalstring.S ubstring(0,intc hars); and still failed
// but, perhaps the first parameter should be intchar + intchar*N,
where N=0,1,2? Anybody have thoughts?

e.HasMorePages = true;
}
else
e.HasMorePages = false;
//end of relevant code--rest below is not relevant to this problem --
RL
////p. 292 Chris Sells
////draw to the e.Graphics object that wraps the print
target
//Graphics g = e.Graphics;
//using (Font font = new Font("Courier", 12))
//{
// string mylocalstring;

// // mylocalstring =
myGlobalStringB uilder.ToString (); //commented out, an earlier version
used this
// mylocalstring = textBox1.Text;
// if (myGlobalString Builder.Length != 0)
// {
// g.DrawString(my localstring, font, Brushes.Blue,
0, 0);
// }
//}
////// end of pg. 292 Chris Sells

}
// this is code that you need to open a file. Not really relevant for
the 'infinite loop' problem above, but I include for Pavel
private void openAToolStripB uttun_Click(obj ect sender,
EventArgs e)
{
Stream myStream;
OpenFileDialog openFileDialog1 = new OpenFileDialog( );
openFileDialog1 .Title = "Open text file";
openFileDialog1 .InitialDirecto ry = @"c:\";
openFileDialog1 .Filter = "txt files (*.txt)|*.txt|A ll
files (*.*)|*.*";

if (openFileDialog 1.ShowDialog() == DialogResult.OK )
{
try
{
if ((myStream = openFileDialog1 .OpenFile()) !=
null)
{
using (myStream)
{
StreamReader sr =
File.OpenText(o penFileDialog1. FileName);
myPrintFilename =
openFileDialog1 .FileName;
string s = sr.ReadLine();
StringBuilder sb = new StringBuilder() ;
while (s != null)
{
sb.Append(s);
myGlobalStringB uilder.AppendLi ne(s);
s = sr.ReadLine();
myGlobalStringB uilder.AppendLi ne(s);
Debug.WriteLine ("Hi");

}
sr.Close();
textBox1.Text = sb.ToString();
//
myGlobalStringB uilder.Append(s b.ToString()); //wrong

}
}
}
catch (Exception ex)
{
MessageBox.Show ("Error: could not read file from
disk (myStream); Err: " + ex.Message);
}
}
}

// // this is code that you need to save a file. Not really relevant
for the 'infinite loop' problem above, but I include for Pavel

private void saveToolStripBu tton_Click(obje ct sender,
EventArgs e)
{

// SaveFileDialog saveFileDialog1 = new SaveFileDialog( ); //
not needed
SaveFileDialog MySaveFileDialo g = new SaveFileDialog( );
MySaveFileDialo g.Filter = "txt files (*.txt)|*.txt|A ll
files (*.*)|*.*";
MySaveFileDialo g.DefaultExt = "txt";
MySaveFileDialo g.FilterIndex = 2;
MySaveFileDialo g.RestoreDirect ory = true;

if (MySaveFileDial og.ShowDialog() == DialogResult.OK )
{
using (Stream myStream = MySaveFileDialo g.OpenFile())
{
if (myStream != null)
{
using (StreamWriter myWritter = new
StreamWriter(my Stream, System.Text.Enc oding.ASCII))
{
myWritter.Write (textBox1.Text) ;
}
}
}

}
}

private void printDocument1_ BeginPrint(obje ct sender,
System.Drawing. Printing.PrintE ventArgs e)
{
//can go here to avoid having to do this for every page
(since same for every page)
////Hence we have created the Font, SolidBrush and
StringFormat objects in the handler for the BeginPrint event. Note
that we could have done this in the handler of the PrintPage event as
well but then these objects would have been created for each page

f = new Font("Arial", 12, FontStyle.Regul ar);
b = new SolidBrush(Colo r.Black);
strformat.Trimm ing = StringTrimming. Word;
}

private void printDocument1_ QueryPageSettin gs(object sender,
System.Drawing. Printing.QueryP ageSettingsEven tArgs e)
{
//set margins to 0.5" all around p. 305 Chris Sells
// e.PageSettings. Margins = new Margins(50, 50, 50, 50); //
does not really help much it seems, but does not hurt either
}

}
}

Aug 28 '08 #5
On Aug 28, 4:53*am, Pavel Minaev <int...@gmail.c omwrote:
Note how myStream is never actually used. Also, it is pointlessly
initialized outside the using-expression.
Privet Pavel!

I thank you for your time. Now since I've seen so many ways to open/
close read/write a text file, I would appreciate the 'right' way.
Even experts (on the net) have disagreed about this.

So, in my last post (the long one, in this thread, from a few minutes
ago), I include a comment: "// this is code that you need to open a
file. Not really relevant for the 'infinite loop' problem above, but
I include for Pavel"

If you can please tell me what parts of this code is not needed to
safely open/close read/write a text file, I would be thankful. This
way, I can put the 'proper' code into my library, and for future
reference not have to worry about it.

I also have done this for binary files, but for now text file is more
important, for this example. My binary files seem to be working (so
are my text files, but I don't like using code that is superfluous or
not needed, as you say).

Spasibo

RL

Aug 29 '08 #6
raylopez99 <ra********@yah oo.comwrote:
On Aug 28, 4:53*am, Pavel Minaev <int...@gmail.c omwrote:
Note how myStream is never actually used. Also, it is pointlessly
initialized outside the using-expression.

Privet Pavel!

I thank you for your time. Now since I've seen so many ways to open/
close read/write a text file, I would appreciate the 'right' way.
Even experts (on the net) have disagreed about this.
This really has nothing to do with the "right" way to open a file, but
rather an unused variable.
myStream can be left out entirely without changing how the program
works.

But if you want to use the "using" statement, and don't want to use
myStream for anything, then replace
using (myStream)
{
StreamReader sr = File.OpenText(o penFileDialog1. FileName);
}

With

using (StreamReader sr = File.OpenText(o penFileDialog1. FileName))
{
}

And then delete the if where mystream is assigned.

--
J.B. Moreno
Aug 29 '08 #7
It appears you get the value from the textbox and put it into mylocalstring
within the printDocument1_ PrintPage routine, but you never reset the textbox
to what is left. This means, the textbox remains the same throughout the
printing and thus there is always more than one page left to print.

"raylopez99 " <ra********@yah oo.comwrote in message
news:b4******** *************** ***********@z66 g2000hsc.google groups.com...
On Aug 28, 5:57 am, Family Tree Mike
<FamilyTreeM... @discussions.mi crosoft.comwrot e:

No kidding FTM! Printing is indeed very complicated in .NET. In
fact, I'm giving up after this post! (assuming I don't get a reply
that fixes the below)

I just spent half a day doing various things trying to get print to
work. I finally got it to work--somewhat--but with one big caveat--
the print only prints one page! If it's more than one page of text,
you get an infinite loop (the pages just keep increasing, until you
hit cancel).

Below is the code, and where I think the infinite loop problem is--
I've keyword marked it with 'fooey' (see also // Infinite Loop? Why?)

Like I say, everything works fine, if the textbox has one page of text
in it or less.

I also tried setting up a temporary file and writing and reading from
it, but it's the same as reading from a textbox (but nevertheless I
left this code in below, commented out).

I appreciate you guys helping. Please don't spend too much time on
this--I've thrown in the towel--but I do believe the problem is in the
place marked "fooey" below--you are not 'consuming' your string
properly when using the method ".Substring " (this code was from an
example on the net--see the header)--and thus the string never
'decreases' so you always get a "e.HasMoreP ages = true;" condition,
rather than "= false".

If any of you pity a newbie, please upload a working example of a
simple print (no preview required) for printing from a textbox.

RL

//adapted from
http://www.expresscomputeronline.com...hspace02.shtml
//main code from here
// an excellent example, too bad it doesn't work for me

// and from Chris Sells, Chapter 8, Printing in WinForms
//Chris Sells Chap 8 is very very simplistic--in retrospect I suspect
because printing is difficult and he didn't want to spend time on it
//

using System;
using System.Collecti ons.Generic;
using System.Componen tModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows. Forms;
using System.Diagnost ics;
using System.Drawing. Printing; //needed for print
namespace MyProgram1
{
public partial class MyPrintForm : Form
{
string myPrintFilename ;
StringBuilder myGlobalStringB uilder;
Font f;
SolidBrush b;
StringFormat strformat;
string printstr;
int intchars, intlines;

StreamReader reader;
public MyPrintForm()
{
InitializeCompo nent();
myGlobalStringB uilder = new StringBuilder() ;
strformat = new StringFormat();
FileNotSavedYet = true; //dirty file bool indicator—not
used

}

private void printToolStripB utton_Click(obj ect sender,
EventArgs e)
{
if (myPrintFilenam e != "")
{

this.printDocum ent1.DocumentNa me =
this.myPrintFil ename;

this.printDocum ent1.Print();
}

}

private void printDocument1_ PrintPage(objec t sender,
System.Drawing. Printing.PrintP ageEventArgs e)
{
////try writing textbox text to a file first! Make it
write to a temp file and read back.
////// //UPDATE: Not true,you still get an infinite loop
if you do this

//string path1 =
System.IO.Path. GetDirectoryNam e(System.Reflec tion.Assembly.G etExecutingAsse mbly().Location );
//string path2 = "\\temp12345432 1.txt"; //temporary file
name
//string path12 = path1 + path2; //local path + file name

//try
//{
// using (FileStream fs = new FileStream(path 12,
FileMode.Create )) //fs = new FileStream("tes t123454321.txt" ,
FileMode.OpenOr Create)
// {
// using (StreamWriter myWritter = new
StreamWriter(fs , System.Text.Enc oding.ASCII))
// {
// myWritter.Write (textBox1.Text) ;
// }
// }
//}
//catch(Exception ex)
//{
// MessageBox.Show (ex.Message);
//}

//string mylocalstring;

//try
//{
// reader = new StreamReader(pa th12);
//}
//catch (Exception ex)
//{
// MessageBox.Show ("reader err:" + ex.Message);
//}

//mylocalstring = reader.ReadToEn d();

RectangleF myrect = new
RectangleF(e.Ma rginBounds.Left ,e.MarginBounds .Top,
e.MarginBounds. Width,e.MarginB ounds.Height);
SizeF sz = new SizeF(e.MarginB ounds.Width,
e.MarginBounds. Height);

string mylocalstring = textBox1.Text; //also equivalent it
turns out--same thing!
//thus, no need to create and save a temporary file from the textBox1—
just use directly.

//mylocalstring = myGlobalStringB uilder.ToString ();
e.Graphics.Meas ureString(myloc alstring, f, sz, strformat,
out intchars, out intlines);

printstr = mylocalstring.S ubstring(0,intc hars);
e.Graphics.Draw String(printstr , f, b, myrect,strforma t);

if (mylocalstring. Length intchars)
{
mylocalstring = mylocalstring.S ubstring(intcha rs);//
problem here! fooey!
// Infinite Loop? Why?

// one idea: is mylocalstring being changed? note .Substring library
method here has only one parameter
//should .Substring method not have two parameters?
// Update: tried with ‘mylocalstring =
mylocalstring.S ubstring(0,intc hars); and still failed
// but, perhaps the first parameter should be intchar + intchar*N,
where N=0,1,2? Anybody have thoughts?

e.HasMorePages = true;
}
else
e.HasMorePages = false;
//end of relevant code--rest below is not relevant to this problem --
RL
////p. 292 Chris Sells
////draw to the e.Graphics object that wraps the print
target
//Graphics g = e.Graphics;
//using (Font font = new Font("Courier", 12))
//{
// string mylocalstring;

// // mylocalstring =
myGlobalStringB uilder.ToString (); //commented out, an earlier version
used this
// mylocalstring = textBox1.Text;
// if (myGlobalString Builder.Length != 0)
// {
// g.DrawString(my localstring, font, Brushes.Blue,
0, 0);
// }
//}
////// end of pg. 292 Chris Sells

}
// this is code that you need to open a file. Not really relevant for
the 'infinite loop' problem above, but I include for Pavel
private void openAToolStripB uttun_Click(obj ect sender,
EventArgs e)
{
Stream myStream;
OpenFileDialog openFileDialog1 = new OpenFileDialog( );
openFileDialog1 .Title = "Open text file";
openFileDialog1 .InitialDirecto ry = @"c:\";
openFileDialog1 .Filter = "txt files (*.txt)|*.txt|A ll
files (*.*)|*.*";

if (openFileDialog 1.ShowDialog() == DialogResult.OK )
{
try
{
if ((myStream = openFileDialog1 .OpenFile()) !=
null)
{
using (myStream)
{
StreamReader sr =
File.OpenText(o penFileDialog1. FileName);
myPrintFilename =
openFileDialog1 .FileName;
string s = sr.ReadLine();
StringBuilder sb = new StringBuilder() ;
while (s != null)
{
sb.Append(s);
myGlobalStringB uilder.AppendLi ne(s);
s = sr.ReadLine();
myGlobalStringB uilder.AppendLi ne(s);
Debug.WriteLine ("Hi");

}
sr.Close();
textBox1.Text = sb.ToString();
//
myGlobalStringB uilder.Append(s b.ToString()); //wrong

}
}
}
catch (Exception ex)
{
MessageBox.Show ("Error: could not read file from
disk (myStream); Err: " + ex.Message);
}
}
}

// // this is code that you need to save a file. Not really relevant
for the 'infinite loop' problem above, but I include for Pavel

private void saveToolStripBu tton_Click(obje ct sender,
EventArgs e)
{

// SaveFileDialog saveFileDialog1 = new SaveFileDialog( ); //
not needed
SaveFileDialog MySaveFileDialo g = new SaveFileDialog( );
MySaveFileDialo g.Filter = "txt files (*.txt)|*.txt|A ll
files (*.*)|*.*";
MySaveFileDialo g.DefaultExt = "txt";
MySaveFileDialo g.FilterIndex = 2;
MySaveFileDialo g.RestoreDirect ory = true;

if (MySaveFileDial og.ShowDialog() == DialogResult.OK )
{
using (Stream myStream = MySaveFileDialo g.OpenFile())
{
if (myStream != null)
{
using (StreamWriter myWritter = new
StreamWriter(my Stream, System.Text.Enc oding.ASCII))
{
myWritter.Write (textBox1.Text) ;
}
}
}

}
}

private void printDocument1_ BeginPrint(obje ct sender,
System.Drawing. Printing.PrintE ventArgs e)
{
//can go here to avoid having to do this for every page
(since same for every page)
////Hence we have created the Font, SolidBrush and
StringFormat objects in the handler for the BeginPrint event. Note
that we could have done this in the handler of the PrintPage event as
well but then these objects would have been created for each page

f = new Font("Arial", 12, FontStyle.Regul ar);
b = new SolidBrush(Colo r.Black);
strformat.Trimm ing = StringTrimming. Word;
}

private void printDocument1_ QueryPageSettin gs(object sender,
System.Drawing. Printing.QueryP ageSettingsEven tArgs e)
{
//set margins to 0.5" all around p. 305 Chris Sells
// e.PageSettings. Margins = new Margins(50, 50, 50, 50); //
does not really help much it seems, but does not hurt either
}

}
}

Aug 29 '08 #8
FTM you da man!

I did what you suggested, tinkered around with it, and finally it
works but with two minor but important changes:

1/ first and foremost, you must place this line: textBox1.Text =
printstr;

Here:
/////////////////////////
e.Graphics.Meas ureString(myloc alstring, f, sz, strformat,
out intchars, out intlines);

printstr = mylocalstring.S ubstring(0,intc hars);

textBox1.Text = printstr;
//IMPORTANT! DO NOT LEAVE OUT--GET INFINITE LOOP WHEN MORE THAN ONE
PAGE OF TEXT PRESENT

e.Graphics.Draw String(printstr , f, b, myrect,strforma t);

if (mylocalstring. Length intchars)
{
/////////////////////////

2/ A minor point but makes the page look decent, since you don't
print close to the edge: set the "OriginAtMargin s" property of the
printDocument1 icon (at the Wizard, I could not figure out how to set
it programically) to "FALSE" (not true).

Now the code works flawlessly.
Thanks FTM!

RL
Family Tree Mike wrote:
It appears you get the value from the textbox and put it into mylocalstring
within the printDocument1_ PrintPage routine, but you never reset the textbox
to what is left. This means, the textbox remains the same throughout the
printing and thus there is always more than one page left to print.
Aug 29 '08 #9
J.B. Moreno--I did what you suggested and it appears the code works
fine, but, I take it you are sure that this is as 'safe' as before--
what if somebody is reading from the floppy drive and the drive fails
because the floppy disk is taken out of the slot? But I trust you've
thought through this problem. Anyway I wrapped the 'using' with a try/
catch block just to be safer.

I will update my library with your suggestion in mind.

Thanks,

RL

J.B. Moreno wrote:
>
This really has nothing to do with the "right" way to open a file, but
rather an unused variable.
myStream can be left out entirely without changing how the program
works.

But if you want to use the "using" statement, and don't want to use
myStream for anything, then replace
using (myStream)
{
StreamReader sr = File.OpenText(o penFileDialog1. FileName);
}

With

using (StreamReader sr = File.OpenText(o penFileDialog1. FileName))
{
}

And then delete the if where mystream is assigned.

--
J.B. Moreno
Aug 29 '08 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
4410
by: Sriram | last post by:
Hi, I am having trouble matching a regex that combines a negated character class and an anchor ($). Basically, I want to match all strings that don't end in a digit. So I tried: bash-2.05a@bermuda:15$perl -e 'while (<STDIN>) { if (/$/) { print;}}' skdsklds skdsklds
4
5600
by: Simom Thorpe | last post by:
Hi, I'm trying to insert a line into a MS access DB using ASP on IIS 5. This is the line: con.execute "INSERT INTO newProds(title,desc,catcode) VALUES ('Champagne Muff Scarf','','AC304B')" But it throws up this error:
2
1294
by: keithlackey | last post by:
I'm relatively new to python and I've run into this problem. DECLARING CLASS class structure: def __init__(self, folders = ): self.folders = folders def add_folder(self, folder):
2
2701
by: Aaron Ackerman | last post by:
I cannot a row to this bound DataGrid to SAVE MY LIFE! I have tried everything and I am at a loss. The using goes into add mode with the add button adds his data then updates with the update button, seems simple. I am using ALL visual controls (supposedly to simplify things. If I was not using the visual controls and calling an ExecuteNonQuery...
6
1532
by: Hitesh Joshi | last post by:
Hi, I wanted to pass a popup mesage using windows messagin service to five PCs. If I just use following then PC1 gets the popup service message: import os os.system('net send PC1 "Message"')
2
1405
by: shapper | last post by:
Hello, I have an ASP.NET page and in its runtime code I am trying to get an user profile, change it and save it. It works if I use Profile, which is the profile for the current authenticated user. But I want to change the profile of another user. Anyway, I am using:
2
1822
by: alnoir | last post by:
I've looked around online and have even had a friend help me, however, for some reason I can't compare two strings. I'm doing this at the end of the code (within the two foreach loops), above where the 'print "found"' code is located. It works when I use a string rather than the scalar variable '$word'. However, this just isn't feasible in...
0
1318
by: shapper | last post by:
Hello, I am creating a class with a control. I compiled the class and used it on an Asp.Net 2.0 web site page. I can see the begin and end tags of my control (<oland </ol>) but somehow the child controls (just a literal for testing) of my control is not being added to the page. Could someone tell me what am I doing wrong?
10
1788
by: DavidSeck.com | last post by:
Hi, I am working with the Facebook API right now, an I have kind of a problem, but I don't know what I am doing wrong. So I have a few arrays, f.ex.: User albums: array(2) {
0
7862
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7789
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
8144
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
1
7894
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
6551
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5670
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3820
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1400
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1132
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.