473,382 Members | 1,437 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,382 software developers and data experts.

Printing

I have an application that prints documents that it creates. It uses what I
believe is a standard .NET way of doing so, like this:

PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler
(this.pd_PrintPage);
PrintDialog PrintDialog1 = new PrintDialog();
PrintDialog1.Document = pd;

DialogResult result = PrintDialog1.ShowDialog();
if (result == DialogResult.OK)
{
this.streamToPrint = new StreamReader(FileName);
pd.Print();
this.streamToPrint.Close();
}

I have written a pd_PrintPage method that does the actual graphics commands
to print each page. This all works fine.

Where I have encountered a problem is in implementing selective page
printing. I have been able to activate the page range in the dialog like this:

PrintDialog1.PrinterSettings.FromPage=1;
PrintDialog1.PrinterSettings.ToPage=100;
PrintDialog1.AllowSomePages=true;

I had hoped that this was all I needed to do, since the printing routine
clearly knows what page it is printing as it displays the page number while
doing so, and generally pages the document properly. But it always prints all
the pages regardless of what the users selects. I have this in my page print
method, which allows me to determine whether this page should be printed or
not:

PrinterSettings PrSe=ev.PageSettings.PrinterSettings;
if(PrSe.PrintRange==PrintRange.SomePages&&
(PrSe.FromPage>PageNumber||PrSe.ToPage<PageNumber) )
// do not print this page.

But I can not figure out a way to tell Windows not to print the page. If I
simply do not execute the contents of the print page routine, I still get a
blank page. How do I not print the page entirely? Alternatively, is there an
example somewhere of using the AllowSomePages and FromPage and ToPage
members? Thanks.

Sep 24 '06 #1
3 4543
Hi Richard,

In the event of PrintPage, a blank page is already created for you. Please
use following code to test this AllowSomePages feature:

Create a simple WinForm application, add a Button to the default Form,
handle its Click event:

const int TOTAL_PAGES = 10;
int _pageNumber;
int _maxPageNumber;

private void button1_Click(object sender, EventArgs e)
{
PrintDocument _doc = new PrintDocument();
_doc.PrintPage += new PrintPageEventHandler(_doc_PrintPage);
_doc.PrinterSettings.FromPage = 1;
_doc.PrinterSettings.ToPage = TOTAL_PAGES;
_doc.PrinterSettings.MinimumPage = 1;
_doc.PrinterSettings.MaximumPage = TOTAL_PAGES;
PrintDialog pd = new PrintDialog();
pd.AllowSomePages = true;
pd.Document = _doc;
if (pd.ShowDialog() == DialogResult.OK)
{
if (pd.PrinterSettings.PrintRange == PrintRange.SomePages)
{
_pageNumber = _doc.PrinterSettings.FromPage;
_maxPageNumber = _doc.PrinterSettings.ToPage;
}
else
{
_pageNumber = 1;
_maxPageNumber = TOTAL_PAGES;
}
_doc.Print();
}
}

void _doc_PrintPage(object sender, PrintPageEventArgs e)
{
e.Graphics.DrawString("Page " + _pageNumber.ToString(), new
Font("Verdana", 35), Brushes.Black, new Point(10, 10));
_pageNumber++;
e.HasMorePages = _pageNumber <= _maxPageNumber;
}

Please let me know whether or not this works for you.

Sincerely,
Walter Wang (wa****@online.microsoft.com, remove 'online.')
Microsoft Online Community Support

==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications. If you are using Outlook Express, please make sure you clear the
check box "Tools/Options/Read: Get 300 headers at a time" to see your reply
promptly.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.

Sep 25 '06 #2
Thank you for your response. With your solution, if I ask for pages 3-5, I
will indeed get pages numbered 3, 4 and 5. The problem is that I am printing
actual content, and I need the content from page 3, but not the content from
1 or 2. What I do not understand is how I can tell the print page command to
start at page 3. My print page routine contains this:

private void pd_PrintPage(object sender, PrintPageEventArgs ev)
{

while (count < linesPerPage &&
((line = streamToPrint.ReadLine()) != null))
{
ev.Graphics.DrawString(line, printFont, Brushes.Black,
leftMargin, yPos, new StringFormat());
}

I need a way to tell it to get the stream content for the third page, not
the first page. I could attempt to figure out where the page breaks are and
read through the whole stream to get there, but it seemed to me that since
Windows knows what is on what page, there had to be a better way? Thanks.
"Walter Wang [MSFT]" wrote:
Hi Richard,

In the event of PrintPage, a blank page is already created for you. Please
use following code to test this AllowSomePages feature:

Create a simple WinForm application, add a Button to the default Form,
handle its Click event:

const int TOTAL_PAGES = 10;
int _pageNumber;
int _maxPageNumber;

private void button1_Click(object sender, EventArgs e)
{
PrintDocument _doc = new PrintDocument();
_doc.PrintPage += new PrintPageEventHandler(_doc_PrintPage);
_doc.PrinterSettings.FromPage = 1;
_doc.PrinterSettings.ToPage = TOTAL_PAGES;
_doc.PrinterSettings.MinimumPage = 1;
_doc.PrinterSettings.MaximumPage = TOTAL_PAGES;
PrintDialog pd = new PrintDialog();
pd.AllowSomePages = true;
pd.Document = _doc;
if (pd.ShowDialog() == DialogResult.OK)
{
if (pd.PrinterSettings.PrintRange == PrintRange.SomePages)
{
_pageNumber = _doc.PrinterSettings.FromPage;
_maxPageNumber = _doc.PrinterSettings.ToPage;
}
else
{
_pageNumber = 1;
_maxPageNumber = TOTAL_PAGES;
}
_doc.Print();
}
}

void _doc_PrintPage(object sender, PrintPageEventArgs e)
{
e.Graphics.DrawString("Page " + _pageNumber.ToString(), new
Font("Verdana", 35), Brushes.Black, new Point(10, 10));
_pageNumber++;
e.HasMorePages = _pageNumber <= _maxPageNumber;
}

Please let me know whether or not this works for you.

Sincerely,
Walter Wang (wa****@online.microsoft.com, remove 'online.')
Microsoft Online Community Support

==================================================
Get notification to my posts through email? Please refer to
http://msdn.microsoft.com/subscripti...ult.aspx#notif
ications. If you are using Outlook Express, please make sure you clear the
check box "Tools/Options/Read: Get 300 headers at a time" to see your reply
promptly.

Note: The MSDN Managed Newsgroup support offering is for non-urgent issues
where an initial response from the community or a Microsoft Support
Engineer within 1 business day is acceptable. Please note that each follow
up response may take approximately 2 business days as the support
professional working with you may need further investigation to reach the
most efficient resolution. The offering is not appropriate for situations
that require urgent, real-time or phone-based interactions or complex
project analysis and dump analysis issues. Issues of this nature are best
handled working with a dedicated Microsoft Support Engineer by contacting
Microsoft Customer Support Services (CSS) at
http://msdn.microsoft.com/subscripti...t/default.aspx.
==================================================

This posting is provided "AS IS" with no warranties, and confers no rights.

Sep 25 '06 #3
Thanks Walter, that is very helpful, just what I was looking for. Thanks.
"Walter Wang [MSFT]" wrote:
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
Sep 27 '06 #4

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

Similar topics

4
by: Jody Gelowitz | last post by:
I am having a problem with printing selected pages. Actually, the problem isn't with printing selected pages as it is more to do with having blank pages print for those pages that have not been...
0
by: Programatix | last post by:
Hi, I am working on the PrintDocument, PrintDialog, PageSetupDialog and PrintPreviewControl components of Visual Studio .NET 2003. My developement machine is running Windows XP. There are...
9
by: Jody Gelowitz | last post by:
I am trying to find the definition of "Safe Printing" and cannot find out exactly what this entitles. The reason is that I am trying to print contents from a single textbox to no avail using the...
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: Arif | last post by:
I C# code prints very slow as compared to a third party barcode printing software. That software prints approximately 10 labels in 2 seconds while my C# code prints 10 labels in 5 to 6 seconds. And...
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...
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: nikhilgargi | last post by:
Requirement: I need to provide printing capability in a C# desktop application that I am developing The documents that need to be printed can be in Rich Text Format (RTF) or HTML. Custom...
18
by: Brett | last post by:
I have an ASP.NET page that displays work orders in a GridView. In that GridView is a checkbox column. When the user clicks a "Print" button, I create a report, using the .NET Framework printing...
0
it0ny
by: it0ny | last post by:
Hi guys, thanks I am fairly new to this forum so I hope I chose the right place to post this question. I try to make my program printout a deposit's report. I created a class to store the...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.