473,287 Members | 1,413 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,287 software developers and data experts.

Printing Text in C#.NET with PageSelection Option and Preview Option

Hi,
First of all let me confess that I could not get the solution to the same problem from an earlier post Printing :by Mr.Richard MSL (dated September 24th 2006) working.
(Replied by Mr.Walter Wang - September 27th 2006)

My problem is to Print a text from a RichTextBox with all options like - AllowMultiplePages enabled plus PrintPreview and PageSetup.

I tried 2 algorithms - 1 posted in Microsoft and 1 posted in this forum.

Everything works brilliantly when i extend the RichTextBox as specified in :
http://support.microsoft.com/kb/812425/
(How to print the content of a RichTextBox control by using Visual C# .NET or Visual C# 2005). In this case it is difficult to provide options while printing.

In the post that i found here, I have copy pasted the same below, I am unable to print it correctly with print preview. If i can get any of the 2 algorithms working then that solves my problem.

For the post the follows below - if i can get the working project then it would be very helpful. Also please tell me how and where to download the attachment as i am new to this.
My deadline is today as i am working on this from 2 days. Thanks in advance

.
Richard MSL
Guest
n/a Posts
September 27th, 2006
04:05 PM
#4

Re: Printing
Thanks Walter, that is very helpful, just what I was looking for. Thanks.


"Walter Wang [MSFT]" wrote:
Quote:
Originally Posted by
Hi,
>
In WinForm's printing architecture, it's the user's responsibility to do
the pagination:
>
1) System fires the event PrintPage
2) User process the event, prints content to the Graphics object; at the
end of the event, user need to set the flag PrintPageEventArgs.HasMorePages
to notify the system whether or not there're remaining pages.
3) System checks the flag, if it's True, go to step 1).
>
If user wants to print some pages, the settings are returned in the
PrinterSettings.PrintRange, FromPage, ToPage, etc. But they have nothing to
do with how the PrintPage event is raised and handled. That's why you need
to save the FromPage and ToPage as member variables and use them in the
event later.
>
From your code, I assume what you're doing is to print a multi-page text
file like following example:
>
[1] How to: Print a Multi-Page Text File in Windows Forms
http://msdn2.microsoft.com/en-us/library/cwbe712d.aspx
>
However, the example above doesn't allow user selectively print some pages
using AllowSomePages property.
>
Let's implement this feature now.
>
First, to let user know exactly the total pages count, we need to create a
custom PrintController which computes the page count dynamically.
>
class PageCountPrintController : PreviewPrintController
{
int pageCount = 0;
>
public override void OnStartPrint(PrintDocument document,
PrintEventArgs e)
{
base.OnStartPrint(document, e);
this.pageCount = 0;
}
>
public override System.Drawing.Graphics OnStartPage(PrintDocument
document, PrintPageEventArgs e)
{
// Increment page count
++this.pageCount;
return base.OnStartPage(document, e);
}
>
public int PageCount
{
get { return this.pageCount; }
}
>
// Helper method to simplify client code
public static int GetPageCount(PrintDocument document)
{
// Must have a print document to generate page count
if (document == null)
throw new ArgumentNullException("PrintDocument must be
set.");
>
// Substitute this PrintController to cause a Print to initiate
the
// count, which means that OnStartPrint and OnStartPage are
called
// as the PrintDocument prints
PrintController existingController = document.PrintController;
PageCountPrintController controller = new
PageCountPrintController();
document.PrintController = controller;
document.Print();
document.PrintController = existingController;
return controller.PageCount;
}
}
>
Also, we can use this "pre-processing" phase to get which text should be
printed on which page.
>
void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
>
if (_isPreProcessing)
{
int charactersOnPage = 0;
int linesPerPage = 0;
// Sets the value of charactersOnPage to the number of
characters
// of stringToPrint that will fit within the bounds of the page.
e.Graphics.MeasureString(_stringToPrint, this.Font,
e.MarginBounds.Size, StringFormat.GenericTypographic,
out charactersOnPage, out linesPerPage);
>
// Save the text for the page
_pages.Add(_stringToPrint.Substring(0, charactersOnPage));
// Remove the portion of the string that has been printed.
_stringToPrint = _stringToPrint.Substring(charactersOnPage);
>
// Check to see if more pages are to be printed.
e.HasMorePages = (_stringToPrint.Length 0);
if (!e.HasMorePages) _stringToPrint = null;
}
else
{
// Draws the string within the bounds of the page
e.Graphics.DrawString(_pages[_pageNumber-1], this.Font,
Brushes.Black,
e.MarginBounds, StringFormat.GenericTypographic);
_pageNumber++;
e.HasMorePages = _pageNumber <= _maxPageNumber;
if (!e.HasMorePages) _pages = null;
}
}
>
private void button1_Click(object sender, EventArgs e)
{
ReadFile();
>
// Get the total page count
_isPreProcessing = true;
_pages = new List<string>();
_totalPages =
PageCountPrintController.GetPageCount(_printDocume nt1);
_isPreProcessing = false;
>
_printDocument1.PrinterSettings.FromPage = 1;
_printDocument1.PrinterSettings.ToPage = _totalPages;
_printDocument1.PrinterSettings.MinimumPage = 1;
_printDocument1.PrinterSettings.MaximumPage = _totalPages;
PrintDialog pd = new PrintDialog();
pd.AllowSomePages = true;
pd.Document = _printDocument1;
if (pd.ShowDialog() == DialogResult.OK)
{
if (pd.PrinterSettings.PrintRange == PrintRange.SomePages)
{
_pageNumber = _printDocument1.PrinterSettings.FromPage;
_maxPageNumber = _printDocument1.PrinterSettings.ToPage;
}
else
{
_pageNumber = 1;
_maxPageNumber = _totalPages;
}
_printDocument1.Print();
}
}
>
>
I've created a complete working project for you to test it. It will print
"c:\testpage.txt". You can use the "Page Setup..." button to change the
margins and you will notice the total page count changes accordingly when
you click "Print..." to bring up the print dialog.
>
Note: you will have to use Outlook Express to download the attachment
Jun 22 '07 #1
2 8276
kenobewan
4,871 Expert 4TB
What attachment do you want to download?
Jun 22 '07 #2
What attachment do you want to download?

In the earlier post I read this -

I've created a complete working project for you to test it. It will print
"c:\testpage.txt". You can use the "Page Setup..." button to change the
margins and you will notice the total page count changes accordingly when
you click "Print..." to bring up the print dialog.
>
Note: you will have to use Outlook Express to download the attachment

I need the project specified here. Thanks again!
Jun 23 '07 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

16
by: gb | last post by:
Hi All, Ive created a popup page using 'var openWindow = window.open("new","pop")' And added content using openWindow.document.write(" "); statements. But now I would like to be able to print...
5
by: Mr. B | last post by:
This is driving me NUTZ!!! I've been screwing around on this for a week now. And I have tried to find examples similar to what I have (nada). Got lots of streaming a TXT file... bah! I am...
4
by: Suzanka | last post by:
Hello, I have an application written in C# on visual studio .NET. It is a web aplication. The application consists of many different forms, that users occassionaly want to print out for filing....
4
by: Al Jones | last post by:
Well, hopefully that title get someones attention. In this old gwbasic program I've converted I *have* sucessuflly converted it to print to a file and the output is acceptable. From there I have...
1
by: hamil | last post by:
I am trying to print a graphic file (tif) and also use the PrintPreview control, the PageSetup control, and the Print dialog control. The code attached is a concatination of two examples taken out...
6
by: Siv | last post by:
Hi, I am getting into printing with VB.NET 2005 and want to implement the usual capability that a user can select a selection of pages. I have a report that is generated by my application that if...
2
by: Brad Pears | last post by:
I have some sample code that uses the print dialog, print preview and a print direct options. If I select print preview and then click the printer icon from that, the document prints. If I...
8
by: Neo Geshel | last post by:
Greetings. BACKGROUND: My sites are pure XHTML 1.1 with CSS 2.1 for markup. My pages are delivered as application/xhtml+xml for all non-MS web clients, and as text/xml for all MS web...
0
by: Peter Duniho | last post by:
On Wed, 23 Apr 2008 09:40:14 -0700, Al Meadows <fineware@fineware.com> wrote: This doesn't really seem to be a .NET or C# question. However, you may want to look at the driver settings...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: MeoLessi9 | last post by:
I have VirtualBox installed on Windows 11 and now I would like to install Kali on a virtual machine. However, on the official website, I see two options: "Installer images" and "Virtual machines"....
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: marcoviolo | last post by:
Dear all, I would like to implement on my worksheet an vlookup dynamic , that consider a change of pivot excel via win32com, from an external excel (without open it) and save the new file into a...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...

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.