Print and provide print previews with more advanced features in C#

The example Print and provide print previews in C# shows how to create a basic printout by handling the PrintDocument object's PrintPage event. This example shows how to use two other PrintDocument event handlers: BeginPrint and QueryPageSettings.

BeginPrint

BeginPrint fires just before a printout starts. You can use it to prepare for the printout, opening files, connecting to databases, or whatever.

This example uses BeginPrint to initialize the class-level variables m_NextPage to tell the program to start printing with the first page. The previous example reset this variable to 0 after it printed the last page so it would be ready for the next printout. This version is a bit more intuitive because it sets m_NextPage = 0 before printing instead of afterward.

// Get ready to print.
private void pdocShapes_BeginPrint(object sender, System.Drawing.Printing.PrintEventArgs e)
{
// Start with page 0.
m_NextPage = 0;
}

QueryPageSettings

QueryPageSettings fires just before each page is generated. You can use this event to prepare to print the next page. In particular, you can set the page's margins.

This example, assumes you are printing a booklet and adds a gutter to each page. A gutter is an extra bit of space next to the margin to allow for the booklet's staples or stitching for a book's binding. This example adds a gutter to the left of even-numbered pages and to the right of odd-numbered pages (remember, numbering starts with 0).

// Prepare to print the next page.
private void pdocShapes_QueryPageSettings(object sender, System.Drawing.Printing.QueryPageSettingsEventArgs e)
{
const int GUTTER = 100;
// Even numbered pages have a big margin on the left.
if (m_NextPage == 0)
{
// The first page. Increase the left margin.
e.PageSettings.Margins.Left += GUTTER;
}
else if (m_NextPage % 2 == 0)
{
// An even page. Increase the left margin
// and decrease the right margin.
e.PageSettings.Margins.Left += GUTTER;
e.PageSettings.Margins.Right -= GUTTER;
}
else
{
// An odd page. Decrease the left margin
// and increase the right margin.
e.PageSettings.Margins.Left -= GUTTER;
e.PageSettings.Margins.Right += GUTTER;
}
}

The PrintDocument fires one other event: EndPrint. This event fires when the printout is complete. You should use it to perform any necessary clean up. For example, you can use EndPrint to disconnect a database or close a file that you opened to make the printout.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments
  • No comments exist for this post.
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.