Introduction
In this article I will explain how to print documents in
multiple pages in windows application using C#.
Background
To specify the output to print, use the Graphics
property of the PrintPageEventArgs
and PrintPage event handler of PrintDocument
. The Graphics
class provides methods
for drawing objects (graphics or text) to a device, such as a screen or
printer. This Graphics
Property calculates length, lines per page of a document.
For example, to specify a line of text that should be printed, draw the text
using the Graphics.DrawString
method.
Using the code
To print multiple pages , I have taken one button, one
printDocument
, one
printPreviewDialog
and one
printDialog
by drag and drop from toolbox.

Here 50
numbers will be printed in three pages. Among them first 20 number will be printed
in first page, next 20 in second one and rest of numbers will be printed in
last page.
The numbers will be printed one by one with some line
spacing in between them. After each page is drawn, check whether the count is 20
or not, if the count is more than 20 then set the HasMorePages
property of the PrintPageEventArgs
to true.
PaperSize paperSize = new PaperSize("papersize", 150, 500);
int totalnumber = 0;
int itemperpage= 0;
private void btnprintpreview_Click(object sender, EventArgs e)
{
itemperpage = totalnumber = 0;
printPreviewDialog1.Document = printDocument1;
((ToolStripButton)((ToolStrip)printPreviewDialog1.Controls[1]).Items[0]).Enabled
= false;
printDocument1.DefaultPageSettings.PaperSize = paperSize;
printPreviewDialog1.ShowDialog();
}
private void bnprint_Click(object sender, EventArgs e)
{
itemperpage = totalnumber = 0;
printDialog1.Document =printDocument1;
printDocument1.DefaultPageSettings.PaperSize = paperSize;
printDialog1.ShowDialog();
}
private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
float currentY = 10;
e.Graphics.DrawString("Print in Multiple Pages", DefaultFont, Brushes.Black, 10, currentY);
currentY += 15;
while(totalnumber <= 50)
{
e.Graphics.DrawString(totalnumber.ToString(),DefaultFont, Brushes.Black, 50,currentY);
currentY += 20;
totalnumber += 1;
if(itemperpage < 20)
{
itemperpage += 1;
e.HasMorePages = false;
}
else
{
itemperpage = 0;
e.HasMorePages = true;
return;
}
}
}
The out put will be like this
Points of Interest
The main logic behind the trick is that you need to work out how much space you have on the page and ensure that you must track item collection and page height.