Print Preview & Print in C#

Got it to work and thought I'd share.

Page 1 of 1

3 Replies - 46248 Views - Last Post: 09 March 2009 - 11:37 AM Rate Topic: -----

#1 W.Carlisle  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 05-March 09

Print Preview & Print in C#

Post icon  Posted 05 March 2009 - 10:50 PM

I was having a bit of trouble getting text to print out (or to get a print preview of it). After reading a bunch of stuff online and fiddling with it a bunch, I got both to work for me...so I thought I'd share. Hopefully it will help someone else too. :-)

All my little project is, is a form with 2 buttons: (1) Print Preview and (2) Print. They were designed to output the contents of a text document to either the printer or a print preview window.


Attached Image


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

namespace Test001
{
	public partial class Form1 : Form
	{
		private Font printFont;
		private StreamReader streamToPrint;
		private PrintDocument pd = new PrintDocument();

		public Form1()
		{
			InitializeComponent();

			printFont = new Font("Arial", 10);
			pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
		   
		}

		private void printThis_Click(object sender, EventArgs e)
		{
			try
			{
				streamToPrint = new StreamReader("C:\\Temp\\text.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);
			}
		}


		private void printPrev_Click(object sender, EventArgs e)
		{
			try
			{
				streamToPrint = new StreamReader("C:\\Temp\\text.txt");
				try
				{
					//printFont = new Font("Arial", 10);
					//PrintDocument pd = new PrintDocument();
					//pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);

					PrintPreviewDialog ppdlg = new PrintPreviewDialog();
					ppdlg.Document = pd;
					ppdlg.ShowDialog();
				}
				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);
				count++;
			}

			// If more lines exist, print another page...
			if (line != null)
				ev.HasMorePages = true;
			else
				ev.HasMorePages = false;
		}


	}
}



I had not see both examples included in a simplistic fashion anywhere I looked online so I thought I'd post it just in case it could be useful.

Thank you guys for all of your really helpful examples and dialog. You've been more helpful to me than I can really say. Hopefully as my knowledge increases a bit, I'll be able to return the favor in some small way.

Update: I found another way to do it that is even simpler (and works better)...

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

namespace Test002
{
	public partial class Form1 : Form
	{
		private Font printFont;
		private PrintDocument pd = new PrintDocument();
		private PrintPreviewDialog ppdlg = new PrintPreviewDialog();

		private string documentContents;
		private string stringToPrint;


		public Form1()
		{
			InitializeComponent();

			printFont = new Font("Arial", 10);
			pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
			ReadDocument();
		   
		}

		private void printThis_Click(object sender, EventArgs e)
		{
			//ReadDocument();
			pd.Print();
		}


		private void printPrev_Click(object sender, EventArgs e)
		{
			//ReadDocument();
			ppdlg.Document = pd;
			ppdlg.ShowDialog();
		}


		private void ReadDocument()
		{
			string docName = "text.txt";
			string docPath = @"C:\Temp\";
			pd.DocumentName = docName;
			using (FileStream stream = new FileStream(docPath + docName, FileMode.Open))
			using (StreamReader reader = new StreamReader(stream))
			{
				documentContents = reader.ReadToEnd();
			}
			stringToPrint = documentContents;			
		}


		void pd_PrintPage(object sender, PrintPageEventArgs ev)
		{
			int charactersOnPage = 0;
			int linesPerPage = 0;

			ev.Graphics.MeasureString(stringToPrint, printFont,
				ev.MarginBounds.Size, StringFormat.GenericTypographic,
				out charactersOnPage, out linesPerPage);

			//MessageBox.Show(charactersOnPage.ToString() + " : " + linesPerPage.ToString());

			ev.Graphics.DrawString(stringToPrint, printFont, Brushes.Black,
				ev.MarginBounds, StringFormat.GenericTypographic);

			stringToPrint = stringToPrint.Substring(charactersOnPage);

			ev.HasMorePages = (stringToPrint.Length > 0);

			if (!ev.HasMorePages)
				stringToPrint = documentContents;
		}




	}
}



Thanks again!

This post has been edited by W.Carlisle: 06 March 2009 - 02:27 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Print Preview & Print in C#

#2 tody4me  Icon User is offline

  • Banned
  • member icon

Reputation: 12
  • View blog
  • Posts: 1,398
  • Joined: 12-April 06

Re: Print Preview & Print in C#

Posted 06 March 2009 - 02:46 PM

Please close the thread if the solution was found.

This post has been edited by tody4me: 06 March 2009 - 02:46 PM

Was This Post Helpful? 0

#3 p0rkjell0  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 06-March 09

Re: Print Preview & Print in C#

Posted 06 March 2009 - 05:47 PM

View Posttody4me, on 6 Mar, 2009 - 01:46 PM, said:

Please close the thread if the solution was found.


umm.. shouldn't that signature be...

 KYAgoodbye = ! theAnswer;


?
Was This Post Helpful? 0
  • +
  • -

#4 W.Carlisle  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 05-March 09

Re: Print Preview & Print in C#

Posted 09 March 2009 - 11:37 AM

View Posttody4me, on 6 Mar, 2009 - 01:46 PM, said:

Please close the thread if the solution was found.


Beginner questions no doubt, but:
1. What does closing a thread do and/or what is the purpose?
2. How does one go about closing a thread?
3. How does one verify that the thread has been closed?

Thank you.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1