private void printToolStripMenuItem_Click(object sender, EventArgs e) { m_nTotalPage = PageCountPrintController.GetPageCount(this.printDocument); m_nPage = 0; realPrint = true; printDocument.PrinterSettings.FromPage = 1; printDocument.PrinterSettings.ToPage = m_nTotalPage; printDocument.PrinterSettings.MinimumPage = 1; printDocument.PrinterSettings.MaximumPage = m_nTotalPage; if (printDialog.ShowDialog() == DialogResult.OK) { if (printDialog.PrinterSettings.PrintRange == PrintRange.SomePages) { m_nPage = printDocument.PrinterSettings.FromPage - 1; m_nMaxPage = printDocument.PrinterSettings.ToPage; } else { m_nPage = 0; m_nMaxPage = m_nTotalPage; } this.printDocument.Print(); } realPrint = false; }
// 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); }