/*
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.ComponentModel;
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.ComponentModel.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;
}
}
}
Software Development
software development notes, main category for Cs, Java, and other programming experiences.
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.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;
using System.Drawing.Printing;
namespace GridPrinting
{
///
///
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.ComponentModel.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();
}
///
///
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
///
/// the contents of this method with the code editor.
///
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.ComponentModel.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.ComponentModel.ISupportInitialize)(this.dGrid)).EndInit();
this.ResumeLayout(false);
}
#endregion
///
///
[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_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;
}
}
}
}
}
[/csharp]
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);
}
}
}
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.ComponentModel;
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.ComponentModel.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();
}
}
}
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.ComponentModel;
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.ComponentModel.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() + "
" ;
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();
}
}
}
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.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace BeginPrint_c
{
///
///
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.ComboBox 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.ComponentModel.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
///
/// the contents of this method with the code editor.
///
private void InitializeComponent()
{
this.cmbPrinters = new System.Windows.Forms.ComboBox();
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.ComboBoxStyle.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;
}
}
}
[/csharp]
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://international.us.server12.fileserver.kutayzorlu.com/files/download/2017/01/1604_CustomControls_SampleChapter_uuid-691f9c5b-afac-4710-86fb-20f04521bc6e_crc-0.pdf
For More info on GDI+ Custom Control with Microsoft Visual C# book
visit website www.packtpub.com
*/
using System;
using System.Collections.Generic;
using System.ComponentModel;
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
";
}
SimpleReportPrinter printDocument = new SimpleReportPrinter(imageHeader, textDocument, this.Font);
printDocument.Print(false);
}
private System.ComponentModel.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);
}
}
}