Csharp/C Sharp/GUI Windows Form/Print
Версия от 15:31, 26 мая 2010; (обсуждение)
Содержание
Basic Printing
/*
Professional Windows GUI Programming Using C#
by Jay Glynn, Csaba Torok, Richard Conway, Wahid Choudhury,
Zach Greenvoss, Shripad Kulkarni, Neil Whitlow
Publisher: Peer Information
ISBN: 1861007663
*/
using System;
using System.Drawing.Printing;
using System.Drawing;
namespace BasicPrinting
{
public class PrintSample
{
[STAThread]
static void Main(string[] args)
{
PrintSample oSample = new PrintSample();
oSample.RunSample();
}
public void RunSample()
{
Console.WriteLine("Printing to the default printer...");
try
{
PrintDocument pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(this.PrintPageEvent);
pd.Print();
}
catch(Exception ex)
{
Console.WriteLine("Error printing -- " + ex.ToString());
}
//Read input - to delay the closing of the DOS shell
Console.ReadLine();
}
//Event fired for each page to print
private void PrintPageEvent(object sender, PrintPageEventArgs ev)
{
string strHello = "Hello Printer!";
Font oFont = new Font("Arial",10);
Rectangle marginRect = ev.MarginBounds;
ev.Graphics.DrawRectangle(new Pen(System.Drawing.Color.Black),marginRect);
ev.Graphics.DrawString(strHello,oFont,new SolidBrush(System.Drawing.Color.Blue),
(ev.PageBounds.Right/2), ev.PageBounds.Bottom/2);
}
}
}
Begin Print
/*
GDI+ Programming in C# and VB .NET
by Nick Symmonds
Publisher: Apress
ISBN: 159059035X
*/
using System;
using System.Drawing;
using System.IO;
using System.Drawing.Printing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
namespace BeginPrint_c
{
/// <summary>
/// Summary description for BeginPrint.
/// </summary>
public class BeginPrint1 : System.Windows.Forms.Form
{
#region Class Local Storage
PrintDocument Pd;
Font Pf;
TextReader file;
int Pages = 0;
#endregion
private System.Windows.Forms.ruboBox cmbPrinters;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button cmdStartPrint;
private System.Windows.Forms.ListBox lstPaper;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.ListBox lstRes;
private System.ruponentModel.Container components = null;
public BeginPrint1()
{
InitializeComponent();
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.cmbPrinters = new System.Windows.Forms.ruboBox();
this.label1 = new System.Windows.Forms.Label();
this.cmdStartPrint = new System.Windows.Forms.Button();
this.lstPaper = new System.Windows.Forms.ListBox();
this.label2 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.lstRes = new System.Windows.Forms.ListBox();
this.SuspendLayout();
//
// cmbPrinters
//
this.cmbPrinters.DropDownStyle = System.Windows.Forms.ruboBoxStyle.DropDownList;
this.cmbPrinters.Location = new System.Drawing.Point(16, 192);
this.cmbPrinters.Name = "cmbPrinters";
this.cmbPrinters.Size = new System.Drawing.Size(256, 21);
this.cmbPrinters.TabIndex = 0;
//
// label1
//
this.label1.Location = new System.Drawing.Point(16, 176);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(256, 16);
this.label1.TabIndex = 1;
this.label1.Text = "Installed Printers";
//
// cmdStartPrint
//
this.cmdStartPrint.Location = new System.Drawing.Point(88, 224);
this.cmdStartPrint.Name = "cmdStartPrint";
this.cmdStartPrint.Size = new System.Drawing.Size(88, 32);
this.cmdStartPrint.TabIndex = 2;
this.cmdStartPrint.Text = "Start Print";
this.cmdStartPrint.Click += new System.EventHandler(this.cmdStartPrint_Click);
//
// lstPaper
//
this.lstPaper.Location = new System.Drawing.Point(16, 24);
this.lstPaper.Name = "lstPaper";
this.lstPaper.Size = new System.Drawing.Size(256, 56);
this.lstPaper.TabIndex = 3;
//
// label2
//
this.label2.Location = new System.Drawing.Point(18, 8);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(256, 16);
this.label2.TabIndex = 4;
this.label2.Text = "Paper Size";
//
// label3
//
this.label3.Location = new System.Drawing.Point(16, 88);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(256, 16);
this.label3.TabIndex = 6;
this.label3.Text = "Printer Resolution";
//
// lstRes
//
this.lstRes.Location = new System.Drawing.Point(16, 104);
this.lstRes.Name = "lstRes";
this.lstRes.Size = new System.Drawing.Size(256, 56);
this.lstRes.TabIndex = 5;
//
// BeginPrint
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 273);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.label3,
this.lstRes,
this.label2,
this.lstPaper,
this.cmdStartPrint,
this.label1,
this.cmbPrinters});
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "BeginPrint";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "BeginPrint";
this.Load += new System.EventHandler(this.BeginPrint_Load);
this.ResumeLayout(false);
}
#endregion
[STAThread]
static void Main()
{
Application.Run(new BeginPrint1());
}
private void BeginPrint_Load(object sender, System.EventArgs e)
{
Init();
}
private void Init()
{
foreach(String p in PrinterSettings.InstalledPrinters)
cmbPrinters.Items.Add(p);
if ( cmbPrinters.Items.Count > 0 )
cmbPrinters.SelectedIndex = 0;
//Add a few paper sizes to the list box
lstPaper.Items.Add(PaperKind.A4.ToString());
lstPaper.Items.Add(PaperKind.Letter.ToString());
lstPaper.Items.Add(PaperKind.CSheet.ToString());
//Add all the printer resolutions to the list box
lstRes.Items.Add(PrinterResolutionKind.Custom.ToString());
lstRes.Items.Add(PrinterResolutionKind.Draft.ToString());
lstRes.Items.Add(PrinterResolutionKind.High.ToString());
lstRes.Items.Add(PrinterResolutionKind.Low.ToString());
lstRes.Items.Add(PrinterResolutionKind.Medium.ToString());
}
private void cmdStartPrint_Click(object sender, System.EventArgs e)
{
try
{
file = new StreamReader("Test.txt");
try
{
//Create the document and give it a somewhat unique name
Pd = new PrintDocument();
Pd.DocumentName = DateTime.Now.Millisecond.ToString();
//Install event handlers
Pd.BeginPrint += new PrintEventHandler(this.BeginPrint);
Pd.PrintPage += new PrintPageEventHandler(this.PagePrint);
Pd.EndPrint += new PrintEventHandler(this.EndPrint);
// Print the document.
Pd.Print();
}
finally
{
file.Close();
if (Pd != null)
Pd.Dispose();
if (Pf != null)
Pf.Dispose();
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void BeginPrint1(object sender, PrintEventArgs ev)
{
PageSettings Psettings = Pd.DefaultPageSettings;
//Initialize the font
Pf = new Font("Times New Roman", 10);
Pd.PrinterSettings.PrinterName = cmbPrinters.SelectedItem.ToString();
foreach (PaperSize ps in Pd.PrinterSettings.PaperSizes)
{
if (ps.PaperName == lstPaper.SelectedItem.ToString())
{
Psettings.PaperSize = ps;
break;
}
}
foreach (PrinterResolution pr in Pd.PrinterSettings.PrinterResolutions)
{
if (pr.Kind.ToString() == lstRes.SelectedItem.ToString())
{
Psettings.PrinterResolution = pr;
break;
}
}
//Make 1/4 inch margins all around
Psettings.Margins = new Margins(25, 25, 25, 25);
Pd.DefaultPageSettings = Psettings;
//Reset the pages
Pages = 0;
}
private void EndPrint(object sender, PrintEventArgs ev)
{
Pf.Dispose();
}
// The PrintPage event is raised for each page to be printed.
private void PagePrint(object sender, PrintPageEventArgs ev)
{
float linesPerPage = 0;
float yPos = 0;
int count = 0;
float leftMargin = ev.MarginBounds.Left;
float topMargin = ev.MarginBounds.Top;
String line = null;
//Keep track of pages as they are printed
if (++Pages == 2)
{
try
{
ev.PageSettings.Landscape = true;
}
catch (Exception ex)
{
ev.PageSettings.Landscape = false;
}
}
else
ev.PageSettings.Landscape = false;
// Calculate the number of lines per page.
linesPerPage = ev.MarginBounds.Height / Pf.GetHeight(ev.Graphics);
// Iterate over the file, printing each line. Use a basic StringFormat
while (count++ < linesPerPage && ((line=file.ReadLine()) != null))
{
yPos = topMargin + (count * Pf.GetHeight(ev.Graphics));
ev.Graphics.DrawString (line, Pf, Brushes.Black,
leftMargin, yPos, new StringFormat());
}
// If more lines exist, print another page.
if (line != null)
ev.HasMorePages = true;
else
ev.HasMorePages = false;
}
}
}
Control Print
/*
Code revised from chapter 7
GDI+ Custom Controls with Visual C# 2005
By Iulian Serban, Dragos Brezoi, Tiberiu Radu, Adam Ward
Language English
Paperback 272 pages [191mm x 235mm]
Release date July 2006
ISBN 1904811604
Sample chapter
http://www.packtpub.ru/files/1604_CustomControls_SampleChapter.pdf
For More info on GDI+ Custom Control with Microsoft Visual C# book
visit website www.packtpub.ru
*/
using System;
using System.Collections.Generic;
using System.ruponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;
namespace PrintingCustomControlApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
printableRichTextBox1.Print(false);
}
private System.ruponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.printableRichTextBox1 = new PrintingCustomControlApp1.PrintableRichTextBox();
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// printableRichTextBox1
//
this.printableRichTextBox1.Location = new System.Drawing.Point(77, 25);
this.printableRichTextBox1.Name = "printableRichTextBox1";
this.printableRichTextBox1.Size = new System.Drawing.Size(124, 117);
this.printableRichTextBox1.TabIndex = 0;
this.printableRichTextBox1.Text = "";
//
// button1
//
this.button1.Location = new System.Drawing.Point(63, 191);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(126, 30);
this.button1.TabIndex = 1;
this.button1.Text = "Print the Control text";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(292, 266);
this.Controls.Add(this.button1);
this.Controls.Add(this.printableRichTextBox1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
private PrintableRichTextBox printableRichTextBox1;
private System.Windows.Forms.Button button1;
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
public partial class PrintableRichTextBox : RichTextBox
{
public PrintableRichTextBox()
{
InitializeComponent();
_prtdoc = new PrintDocument();
_prtdoc.PrintPage += new PrintPageEventHandler(_prtdoc_PrintPage);
}
string _text = null;
int _pageNumber = 0;
int _start = 0;
PrintDocument _prtdoc = null;
private bool DrawText(Graphics target, Graphics measurer, RectangleF r, Brush brsh)
{
if (r.Height < this.Font.Height)
throw new ArgumentException("The rectangle is not tall enough to fit a single line of text inside.");
int charsFit = 0;
int linesFit = 0;
int cut = 0;
string temp = _text.Substring(_start);
StringFormat format = new StringFormat(StringFormatFlags.FitBlackBox | StringFormatFlags.LineLimit);
//measure how much of the string we can fit into the rectangle
measurer.MeasureString(temp, this.Font, r.Size, format, out charsFit, out linesFit);
cut = BreakText(temp, charsFit);
if (cut != charsFit)
temp = temp.Substring(0, cut);
bool h = true;
h &= true;
target.DrawString(temp.Trim(" "), this.Font, brsh, r, format);
_start += cut;
if (_start == _text.Length)
{
_start = 0; //reset the location so we can repeat the document
return true; //finished printing
}
else
return false;
}
private static int BreakText(string text, int approx)
{
if (approx == 0)
throw new ArgumentException();
if (approx < text.Length)
{
//are we in the middle of a word?
if (char.IsLetterOrDigit(text[approx]) && char.IsLetterOrDigit(text[approx - 1]))
{
int temp = text.LastIndexOf(" ", approx, approx + 1);
if (temp >= 0)
return temp;
}
}
return approx;
}
public void Print(bool hardcopy)
{
_text = this.Text;
//create a PrintDialog based on the PrintDocument
PrintDialog pdlg = new PrintDialog();
pdlg.Document = _prtdoc;
//show the PrintDialog
if (pdlg.ShowDialog() == DialogResult.OK)
{
//create a PageSetupDialog based on the PrintDocument and PrintDialog
PageSetupDialog psd = new PageSetupDialog();
psd.EnableMetric = true; //Ensure all dialog measurements are in metric
psd.Document = pdlg.Document;
//show the PageSetupDialog
if (psd.ShowDialog() == DialogResult.OK)
{
//apply the settings of both dialogs
_prtdoc.DefaultPageSettings = psd.PageSettings;
//decide what action to take
if (hardcopy)
{
//actually print hardcopy
_prtdoc.Print();
}
else
{
//preview onscreen instead
PrintPreviewDialog prvw = new PrintPreviewDialog();
prvw.Document = _prtdoc;
prvw.ShowDialog();
}
}
}
}
private void _prtdoc_PrintPage(object sender, PrintPageEventArgs e)
{
e.Graphics.Clip = new Region(e.MarginBounds);
//this method does all our printing work
Single x = e.MarginBounds.Left;
Single y = e.MarginBounds.Top;
if (_pageNumber++ == 0)
y += 30;
RectangleF mainTextArea = RectangleF.FromLTRB(x, y, e.MarginBounds.Right, e.MarginBounds.Bottom);
//draw the text
if (DrawText(e.Graphics, e.PageSettings.PrinterSettings.CreateMeasurementGraphics(), mainTextArea, Brushes.Black))
{
e.HasMorePages = false; //the end has been reached
_pageNumber = 0;
}
else
e.HasMorePages = true;
}
private System.ruponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
components = new System.ruponentModel.Container();
//this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
}
#endregion
}
}
Define Print Settings
/*
GDI+ Programming in C# and VB .NET
by Nick Symmonds
Publisher: Apress
ISBN: 159059035X
*/
using System;
using System.Drawing.Printing;
namespace DefPrintSettings_c
{
public class DefPrintSettings
{
[STAThread]
static void Main(string[] args)
{
PrintDocument pd = new PrintDocument();
PageSettings pg = pd.DefaultPageSettings;
PrinterSettings ps = pg.PrinterSettings;
Console.WriteLine("Printer Settings");
Console.WriteLine("PrinterName = " + pd.PrinterSettings.PrinterName);
Console.WriteLine("Is default Printer = " +
ps.IsDefaultPrinter.ToString());
Console.WriteLine("Is plotter = " + ps.IsPlotter.ToString());
Console.WriteLine("Is printer valid = " + ps.IsValid.ToString());
Console.WriteLine("Can Duplex = " + ps.IsValid.ToString());
Console.WriteLine("Num copies = " + ps.Copies.ToString());
Console.WriteLine("Max Copies = " + ps.MaximumCopies.ToString());
Console.WriteLine("Max Page = " + ps.MaximumPage.ToString());
Console.WriteLine("Min Page = " + ps.MinimumPage.ToString());
Console.WriteLine("Supports Color = " + ps.SupportsColor.ToString());
foreach (PaperSize p in ps.PaperSizes)
Console.WriteLine("Supports Paper Size: " + p.PaperName);
foreach (PaperSource p in ps.PaperSources)
Console.WriteLine("Supports Paper Source: " + p.SourceName);
Console.WriteLine("\nPage Settings");
Console.WriteLine("Is Color = " + pg.Color.ToString());
Console.WriteLine("Top Bound = " + pg.Bounds.Top.ToString());
Console.WriteLine("Bottom Bound = " + pg.Bounds.Bottom.ToString());
Console.WriteLine("Left Bound = " + pg.Bounds.Left.ToString());
Console.WriteLine("Right Bound = " + pg.Bounds.Right.ToString());
Console.WriteLine("Top Margin = " + pg.Margins.Top.ToString());
Console.WriteLine("Bottom Margin = " + pg.Margins.Bottom.ToString());
Console.WriteLine("Left Margin = " + pg.Margins.Left.ToString());
Console.WriteLine("Right Margin = " + pg.Margins.Right.ToString());
Console.WriteLine("Landscape = " + pg.Landscape.ToString());
Console.WriteLine("PaperSize = " + pg.PaperSize.PaperName);
Console.WriteLine("PaperSource = " + pg.PaperSource.SourceName);
Console.WriteLine("PrinterResolution = " +
pg.PrinterResolution.Kind.ToString());
Console.WriteLine("PrinterResolution X = " +
pg.PrinterResolution.X.ToString());
Console.WriteLine("PrinterResolution Y = " +
pg.PrinterResolution.Y.ToString());
Console.ReadLine();
}
}
}
Grid Printing
/*
Professional Windows GUI Programming Using C#
by Jay Glynn, Csaba Torok, Richard Conway, Wahid Choudhury,
Zach Greenvoss, Shripad Kulkarni, Neil Whitlow
Publisher: Peer Information
ISBN: 1861007663
*/
using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
using System.Drawing.Printing;
namespace GridPrinting
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class GridPrintingDemo : System.Windows.Forms.Form
{
//Stored Page Settings object
private PageSettings oPageSettings;
private System.Windows.Forms.MenuItem menuItem1;
private System.Windows.Forms.MenuItem menuItem2;
private System.ruponentModel.Container components = null;
private System.Windows.Forms.MainMenu mnuMain;
private System.Windows.Forms.PrintPreviewDialog ppDialog;
private System.Windows.Forms.MenuItem menuItem3;
private System.Windows.Forms.MenuItem menuItem4;
private System.Windows.Forms.PrintDialog oPrintDialog;
private System.Windows.Forms.MenuItem menuItem5;
private System.Windows.Forms.MenuItem menuItem6;
private System.Windows.Forms.PageSetupDialog oPageSetup;
private System.Windows.Forms.DataGrid dGrid;
public GridPrintingDemo()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
oPageSettings = new PageSettings();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
// System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(GridPrintingDemo));
this.dGrid = new System.Windows.Forms.DataGrid();
this.mnuMain = new System.Windows.Forms.MainMenu();
this.menuItem1 = new System.Windows.Forms.MenuItem();
this.menuItem3 = new System.Windows.Forms.MenuItem();
this.menuItem4 = new System.Windows.Forms.MenuItem();
this.menuItem2 = new System.Windows.Forms.MenuItem();
this.menuItem5 = new System.Windows.Forms.MenuItem();
this.menuItem6 = new System.Windows.Forms.MenuItem();
this.ppDialog = new System.Windows.Forms.PrintPreviewDialog();
this.oPrintDialog = new System.Windows.Forms.PrintDialog();
this.oPageSetup = new System.Windows.Forms.PageSetupDialog();
((System.ruponentModel.ISupportInitialize)(this.dGrid)).BeginInit();
this.SuspendLayout();
//
// dGrid
//
this.dGrid.DataMember = "";
this.dGrid.Dock = System.Windows.Forms.DockStyle.Fill;
this.dGrid.HeaderForeColor = System.Drawing.SystemColors.ControlText;
this.dGrid.Name = "dGrid";
this.dGrid.Size = new System.Drawing.Size(292, 266);
this.dGrid.TabIndex = 0;
//
// mnuMain
//
this.mnuMain.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItem1});
//
// menuItem1
//
this.menuItem1.Index = 0;
this.menuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItem3,
this.menuItem4,
this.menuItem2,
this.menuItem5,
this.menuItem6});
this.menuItem1.Text = "&File";
//
// menuItem3
//
this.menuItem3.Index = 0;
this.menuItem3.Text = "Page Setup...";
this.menuItem3.Click += new System.EventHandler(this.menuItem3_Click);
//
// menuItem4
//
this.menuItem4.Index = 1;
this.menuItem4.Text = "Print...";
this.menuItem4.Click += new System.EventHandler(this.menuItem4_Click);
//
// menuItem2
//
this.menuItem2.Index = 2;
this.menuItem2.Text = "Print Preview...";
this.menuItem2.Click += new System.EventHandler(this.menuItem2_Click);
//
// menuItem5
//
this.menuItem5.Index = 3;
this.menuItem5.Text = "-";
//
// menuItem6
//
this.menuItem6.Index = 4;
this.menuItem6.Text = "Exit";
//
// ppDialog
//
this.ppDialog.AutoScrollMargin = new System.Drawing.Size(0, 0);
this.ppDialog.AutoScrollMinSize = new System.Drawing.Size(0, 0);
this.ppDialog.ClientSize = new System.Drawing.Size(400, 300);
this.ppDialog.Enabled = true;
// this.ppDialog.Icon = ((System.Drawing.Icon)(resources.GetObject("ppDialog.Icon")));
this.ppDialog.Location = new System.Drawing.Point(121, 21);
this.ppDialog.MaximumSize = new System.Drawing.Size(0, 0);
this.ppDialog.Name = "ppDialog";
this.ppDialog.Opacity = 1;
this.ppDialog.TransparencyKey = System.Drawing.Color.Empty;
this.ppDialog.Visible = false;
//
// oPrintDialog
//
this.oPrintDialog.AllowSomePages = true;
//
// GridPrintingDemo
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 266);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.dGrid});
this.Menu = this.mnuMain;
this.Name = "GridPrintingDemo";
this.Text = "Printing Grid Example";
this.Load += new System.EventHandler(this.Form1_Load);
((System.ruponentModel.ISupportInitialize)(this.dGrid)).EndInit();
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new GridPrintingDemo());
}
private void Form1_Load(object sender, System.EventArgs e)
{
try
{
//COnnection to database - get dataset
SqlConnection aConn = new SqlConnection("data source=HOBBIT;initial catalog=Northwind;integrated security=SSPI;");
SqlDataAdapter sqlAdapter = new SqlDataAdapter("Select CompanyName, Address, City, Region, PostalCode, Country from Customers",aConn);
DataSet aDataSet = new DataSet();
sqlAdapter.Fill(aDataSet);
//Assign dataset to Grid
dGrid.DataSource = aDataSet;
dGrid.SetDataBinding(aDataSet.Tables[0],"");
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString(),"Error");
}
}
private void menuItem2_Click(object sender, System.EventArgs e)
{
//Setup the document to print
PrintGridDocument aDoc = new PrintGridDocument(dGrid);
aDoc.Title = "Employee Report";
oPrintDialog.Document = aDoc;
if (oPrintDialog.ShowDialog() == DialogResult.OK)
{
//Display the print preview dialog
aDoc.DefaultPageSettings = oPageSettings;
ppDialog.Document = aDoc;
ppDialog.ShowDialog();
}
}
private void menuItem3_Click(object sender, System.EventArgs e)
{
oPageSetup.PageSettings = oPageSettings;
if(oPageSetup.ShowDialog() == DialogResult.OK)
{
oPageSettings = oPageSetup.PageSettings;
}
}
private void menuItem4_Click(object sender, System.EventArgs e)
{
//Setup the document to print
PrintGridDocument aDoc = new PrintGridDocument(dGrid);
aDoc.Title = "Employee Report";
oPrintDialog.Document = aDoc;
if (oPrintDialog.ShowDialog() == DialogResult.OK)
{
//Display the print preview dialog
aDoc.DefaultPageSettings = oPageSettings;
try
{
//Print the document
aDoc.Print();
}
catch(Exception ex)
{
//Display any errors
MessageBox.Show(ex.ToString());
}
}
}
}
public class PrintGridDocument : PrintDocument
{
//Data Members
private DataGrid m_oDataGrid;
private int m_nCurrPage;
private int m_nCurrRow;
private int m_nColumns;
private int m_nRows;
private bool m_bInitialized;
private int m_nLinesPerPage;
private int m_nTotalPages;
private int[] m_nColBounds;
//Properties
public Font PrintFont;
public string Title;
public PrintGridDocument(DataGrid aGrid) : base()
{
//Default Values
m_oDataGrid = aGrid;
m_nCurrPage = 0;
m_nCurrRow = 0;
m_bInitialized = false;
//Get total number of cols/rows in the data source
m_nColumns = ((DataTable)(m_oDataGrid.DataSource)).Columns.Count;
m_nRows = ((DataTable)(m_oDataGrid.DataSource)).Rows.Count;
}
//Override OnBeginPrint to set up the font we are going to use
protected override void OnBeginPrint(PrintEventArgs ev)
{
base.OnBeginPrint(ev);
//If client has not created a font, create a default font
// Note: an exception could be raised here, but it is deliberately not
// being caught because there is nothing we could do at this point!
if(PrintFont == null)
PrintFont = new Font("Arial", 9);
}
//Override the OnPrintPage to provide the printing logic for the document
protected override void OnPrintPage(PrintPageEventArgs e)
{
//Call base method
base.OnPrintPage(e);
//Get the margins
int nTextPosX = e.MarginBounds.Left;
int nTextPosY = e.MarginBounds.Top;
//Do first time initialization stuff
if(!m_bInitialized)
{
// Calculate the number of lines per page.
m_nLinesPerPage = (int)(e.MarginBounds.Height / PrintFont.GetHeight(e.Graphics));
m_nTotalPages = (int)Math.Ceiling((float)m_nRows / (float)m_nLinesPerPage);
//Create bounding box for columns
m_nColBounds = new int[m_nColumns];
//Calculate the correct spacing for the columns
for(int nCol = 0;nCol<m_nColumns;nCol++)
{
//Measure the column headers first
m_nColBounds[nCol] = (int)e.Graphics.MeasureString(
((DataTable)(m_oDataGrid.DataSource)).Columns[nCol].ColumnName, PrintFont).Width;
for(int nRow=0;nRow<m_nRows;nRow++)
{
//Compare data to current max
if(e.Graphics.MeasureString(m_oDataGrid[nRow,nCol].ToString(),PrintFont).Width > m_nColBounds[nCol])
m_nColBounds[nCol] = (int)e.Graphics.MeasureString(m_oDataGrid[nRow,nCol].ToString(),PrintFont).Width;
}
//Just use max possible size if too large
if(m_nColBounds[nCol] > e.MarginBounds.Width / m_nColumns)
m_nColBounds[nCol] = e.MarginBounds.Width / m_nColumns;
//Can"t be less than column width
if(m_nColBounds[nCol] < (int)Math.Round(e.Graphics.MeasureString(((DataTable)(m_oDataGrid.DataSource)).Columns[nCol].ColumnName, PrintFont).Width))
m_nColBounds[nCol] = (int)Math.Round(e.Graphics.MeasureString(((DataTable)(m_oDataGrid.DataSource)).Columns[nCol].ColumnName, PrintFont).Width);
}
//Move to correct starting page
if(this.PrinterSettings.PrintRange == PrintRange.SomePages)
{
while(m_nCurrPage < this.PrinterSettings.FromPage-1)
{
//Move to next page - advance data to next page as well
m_nCurrRow += m_nLinesPerPage;
m_nCurrPage++;
if(m_nCurrRow > m_nRows)
return;
}
if(m_nCurrPage > this.PrinterSettings.ToPage)
{
//Don"t print anything more
return;
}
}
//Set flag
m_bInitialized = true;
}
//Move to next page
m_nCurrPage++;
//Print Title if first page
if(m_nCurrPage == 1)
{
Font TitleFont = new Font("Arial",15);
int nXPos = (int)(((e.PageBounds.Right - e.PageBounds.Left) /2 ) -
(e.Graphics.MeasureString(Title,TitleFont).Width / 2));
e.Graphics.DrawString(Title,TitleFont,Brushes.Black,nXPos,e.MarginBounds.Top - TitleFont.GetHeight(e.Graphics) - 10);
}
//Draw page number
string strOutput = "Page " + m_nCurrPage + " of " + m_nTotalPages;
e.Graphics.DrawString(strOutput,PrintFont,Brushes.Black,e.MarginBounds.Right - e.Graphics.MeasureString(strOutput,PrintFont).Width,
e.MarginBounds.Bottom);
//Utility rectangle - use for many drawing operations
Rectangle aRect = new Rectangle();
//Loop through data
for(int nRow=m_nCurrRow; nRow < m_nRows; nRow++)
{
//Draw the current row within a shaded/unshaded box
aRect.X = e.MarginBounds.Left;
aRect.Y = nTextPosY;
aRect.Width = e.MarginBounds.Width;
aRect.Height = (int)PrintFont.GetHeight(e.Graphics);
//Draw the box
if(nRow%2 == 0)
e.Graphics.FillRectangle(Brushes.LightGray,aRect);
e.Graphics.DrawRectangle(Pens.Black,aRect);
//Loop through each column
for(int nCol=0; nCol < m_nColumns; nCol++)
{
//Set the rectangle to the correct position
aRect.X = nTextPosX;
aRect.Y = nTextPosY;
aRect.Width = m_nColBounds[nCol];
aRect.Height = (int)PrintFont.GetHeight(e.Graphics);
//Print the data
e.Graphics.DrawString(m_oDataGrid[nRow,nCol].ToString(),PrintFont,Brushes.Black,aRect);
//Advance the x Position counter
nTextPosX += m_nColBounds[nCol];
}
//Reassign the x position counter
nTextPosX = e.MarginBounds.Left;
//Move the y position counter down a line
nTextPosY += (int)PrintFont.GetHeight(e.Graphics);
//Check to see if we have reached the line limit - move to a new page if so
if(nRow - ((m_nCurrPage-1) * m_nLinesPerPage) == m_nLinesPerPage)
{
//Save the current row
m_nCurrRow = ++nRow;
e.HasMorePages = true;
return;
}
}
}
}
}
Print Dialogs
/*
GDI+ Programming in C# and VB .NET
by Nick Symmonds
Publisher: Apress
ISBN: 159059035X
*/
using System;
using System.Drawing;
using System.Drawing.Printing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
namespace PrintDialogs_c
{
public class PrintDialogs : System.Windows.Forms.Form
{
private Image MyImage;
private PrintDocument pd;
private PrintPreviewDialog Preview;
private System.Windows.Forms.Button cmdShow;
private System.Windows.Forms.Label lblPrint;
private System.ruponentModel.Container components = null;
public PrintDialogs()
{
InitializeComponent();
MyImage = Bitmap.FromFile(@"d:\colorbars.jpg");
Preview = new PrintPreviewDialog();
Preview.UseAntiAlias = true;
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.cmdShow = new System.Windows.Forms.Button();
this.lblPrint = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// cmdShow
//
this.cmdShow.Location = new System.Drawing.Point(352, 344);
this.cmdShow.Name = "cmdShow";
this.cmdShow.Size = new System.Drawing.Size(72, 24);
this.cmdShow.TabIndex = 0;
this.cmdShow.Text = "Show";
this.cmdShow.Click += new System.EventHandler(this.cmdShow_Click);
//
// lblPrint
//
this.lblPrint.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lblPrint.Location = new System.Drawing.Point(144, 32);
this.lblPrint.Name = "lblPrint";
this.lblPrint.Size = new System.Drawing.Size(280, 136);
this.lblPrint.TabIndex = 1;
//
// PrintDialogs
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(442, 373);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.lblPrint,
this.cmdShow});
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "PrintDialogs";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "PrintDialogs";
this.Load += new System.EventHandler(this.PrintDialogs_Load);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new PrintDialogs());
}
private void PrintDialogs_Load(object sender, System.EventArgs e)
{
pd = new PrintDocument();
pd.PrintPage += new PrintPageEventHandler(this.pd_Print);
Preview.Document = pd;
}
protected override void OnPaint(PaintEventArgs e)
{
DrawIt(e.Graphics);
}
private void pd_Print(object sender, PrintPageEventArgs e)
{
lblPrint.Text += "pd_Print pd= " + sender.ToString() + "\n" ;
DrawIt(e.Graphics);
}
private void DrawIt(Graphics G)
{
G.SmoothingMode=SmoothingMode.AntiAlias;
G.DrawImage(MyImage, 10, 10);
LinearGradientBrush B = new LinearGradientBrush(
new Rectangle(0, 0, 50, 10),
Color.Red, Color.Blue,
LinearGradientMode.ForwardDiagonal);
G.FillEllipse(B, 10, 200, 200, 75);
G.DrawString("Print Preview Test",
new Font("Comic Sans MS",24), B, 50, 275);
}
private void cmdShow_Click(object sender, System.EventArgs e)
{
Preview.WindowState = FormWindowState.Maximized;
pd.DocumentName = DateTime.Now.Ticks.ToString();
Preview.ShowDialog();
}
}
}
Printer Caps 1
/*
Professional Windows GUI Programming Using C#
by Jay Glynn, Csaba Torok, Richard Conway, Wahid Choudhury,
Zach Greenvoss, Shripad Kulkarni, Neil Whitlow
Publisher: Peer Information
ISBN: 1861007663
*/
using System.Drawing.Printing;
using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
//Need Printing namespace
using System.Drawing.Printing;
namespace PrinterCaps1
{
public class PrinterCaps1 : System.Windows.Forms.Form
{
private System.ruponentModel.Container components = null;
public PrinterCaps1()
{
InitializeComponent();
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
//
// PrinterCaps1
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 266);
this.Name = "PrinterCaps1";
this.Text = "Printer Caps";
this.Paint += new System.Windows.Forms.PaintEventHandler(this.PrinterCaps1_Paint);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new PrinterCaps1());
}
private void PrinterCaps1_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
{
PrinterSettings pSettings = new PrinterSettings();
Font printFont = new Font("Arial", 10);
//Position
int nTextPosY = 0;
int nTextPosX = 5;
int nHeight = (int)printFont.GetHeight(e.Graphics);
foreach(string sPtr in PrinterSettings.InstalledPrinters)
{
//pSettings.PrinterName = sPtr;
pSettings.PrinterName = "BadName";
//if(pSettings.IsValid)
//{
e.Graphics.DrawString(sPtr, printFont,Brushes.Black, nTextPosX, nTextPosY + 5);
e.Graphics.DrawString("Can Duplex: " + pSettings.CanDuplex.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight));
e.Graphics.DrawString("Is Default: " + pSettings.IsDefaultPrinter.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*2));
e.Graphics.DrawString("Is Plotter: " + pSettings.IsPlotter.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*3));
e.Graphics.DrawString("Landscape Angle: " + pSettings.LandscapeAngle.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*4));
e.Graphics.DrawString("Maximum Copies: " + pSettings.MaximumCopies.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*5));
e.Graphics.DrawString("Maximum Page: " + pSettings.MaximumPage.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*6));
e.Graphics.DrawString("Minimum Page: " + pSettings.MinimumPage.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*7));
e.Graphics.DrawString("Supports Color: " + pSettings.SupportsColor.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*8));
nTextPosY = nTextPosY + ((5 + nHeight*8) + nHeight);
//}
}
return;
}
}
}
Printer Caps 2
/*
Professional Windows GUI Programming Using C#
by Jay Glynn, Csaba Torok, Richard Conway, Wahid Choudhury,
Zach Greenvoss, Shripad Kulkarni, Neil Whitlow
Publisher: Peer Information
ISBN: 1861007663
*/
using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
//Need this namespace to access the Printing functionality
using System.Drawing.Printing;
namespace PrinterCaps2
{
/// <summary>
/// Summary description for Form1.
/// </summary>
public class PrinterCaps2 : System.Windows.Forms.Form
{
private System.Drawing.Printing.PrintDocument printDoc;
private System.Windows.Forms.PrintPreviewDialog ppDialog;
private System.Windows.Forms.Button btnPrint;
/// <summary>
/// Required designer variable.
/// </summary>
private System.ruponentModel.Container components = null;
public PrinterCaps2()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
// System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(PrinterCaps2));
this.printDoc = new System.Drawing.Printing.PrintDocument();
this.ppDialog = new System.Windows.Forms.PrintPreviewDialog();
this.btnPrint = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// printDoc
//
this.printDoc.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.printDoc_PrintPage);
//
// ppDialog
//
this.ppDialog.AutoScrollMargin = new System.Drawing.Size(0, 0);
this.ppDialog.AutoScrollMinSize = new System.Drawing.Size(0, 0);
this.ppDialog.ClientSize = new System.Drawing.Size(400, 300);
this.ppDialog.Enabled = true;
// this.ppDialog.Icon = ((System.Drawing.Icon)(resources.GetObject("ppDialog.Icon")));
this.ppDialog.Location = new System.Drawing.Point(195, 22);
this.ppDialog.MaximumSize = new System.Drawing.Size(0, 0);
this.ppDialog.Name = "ppDialog";
this.ppDialog.Opacity = 1;
this.ppDialog.TransparencyKey = System.Drawing.Color.Empty;
this.ppDialog.Visible = false;
//
// btnPrint
//
this.btnPrint.Location = new System.Drawing.Point(52, 28);
this.btnPrint.Name = "btnPrint";
this.btnPrint.TabIndex = 0;
this.btnPrint.Text = "Print";
this.btnPrint.Click += new System.EventHandler(this.btnPrint_Click);
//
// PrinterCaps2
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(176, 86);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.btnPrint});
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Name = "PrinterCaps2";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Printer Caps";
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new PrinterCaps2());
}
private void printDoc_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
PrinterSettings pSettings = new PrinterSettings();
Font printFont = new Font("Arial", 12);
//Use the Margins
int nTextPosY = e.MarginBounds.Top;
int nTextPosX = e.MarginBounds.Left;
int nHeight = (int)printFont.GetHeight(e.Graphics);
foreach(string sPtr in PrinterSettings.InstalledPrinters)
{
pSettings.PrinterName = sPtr;
if(pSettings.IsValid)
{
e.Graphics.DrawString(sPtr, printFont,Brushes.Black, nTextPosX, nTextPosY + 5);
e.Graphics.DrawString("Can Duplex: " + pSettings.CanDuplex.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight));
e.Graphics.DrawString("Is Default: " + pSettings.IsDefaultPrinter.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*2));
e.Graphics.DrawString("Is Plotter: " + pSettings.IsPlotter.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*3));
e.Graphics.DrawString("Landscape Angle: " + pSettings.LandscapeAngle.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*4));
e.Graphics.DrawString("Maximum Copies: " + pSettings.MaximumCopies.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*5));
e.Graphics.DrawString("Maximum Page: " + pSettings.MaximumPage.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*6));
e.Graphics.DrawString("Minimum Page: " + pSettings.MinimumPage.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*7));
e.Graphics.DrawString("Supports Color: " + pSettings.SupportsColor.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*8));
nTextPosY = nTextPosY + ((5 + nHeight*8) + nHeight);
}
}
}
private void btnPrint_Click(object sender, System.EventArgs e)
{
try
{
ppDialog.Document = printDoc;
ppDialog.ShowDialog();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
Printer Caps 3
/*
Professional Windows GUI Programming Using C#
by Jay Glynn, Csaba Torok, Richard Conway, Wahid Choudhury,
Zach Greenvoss, Shripad Kulkarni, Neil Whitlow
Publisher: Peer Information
ISBN: 1861007663
*/
using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
using System.Drawing.Printing;
namespace PrinterCaps3
{
public class PrinterCaps3 : System.Windows.Forms.Form
{
private int m_nCurrPrinter;
private System.Drawing.Printing.PrintDocument printDoc;
private System.Windows.Forms.PrintPreviewDialog ppDialog;
private System.Windows.Forms.Button btnPrint;
private System.ruponentModel.Container components = null;
public PrinterCaps3()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
// System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(PrinterCaps3));
this.printDoc = new System.Drawing.Printing.PrintDocument();
this.ppDialog = new System.Windows.Forms.PrintPreviewDialog();
this.btnPrint = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// printDoc
//
this.printDoc.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.printDoc_PrintPage);
//
// ppDialog
//
this.ppDialog.AutoScrollMargin = new System.Drawing.Size(0, 0);
this.ppDialog.AutoScrollMinSize = new System.Drawing.Size(0, 0);
this.ppDialog.ClientSize = new System.Drawing.Size(400, 300);
this.ppDialog.Enabled = true;
// this.ppDialog.Icon = ((System.Drawing.Icon)(resources.GetObject("ppDialog.Icon")));
this.ppDialog.Location = new System.Drawing.Point(195, 22);
this.ppDialog.MaximumSize = new System.Drawing.Size(0, 0);
this.ppDialog.Name = "ppDialog";
this.ppDialog.Opacity = 1;
this.ppDialog.TransparencyKey = System.Drawing.Color.Empty;
this.ppDialog.Visible = false;
//
// btnPrint
//
this.btnPrint.Location = new System.Drawing.Point(52, 28);
this.btnPrint.Name = "btnPrint";
this.btnPrint.TabIndex = 0;
this.btnPrint.Text = "Print";
this.btnPrint.Click += new System.EventHandler(this.btnPrint_Click);
//
// PrinterCaps3
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(176, 86);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.btnPrint});
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Name = "PrinterCaps3";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Printer Caps";
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new PrinterCaps3());
}
private void printDoc_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
PrinterSettings pSettings = new PrinterSettings();
Font printFont = new Font("Arial", 12);
//Use the Margins
int nTextPosY = e.MarginBounds.Top;
int nTextPosX = e.MarginBounds.Left;
int nHeight = (int)printFont.GetHeight(e.Graphics);
//Height of a printer block
int nBlockHeight = 9 * nHeight;
//Loop through using indexor now
//Start with the previous index in m_nCurrPrinter
for(int x = m_nCurrPrinter;x< PrinterSettings.InstalledPrinters.Count; x++)//each(string sPtr in PrinterSettings.InstalledPrinters)
{
pSettings.PrinterName = PrinterSettings.InstalledPrinters[x];
if(pSettings.IsValid)
{
//Ensure this printer block can fit on the page
if(nTextPosY + nBlockHeight < e.MarginBounds.Bottom)
{
//Print the caps of the printer
e.Graphics.DrawString(PrinterSettings.InstalledPrinters[x], printFont,Brushes.Black, nTextPosX, nTextPosY + 5);
e.Graphics.DrawString("Can Duplex: " + pSettings.CanDuplex.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight));
e.Graphics.DrawString("Is Default: " + pSettings.IsDefaultPrinter.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*2));
e.Graphics.DrawString("Is Plotter: " + pSettings.IsPlotter.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*3));
e.Graphics.DrawString("Landscape Angle: " + pSettings.LandscapeAngle.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*4));
e.Graphics.DrawString("Maximum Copies: " + pSettings.MaximumCopies.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*5));
e.Graphics.DrawString("Maximum Page: " + pSettings.MaximumPage.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*6));
e.Graphics.DrawString("Minimum Page: " + pSettings.MinimumPage.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*7));
e.Graphics.DrawString("Supports Color: " + pSettings.SupportsColor.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*8));
nTextPosY = nTextPosY + ((5 + nHeight*8) + nHeight);
}
else
{
//Could nto fit block on the page - need more pages
m_nCurrPrinter = x;
e.HasMorePages = true;
return;
}
}
}
//Last page if we reached here
e.HasMorePages = false;
m_nCurrPrinter = 0;
return;
}
private void btnPrint_Click(object sender, System.EventArgs e)
{
//Set to defaults
m_nCurrPrinter = 0;
try
{
ppDialog.Document = printDoc;
ppDialog.ShowDialog();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
Printer Caps 4
/*
Professional Windows GUI Programming Using C#
by Jay Glynn, Csaba Torok, Richard Conway, Wahid Choudhury,
Zach Greenvoss, Shripad Kulkarni, Neil Whitlow
Publisher: Peer Information
ISBN: 1861007663
*/
using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
using System.Drawing.Printing;
using System.Drawing.Drawing2D;
namespace PrinterCaps4
{
public class PrinterCaps4 : System.Windows.Forms.Form
{
private int m_nCurrPrinter;
private System.Drawing.Printing.PrintDocument printDoc;
private System.Windows.Forms.PrintPreviewDialog ppDialog;
private System.Windows.Forms.Button btnPrint;
private System.ruponentModel.Container components = null;
public PrinterCaps4()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
// System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(PrinterCaps4));
this.printDoc = new System.Drawing.Printing.PrintDocument();
this.ppDialog = new System.Windows.Forms.PrintPreviewDialog();
this.btnPrint = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// printDoc
//
this.printDoc.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.printDoc_PrintPage);
//
// ppDialog
//
this.ppDialog.AutoScrollMargin = new System.Drawing.Size(0, 0);
this.ppDialog.AutoScrollMinSize = new System.Drawing.Size(0, 0);
this.ppDialog.ClientSize = new System.Drawing.Size(400, 300);
this.ppDialog.Enabled = true;
// this.ppDialog.Icon = ((System.Drawing.Icon)(resources.GetObject("ppDialog.Icon")));
this.ppDialog.Location = new System.Drawing.Point(195, 22);
this.ppDialog.MaximumSize = new System.Drawing.Size(0, 0);
this.ppDialog.Name = "ppDialog";
this.ppDialog.Opacity = 1;
this.ppDialog.TransparencyKey = System.Drawing.Color.Empty;
this.ppDialog.Visible = false;
//
// btnPrint
//
this.btnPrint.Location = new System.Drawing.Point(52, 28);
this.btnPrint.Name = "btnPrint";
this.btnPrint.TabIndex = 0;
this.btnPrint.Text = "Print";
this.btnPrint.Click += new System.EventHandler(this.btnPrint_Click);
//
// PrinterCaps4
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(176, 86);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.btnPrint});
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Name = "PrinterCaps4";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Printer Caps";
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new PrinterCaps4());
}
private void printDoc_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
PrinterSettings pSettings = new PrinterSettings();
Font printFont = new Font("Arial", 12);
//Use the Margins
int nTextPosY = e.MarginBounds.Top;
int nTextPosX = e.MarginBounds.Left;
int nHeight = (int)printFont.GetHeight(e.Graphics);
//Height of a printer block
int nBlockHeight = 9 * nHeight;
//Print Background Graphic
LinearGradientBrush aBrush =
new LinearGradientBrush(e.MarginBounds,Color.FromArgb(100,Color.LightBlue),
Color.FromArgb(100,Color.Blue),LinearGradientMode.ForwardDiagonal);
e.Graphics.FillRectangle(aBrush,e.MarginBounds);
//Loop through using indexor now
//Start with the previous index in m_nCurrPrinter
for(int x = m_nCurrPrinter;x< PrinterSettings.InstalledPrinters.Count; x++)//each(string sPtr in PrinterSettings.InstalledPrinters)
{
pSettings.PrinterName = PrinterSettings.InstalledPrinters[x];
if(pSettings.IsValid)
{
//Ensure this printer block can fit on the page
if(nTextPosY + nBlockHeight < e.MarginBounds.Bottom)
{
//Print the caps of the printer
e.Graphics.DrawString(PrinterSettings.InstalledPrinters[x], printFont,Brushes.Black, nTextPosX, nTextPosY + 5);
e.Graphics.DrawString("Can Duplex: " + pSettings.CanDuplex.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight));
e.Graphics.DrawString("Is Default: " + pSettings.IsDefaultPrinter.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*2));
e.Graphics.DrawString("Is Plotter: " + pSettings.IsPlotter.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*3));
e.Graphics.DrawString("Landscape Angle: " + pSettings.LandscapeAngle.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*4));
e.Graphics.DrawString("Maximum Copies: " + pSettings.MaximumCopies.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*5));
e.Graphics.DrawString("Maximum Page: " + pSettings.MaximumPage.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*6));
e.Graphics.DrawString("Minimum Page: " + pSettings.MinimumPage.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*7));
e.Graphics.DrawString("Supports Color: " + pSettings.SupportsColor.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*8));
nTextPosY = nTextPosY + ((5 + nHeight*8) + nHeight);
//Draw line after each
e.Graphics.DrawLine(System.Drawing.Pens.Black,nTextPosX,nTextPosY,e.MarginBounds.Right - 10,nTextPosY);
e.Graphics.FillEllipse(System.Drawing.Brushes.Black,e.MarginBounds.Right - 10,nTextPosY-5,10,10);
}
else
{
//Could nto fit block on the page - need more pages
m_nCurrPrinter = x;
e.HasMorePages = true;
return;
}
}
}
//Last page if we reached here
e.HasMorePages = false;
m_nCurrPrinter = 0;
return;
}
private void btnPrint_Click(object sender, System.EventArgs e)
{
//Set to defaults
m_nCurrPrinter = 0;
try
{
ppDialog.Document = printDoc;
ppDialog.ShowDialog();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
Printer Caps 5
/*
Professional Windows GUI Programming Using C#
by Jay Glynn, Csaba Torok, Richard Conway, Wahid Choudhury,
Zach Greenvoss, Shripad Kulkarni, Neil Whitlow
Publisher: Peer Information
ISBN: 1861007663
*/
using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
using System.Drawing.Printing;
using System.Drawing.Drawing2D;
namespace PrinterCaps5
{
public class PrinterCaps5 : System.Windows.Forms.Form
{
private int m_nCurrPrinter;
private int m_nCurrPage;
private System.Drawing.Printing.PrintDocument printDoc;
private System.Windows.Forms.PrintPreviewDialog ppDialog;
private System.Windows.Forms.Button btnPrint;
private System.Windows.Forms.PrintDialog oPrintDialog;
private System.ruponentModel.Container components = null;
public PrinterCaps5()
{
InitializeComponent();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
// System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(PrinterCaps5));
this.printDoc = new System.Drawing.Printing.PrintDocument();
this.ppDialog = new System.Windows.Forms.PrintPreviewDialog();
this.btnPrint = new System.Windows.Forms.Button();
this.oPrintDialog = new System.Windows.Forms.PrintDialog();
this.SuspendLayout();
//
// printDoc
//
this.printDoc.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.printDoc_PrintPage);
//
// ppDialog
//
this.ppDialog.AutoScrollMargin = new System.Drawing.Size(0, 0);
this.ppDialog.AutoScrollMinSize = new System.Drawing.Size(0, 0);
this.ppDialog.ClientSize = new System.Drawing.Size(400, 300);
this.ppDialog.Enabled = true;
// this.ppDialog.Icon = ((System.Drawing.Icon)(resources.GetObject("ppDialog.Icon")));
this.ppDialog.Location = new System.Drawing.Point(142, 13);
this.ppDialog.MaximumSize = new System.Drawing.Size(0, 0);
this.ppDialog.Name = "ppDialog";
this.ppDialog.Opacity = 1;
this.ppDialog.TransparencyKey = System.Drawing.Color.Empty;
this.ppDialog.Visible = false;
//
// btnPrint
//
this.btnPrint.Location = new System.Drawing.Point(52, 28);
this.btnPrint.Name = "btnPrint";
this.btnPrint.TabIndex = 0;
this.btnPrint.Text = "Print";
this.btnPrint.Click += new System.EventHandler(this.btnPrint_Click);
//
// oPrintDialog
//
this.oPrintDialog.AllowSomePages = true;
//
// PrinterCaps5
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(176, 86);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.btnPrint});
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Name = "PrinterCaps5";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Printer Caps";
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new PrinterCaps5());
}
private void printDoc_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
PrinterSettings pSettings = new PrinterSettings();
Font printFont = new Font("Arial", 12);
//Use the Margins
int nTextPosY = e.MarginBounds.Top;
int nTextPosX = e.MarginBounds.Left;
int nHeight = (int)printFont.GetHeight(e.Graphics);
//Height of a printer block
int nBlockHeight = 9 * nHeight;
if(e.PageSettings.PrinterSettings.PrintRange == PrintRange.SomePages)
{
while(m_nCurrPage < e.PageSettings.PrinterSettings.FromPage)
{
//Move printer to next page block
m_nCurrPrinter += (int)(e.MarginBounds.Height / nBlockHeight);
m_nCurrPage++;
if(m_nCurrPrinter > PrinterSettings.InstalledPrinters.Count)
return;
}
if(m_nCurrPage > e.PageSettings.PrinterSettings.ToPage)
{
//Don"t print anything more
return;
}
}
//Print Background Graphic
LinearGradientBrush aBrush =
new LinearGradientBrush(e.MarginBounds,Color.FromArgb(100,Color.LightBlue),
Color.FromArgb(100,Color.Blue),LinearGradientMode.ForwardDiagonal);
e.Graphics.FillRectangle(aBrush,e.MarginBounds);
//Loop through using indexor now
//Start with the previous index in m_nCurrPrinter
for(int x = m_nCurrPrinter;x< PrinterSettings.InstalledPrinters.Count; x++)//each(string sPtr in PrinterSettings.InstalledPrinters)
{
pSettings.PrinterName = PrinterSettings.InstalledPrinters[x];
if(pSettings.IsValid)
{
//Ensure this printer block can fit on the page
if(nTextPosY + nBlockHeight < e.MarginBounds.Bottom)
{
//Print the caps of the printer
e.Graphics.DrawString(PrinterSettings.InstalledPrinters[x], printFont,Brushes.Black, nTextPosX, nTextPosY + 5);
e.Graphics.DrawString("Can Duplex: " + pSettings.CanDuplex.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight));
e.Graphics.DrawString("Is Default: " + pSettings.IsDefaultPrinter.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*2));
e.Graphics.DrawString("Is Plotter: " + pSettings.IsPlotter.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*3));
e.Graphics.DrawString("Landscape Angle: " + pSettings.LandscapeAngle.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*4));
e.Graphics.DrawString("Maximum Copies: " + pSettings.MaximumCopies.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*5));
e.Graphics.DrawString("Maximum Page: " + pSettings.MaximumPage.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*6));
e.Graphics.DrawString("Minimum Page: " + pSettings.MinimumPage.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*7));
e.Graphics.DrawString("Supports Color: " + pSettings.SupportsColor.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*8));
nTextPosY = nTextPosY + ((5 + nHeight*8) + nHeight);
//Draw line after each
e.Graphics.DrawLine(System.Drawing.Pens.Black,nTextPosX,nTextPosY,e.MarginBounds.Right - 10,nTextPosY);
e.Graphics.FillEllipse(System.Drawing.Brushes.Black,e.MarginBounds.Right - 10,nTextPosY-5,10,10);
}
else
{
//Could nto fit block on the page - need more pages
m_nCurrPrinter = x;
e.HasMorePages = true;
return;
}
}
}
//Last page if we reached here
e.HasMorePages = false;
m_nCurrPrinter = 0;
return;
}
private void btnPrint_Click(object sender, System.EventArgs e)
{
//Set to defaults
m_nCurrPrinter = 0;
m_nCurrPage = 1;
oPrintDialog.Document = printDoc;
if (oPrintDialog.ShowDialog() == DialogResult.OK)
{
try
{
ppDialog.Document = printDoc;
ppDialog.ShowDialog();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
}
}
Printer Caps 6
/*
Professional Windows GUI Programming Using C#
by Jay Glynn, Csaba Torok, Richard Conway, Wahid Choudhury,
Zach Greenvoss, Shripad Kulkarni, Neil Whitlow
Publisher: Peer Information
ISBN: 1861007663
*/
using System;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
using System.Drawing.Printing;
using System.Drawing.Drawing2D;
namespace PrinterCaps6
{
public class PrinterCaps6 : System.Windows.Forms.Form
{
//Saved PageSettings Object
private PageSettings oPageSettings;
private int m_nCurrPrinter;
private int m_nCurrPage;
private System.Drawing.Printing.PrintDocument printDoc;
private System.Windows.Forms.PrintPreviewDialog ppDialog;
private System.Windows.Forms.Button btnPrint;
private System.Windows.Forms.PrintDialog oPrintDialog;
private System.Windows.Forms.PageSetupDialog oPageSetup;
private System.Windows.Forms.Button btnSetup;
private System.ruponentModel.Container components = null;
public PrinterCaps6()
{
InitializeComponent();
//Create PageSettings object to store page information
oPageSettings = new PageSettings();
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
// System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(PrinterCaps6));
this.printDoc = new System.Drawing.Printing.PrintDocument();
this.ppDialog = new System.Windows.Forms.PrintPreviewDialog();
this.btnPrint = new System.Windows.Forms.Button();
this.oPrintDialog = new System.Windows.Forms.PrintDialog();
this.oPageSetup = new System.Windows.Forms.PageSetupDialog();
this.btnSetup = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// printDoc
//
this.printDoc.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.printDoc_PrintPage);
//
// ppDialog
//
this.ppDialog.AutoScrollMargin = new System.Drawing.Size(0, 0);
this.ppDialog.AutoScrollMinSize = new System.Drawing.Size(0, 0);
this.ppDialog.ClientSize = new System.Drawing.Size(400, 300);
this.ppDialog.Enabled = true;
// this.ppDialog.Icon = ((System.Drawing.Icon)(resources.GetObject("ppDialog.Icon")));
this.ppDialog.Location = new System.Drawing.Point(326, 19);
this.ppDialog.MaximumSize = new System.Drawing.Size(0, 0);
this.ppDialog.Name = "ppDialog";
this.ppDialog.Opacity = 1;
this.ppDialog.TransparencyKey = System.Drawing.Color.Empty;
this.ppDialog.Visible = false;
//
// btnPrint
//
this.btnPrint.Location = new System.Drawing.Point(52, 44);
this.btnPrint.Name = "btnPrint";
this.btnPrint.TabIndex = 0;
this.btnPrint.Text = "Print";
this.btnPrint.Click += new System.EventHandler(this.btnPrint_Click);
//
// oPrintDialog
//
this.oPrintDialog.AllowSomePages = true;
this.oPrintDialog.PrintToFile = true;
//
// btnSetup
//
this.btnSetup.Location = new System.Drawing.Point(52, 8);
this.btnSetup.Name = "btnSetup";
this.btnSetup.TabIndex = 1;
this.btnSetup.Text = "Page Setup";
this.btnSetup.Click += new System.EventHandler(this.btnSetup_Click);
//
// PrinterCaps6
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(176, 86);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.btnSetup,
this.btnPrint});
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog;
this.Name = "PrinterCaps6";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Printer Caps";
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new PrinterCaps6());
}
private void printDoc_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
{
PrinterSettings pSettings = new PrinterSettings();
Font printFont = new Font("Arial", 12);
//Use the Margins
int nTextPosY = e.MarginBounds.Top;
int nTextPosX = e.MarginBounds.Left;
int nHeight = (int)printFont.GetHeight(e.Graphics);
//Height of a printer block
int nBlockHeight = 9 * nHeight;
if(e.PageSettings.PrinterSettings.PrintRange == PrintRange.SomePages)
{
while(m_nCurrPage < e.PageSettings.PrinterSettings.FromPage)
{
//Move printer to next page block
m_nCurrPrinter += (int)(e.MarginBounds.Height / nBlockHeight);
m_nCurrPage++;
if(m_nCurrPrinter > PrinterSettings.InstalledPrinters.Count)
return;
}
if(m_nCurrPage > e.PageSettings.PrinterSettings.ToPage)
{
//Don"t print anything more
return;
}
}
//Print Background Graphic
LinearGradientBrush aBrush =
new LinearGradientBrush(e.MarginBounds,Color.FromArgb(100,Color.LightBlue),
Color.FromArgb(100,Color.Blue),LinearGradientMode.ForwardDiagonal);
e.Graphics.FillRectangle(aBrush,e.MarginBounds);
//Loop through using indexor now
//Start with the previous index in m_nCurrPrinter
for(int x = m_nCurrPrinter;x< PrinterSettings.InstalledPrinters.Count; x++)//each(string sPtr in PrinterSettings.InstalledPrinters)
{
pSettings.PrinterName = PrinterSettings.InstalledPrinters[x];
if(pSettings.IsValid)
{
//Ensure this printer block can fit on the page
if(nTextPosY + nBlockHeight < e.MarginBounds.Bottom)
{
//Print the caps of the printer
e.Graphics.DrawString(PrinterSettings.InstalledPrinters[x], printFont,Brushes.Black, nTextPosX, nTextPosY + 5);
e.Graphics.DrawString("Can Duplex: " + pSettings.CanDuplex.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight));
e.Graphics.DrawString("Is Default: " + pSettings.IsDefaultPrinter.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*2));
e.Graphics.DrawString("Is Plotter: " + pSettings.IsPlotter.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*3));
e.Graphics.DrawString("Landscape Angle: " + pSettings.LandscapeAngle.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*4));
e.Graphics.DrawString("Maximum Copies: " + pSettings.MaximumCopies.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*5));
e.Graphics.DrawString("Maximum Page: " + pSettings.MaximumPage.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*6));
e.Graphics.DrawString("Minimum Page: " + pSettings.MinimumPage.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*7));
e.Graphics.DrawString("Supports Color: " + pSettings.SupportsColor.ToString(),
printFont,Brushes.Black, nTextPosX + 10, nTextPosY + (5 + nHeight*8));
nTextPosY = nTextPosY + ((5 + nHeight*8) + nHeight);
//Draw line after each
e.Graphics.DrawLine(System.Drawing.Pens.Black,nTextPosX,nTextPosY,e.MarginBounds.Right - 10,nTextPosY);
e.Graphics.FillEllipse(System.Drawing.Brushes.Black,e.MarginBounds.Right - 10,nTextPosY-5,10,10);
}
else
{
//Couldn"t fit block on the page - need more pages
m_nCurrPrinter = x;
e.HasMorePages = true;
return;
}
}
}
//Last page if we reached here
e.HasMorePages = false;
m_nCurrPrinter = 0;
return;
}
private void btnPrint_Click(object sender, System.EventArgs e)
{
//Set to defaults
m_nCurrPrinter = 0;
m_nCurrPage = 1;
oPrintDialog.Document = printDoc;
if (oPrintDialog.ShowDialog() == DialogResult.OK)
{
try
{
//Ensure the correct PrinterSettings object is used
oPageSettings.PrinterSettings = printDoc.PrinterSettings;
//Assign PageSettings object to all pages
printDoc.DefaultPageSettings = oPageSettings;
ppDialog.Document = printDoc;
ppDialog.ShowDialog();
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
}
private void btnSetup_Click(object sender, System.EventArgs e)
{
oPageSetup.PageSettings = oPageSettings;
if(oPageSetup.ShowDialog() == DialogResult.OK)
{
oPageSettings = oPageSetup.PageSettings;
}
}
}
}
Print Events
/*
GDI+ Programming in C# and VB .NET
by Nick Symmonds
Publisher: Apress
ISBN: 159059035X
*/
using System;
using System.IO;
using System.Drawing;
using System.Drawing.Printing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
namespace PrintEvents_c
{
public class PrintEvents : System.Windows.Forms.Form
{
private Font PrintFont;
private StreamReader PrintStream;
private System.Windows.Forms.Button cmdPrint;
private System.Windows.Forms.Label lblEvents;
private System.ruponentModel.Container components = null;
public PrintEvents()
{
InitializeComponent();
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
PrintFont.Dispose();
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.cmdPrint = new System.Windows.Forms.Button();
this.lblEvents = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// cmdPrint
//
this.cmdPrint.Location = new System.Drawing.Point(104, 280);
this.cmdPrint.Name = "cmdPrint";
this.cmdPrint.Size = new System.Drawing.Size(80, 24);
this.cmdPrint.TabIndex = 0;
this.cmdPrint.Text = "Print";
this.cmdPrint.Click += new System.EventHandler(this.cmdPrint_Click);
//
// lblEvents
//
this.lblEvents.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.lblEvents.Location = new System.Drawing.Point(24, 16);
this.lblEvents.Name = "lblEvents";
this.lblEvents.Size = new System.Drawing.Size(248, 248);
this.lblEvents.TabIndex = 1;
//
// PrintEvents
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(292, 323);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.lblEvents,
this.cmdPrint});
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "PrintEvents";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "PrintEvents";
this.Load += new System.EventHandler(this.PrintEvents_Load);
this.ResumeLayout(false);
}
#endregion
[STAThread]
static void Main()
{
Application.Run(new PrintEvents());
}
private void PrintEvents_Load(object sender, System.EventArgs e)
{
}
// Print the file.
public void Print_It()
{
try
{
//Get the file to print
PrintStream = new StreamReader ("Test.txt");
try
{
PrintFont = new Font("Arial", 10);
PrintDocument pd = new PrintDocument();
//Assign my overloaded version of the standard print controller
//Send it a reference to the label so it can tell us what is
//going on.
pd.PrintController = new MyPrintController(ref lblEvents);
//Install event handlers
pd.BeginPrint += new PrintEventHandler(this.pd_StartPrint);
pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage);
pd.EndPrint += new PrintEventHandler(this.pd_EndPrint);
// Print the document.
pd.Print();
}
finally
{
PrintStream.Close();
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
private void pd_StartPrint(object sender, PrintEventArgs ev)
{
lblEvents.Text += "PrintDocument: BeginPrint\n";
}
private void pd_EndPrint(object sender, PrintEventArgs ev)
{
lblEvents.Text += "PrintDocument: EndPrinting\n";
}
// The PrintPage event is raised for each page to be printed.
private void pd_PrintPage(object sender, PrintPageEventArgs ev)
{
float linesPerPage = 0;
float yPos = 0;
int count = 0;
float leftMargin = ev.MarginBounds.Left;
float topMargin = ev.MarginBounds.Top;
String line=null;
lblEvents.Text += "PrintDocument: PagePrint\n";
// Calculate the number of lines per page.
linesPerPage = ev.MarginBounds.Height / PrintFont.GetHeight(ev.Graphics);
// Iterate over the file, printing each line. Use a basic StringFormat
while (count++ < linesPerPage && ((line=PrintStream.ReadLine()) != null))
{
//Calculate vertical position of the line.
yPos = topMargin + (count * PrintFont.GetHeight(ev.Graphics));
//This is the graphics object obtained by the PrintController
//OnStartPage method. We are drawing to the printer!!
ev.Graphics.DrawString (line, PrintFont, Brushes.Black,
leftMargin, yPos, new StringFormat());
}
// If more lines exist, print another page.
if (line != null)
ev.HasMorePages = true;
else
ev.HasMorePages = false;
}
private void cmdPrint_Click(object sender, System.EventArgs e)
{
Print_It();
}
}
public class MyPrintController : StandardPrintController
{
private Label lblEvents;
public MyPrintController(ref Label lbl): base()
{
lblEvents = lbl;
}
public override void OnStartPrint(PrintDocument doc, PrintEventArgs e)
{
lblEvents.Text += " PrintController: OnStartPrint\n";
base.OnStartPrint(doc, e);
}
public override Graphics OnStartPage(PrintDocument doc, PrintPageEventArgs e)
{
lblEvents.Text += " PrintController: OnStartPage\n";
return( base.OnStartPage(doc, e) );
}
public override void OnEndPage(PrintDocument doc, PrintPageEventArgs e)
{
lblEvents.Text += " PrintController: OnEndPage\n";
base.OnEndPage(doc, e);
}
public override void OnEndPrint(PrintDocument doc, PrintEventArgs e)
{
lblEvents.Text += " PrintController: OnEndPrint\n";
base.OnEndPrint(doc, e);
}
}
}
Simple Report Printer
/*
Code revised from chapter 7
GDI+ Custom Controls with Visual C# 2005
By Iulian Serban, Dragos Brezoi, Tiberiu Radu, Adam Ward
Language English
Paperback 272 pages [191mm x 235mm]
Release date July 2006
ISBN 1904811604
Sample chapter
http://www.packtpub.ru/files/1604_CustomControls_SampleChapter.pdf
For More info on GDI+ Custom Control with Microsoft Visual C# book
visit website www.packtpub.ru
*/
using System;
using System.Collections.Generic;
using System.ruponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;
namespace PrintApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Image imageHeader = new Bitmap(50, 50);
Graphics img = Graphics.FromImage(imageHeader);
img.DrawEllipse(Pens.Black, 0, 0, 45, 45);
img.DrawString("LOGO", this.Font, Brushes.Black, new PointF(7, 16));
img.Dispose();
string textDocument;
textDocument = "";
for (int i = 0; i < 60; i++)
{
for (int j = 0; j < i; j++)
textDocument += " ";
textDocument += "The quick brown fox jumps over the lazy dog\n";
}
SimpleReportPrinter printDocument = new SimpleReportPrinter(imageHeader, textDocument, this.Font);
printDocument.Print(false);
}
private System.ruponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// button1
//
this.button1.BackColor = System.Drawing.SystemColors.ActiveCaption;
this.button1.Location = new System.Drawing.Point(95, 107);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(100, 30);
this.button1.TabIndex = 0;
this.button1.Text = "Print";
this.button1.UseVisualStyleBackColor = false;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(292, 266);
this.Controls.Add(this.button1);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Button button1;
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
public class TextDispenser
{
int _start = 0;
string _text = null;
Font _fnt;
public TextDispenser(string text, Font fnt)
{
_start = 0;
_text = text;
_fnt = fnt;
}
public bool DrawText(Graphics target, Graphics measurer, RectangleF r, Brush brsh)
{
if (r.Height < _fnt.Height)
throw new ArgumentException("The rectangle is not tall enough to fit a single line of text inside.");
int charsFit = 0;
int linesFit = 0;
int cut = 0;
string temp = _text.Substring(_start);
StringFormat format = new StringFormat(StringFormatFlags.FitBlackBox | StringFormatFlags.LineLimit);
//measure how much of the string we can fit into the rectangle
measurer.MeasureString(temp, _fnt, r.Size, format, out charsFit, out linesFit);
cut = BreakText(temp, charsFit);
if (cut != charsFit)
temp = temp.Substring(0, cut);
bool h = true;
h &= true;
target.DrawString(temp.Trim(" "), _fnt, brsh, r, format);
_start += cut;
if (_start == _text.Length)
{
_start = 0; //reset the location so we can repeat the document
return true; //finished printing
}
else
return false;
}
private static int BreakText(string text, int approx)
{
if (approx == 0)
throw new ArgumentException();
if (approx < text.Length)
{
//are we in the middle of a word?
if (char.IsLetterOrDigit(text[approx]) && char.IsLetterOrDigit(text[approx - 1]))
{
int temp = text.LastIndexOf(" ", approx, approx + 1);
if (temp >= 0)
return temp;
}
}
return approx;
}
}
public class SimpleReportPrinter
{
Image _header = null;
string _text = null;
int _pageNumber = 0;
PrintDocument _prtdoc = null;
TextDispenser _textDisp = null;
public SimpleReportPrinter(Image header, string text, Font fnt)
{
_header = (Image)(header.Clone());
_text = text;
_prtdoc = new PrintDocument();
_prtdoc.PrintPage += new PrintPageEventHandler(_prtdoc_PrintPage);
_textDisp = new TextDispenser(_text, fnt);
}
public void Print(bool hardcopy)
{
//create a PrintDialog based on the PrintDocument
PrintDialog pdlg = new PrintDialog();
pdlg.Document = _prtdoc;
//show the PrintDialog
if (pdlg.ShowDialog() == DialogResult.OK)
{
//create a PageSetupDialog based on the PrintDocument and PrintDialog
PageSetupDialog psd = new PageSetupDialog();
psd.EnableMetric = true; //Ensure all dialog measurements are in metric
psd.Document = pdlg.Document;
//show the PageSetupDialog
if (psd.ShowDialog() == DialogResult.OK)
{
//apply the settings of both dialogs
_prtdoc.DefaultPageSettings = psd.PageSettings;
//decide what action to take
if (hardcopy)
{
//actually print hardcopy
_prtdoc.Print();
}
else
{
//preview onscreen instead
PrintPreviewDialog prvw = new PrintPreviewDialog();
prvw.Document = _prtdoc;
prvw.ShowDialog();
}
}
}
}
private void _prtdoc_PrintPage(object sender, PrintPageEventArgs e)
{
e.Graphics.Clip = new Region(e.MarginBounds);
//this method does all our printing work
Single x = e.MarginBounds.Left;
Single y = e.MarginBounds.Top;
//draw the header image
if (_pageNumber++ == 0)
{
e.Graphics.DrawImage(_header, x, y);
y += _header.Height + 30;
}
RectangleF mainTextArea = RectangleF.FromLTRB(x, y, e.MarginBounds.Right, e.MarginBounds.Bottom);
//draw the main part of the report
if (_textDisp.DrawText(e.Graphics, e.PageSettings.PrinterSettings.CreateMeasurementGraphics(), mainTextArea, Brushes.Black))
{
e.HasMorePages = false; //the end has been reached
_pageNumber = 0;
}
else
e.HasMorePages = true;
//watermark
e.Graphics.TranslateTransform(200, 200);
e.Graphics.RotateTransform(e.PageSettings.Landscape ? 30 : 60);
e.Graphics.DrawString("CONFIDENTIAL", new Font("Courier New", 75, FontStyle.Bold), new SolidBrush(Color.FromArgb(64, Color.Black)), 0, 0);
}
}
}
UI Print
/*
GDI+ Programming in C# and VB .NET
by Nick Symmonds
Publisher: Apress
ISBN: 159059035X
*/
using System;
using System.Drawing;
using System.Drawing.Text;
using System.Drawing.Drawing2D;
using System.Drawing.Printing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
namespace UIPrint_c
{
public class UIPrint : System.Windows.Forms.Form
{
private PrintPreviewDialog Pv;
private PageSetupDialog Ps;
private PrintDocument Pd;
private PrintDialog Pr;
private System.Windows.Forms.MainMenu mainMenu1;
private System.Windows.Forms.MenuItem mnuFile;
private System.Windows.Forms.MenuItem mnuSetup;
private System.Windows.Forms.MenuItem mnuPreview;
private System.Windows.Forms.MenuItem mnuPrint;
private System.Windows.Forms.Button cmdQuit;
private System.ruponentModel.Container components = null;
public UIPrint()
{
InitializeComponent();
Pv = new PrintPreviewDialog();
Ps = new PageSetupDialog();
Pr = new PrintDialog();
Pd = new PrintDocument();
Pd.DocumentName = "My New Document";
Pv.Document = Pd;
Ps.Document = Pd;
Pr.Document = Pd;
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.mainMenu1 = new System.Windows.Forms.MainMenu();
this.mnuFile = new System.Windows.Forms.MenuItem();
this.mnuSetup = new System.Windows.Forms.MenuItem();
this.mnuPreview = new System.Windows.Forms.MenuItem();
this.mnuPrint = new System.Windows.Forms.MenuItem();
this.cmdQuit = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// mainMenu1
//
this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.mnuFile});
//
// mnuFile
//
this.mnuFile.Index = 0;
this.mnuFile.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.mnuSetup,
this.mnuPreview,
this.mnuPrint});
this.mnuFile.Text = "File";
//
// mnuSetup
//
this.mnuSetup.Index = 0;
this.mnuSetup.Text = "Page Setup";
this.mnuSetup.Click += new System.EventHandler(this.mnuSetup_Click);
//
// mnuPreview
//
this.mnuPreview.Index = 1;
this.mnuPreview.Text = "Print Preview";
this.mnuPreview.Click += new System.EventHandler(this.mnuPreview_Click);
//
// mnuPrint
//
this.mnuPrint.Index = 2;
this.mnuPrint.Text = "Print";
this.mnuPrint.Click += new System.EventHandler(this.mnuPrint_Click);
//
// cmdQuit
//
this.cmdQuit.Location = new System.Drawing.Point(256, 256);
this.cmdQuit.Name = "cmdQuit";
this.cmdQuit.Size = new System.Drawing.Size(64, 32);
this.cmdQuit.TabIndex = 0;
this.cmdQuit.Text = "Quit";
this.cmdQuit.Click += new System.EventHandler(this.cmdQuit_Click);
//
// UIPrint
//
this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(342, 303);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.cmdQuit});
this.MaximizeBox = false;
this.Menu = this.mainMenu1;
this.MinimizeBox = false;
this.Name = "UIPrint";
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "UIPrint";
this.Load += new System.EventHandler(this.UIPrint_Load);
this.ResumeLayout(false);
}
#endregion
[STAThread]
static void Main()
{
Application.Run(new UIPrint());
}
private void UIPrint_Load(object sender, System.EventArgs e)
{
Pd.PrintPage += new PrintPageEventHandler(this.pd_Print);
}
protected override void OnPaint(PaintEventArgs e)
{
DrawIt(e.Graphics);
}
private void DrawIt(Graphics G)
{
G.SmoothingMode = SmoothingMode.AntiAlias;
Pen P1 = new Pen(Brushes.Violet, 5);
G.DrawString("Test of Print dialog and page setup",
new Font("Time New Roman", 16),
Brushes.Blue,
new Point(5, 5));
G.DrawPie(P1, 10, 10, 150, 150, 28, 57);
G.FillEllipse(Brushes.BurlyWood, 10, 200, this.Width-50, 50);
}
private void pd_Print(object sender, PrintPageEventArgs e)
{
DrawIt(e.Graphics);
}
private void mnuSetup_Click(object sender, System.EventArgs e)
{
Ps.ShowDialog();
Pd.DefaultPageSettings = Ps.PageSettings;
Pd.PrinterSettings = Ps.PrinterSettings;
}
private void mnuPreview_Click(object sender, System.EventArgs e)
{
Pv.WindowState = FormWindowState.Maximized;
Pv.ShowDialog();
}
private void mnuPrint_Click(object sender, System.EventArgs e)
{
if (Pr.ShowDialog() == DialogResult.OK)
Pd.Print();
}
private void cmdQuit_Click(object sender, System.EventArgs e)
{
this.Dispose();
}
}
}