using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Drawing;
using System.Collections;
using System.Data;
using System.Text;
namespace DgPrint
{
public class PrintService
{
private StringFormat StrFormat; // Holds content of a TextBox Cell to write by DrawString
private int RowPos;
// Position of currentlyprinting row
private bool NewPage;
// Indicates if a new page reached
private int PageNo;
// Number of pages to print
private int CellHeight;
// Height of DataGrid Cell
private int RowsPerPage;
// Number of Rows per Page
private System.Drawing.Printing.PrintDocument printDoc =
new System.Drawing.Printing.PrintDocument(); // PrintDocumnet Object used for printing
private ArrayList ColumnLefts = new ArrayList(); // Left Coordinate of Columns
private ArrayList ColumnWidths = new ArrayList(); // Width of Columns
private string PrintTitle = ""; // Header of pages
private DataTable dgv;
// Holds DataGridView Object to print its contents
private List<string> AvailableColumns = new List<string>(); // All Columns avaiable in DataGrid
private int HeaderHeight = 0;
private Dictionary<string, int> ColWith;
public void Print(DataTable tab, string Title, Dictionary<string, int> colWith)
{
PrintPreviewDialog ppvw;
try
{
// Getting DataGridView object to print
dgv = tab;
ColWith = colWith;
// Getting all Coulmns Names in the DataGridView
AvailableColumns.Clear();
foreach (DataColumn c in dgv.Columns)
{
AvailableColumns.Add(c.ColumnName);
}
// Showing the PrintOption Form
PrintTitle = Title;
RowsPerPage = 0;
printDoc.DocumentName = " ";
PrintDialog dia = new PrintDialog();
dia.PrintToFile = false;
dia.Document = printDoc;
dia.UseEXDialog = true;
if (dia.ShowDialog() != DialogResult.OK) return;
ppvw = new PrintPreviewDialog();
ppvw.WindowState = FormWindowState.Maximized;
ppvw.Document = printDoc;
// Showing the Print Preview Page
printDoc.BeginPrint += new System.Drawing.Printing.PrintEventHandler(PrintDoc_BeginPrint);
printDoc.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(PrintDoc_PrintPage);
if (ppvw.ShowDialog() != DialogResult.OK)
{
printDoc.BeginPrint -= new System.Drawing.Printing.PrintEventHandler(PrintDoc_BeginPrint);
printDoc.PrintPage -= new System.Drawing.Printing.PrintPageEventHandler(PrintDoc_PrintPage);
return;
}
// Printing the Documnet
printDoc.Print();
printDoc.BeginPrint -= new System.Drawing.Printing.PrintEventHandler(PrintDoc_BeginPrint);
printDoc.PrintPage -= new System.Drawing.Printing.PrintPageEventHandler(PrintDoc_PrintPage);
}
catch (Exception ex)
{
}
finally
{
}
}
private DataGridView grid;
public void Print(DataGridView grid, string Title)
{
PrintPreviewDialog ppvw;
try
{
// Getting DataGridView object to print
this.grid = grid;
// Getting all Coulmns Names in the DataGridView
AvailableColumns.Clear();
foreach (DataGridViewColumn c in grid.Columns)
{
if (c.Visible)
AvailableColumns.Add(c.HeaderText);
}
// Showing the PrintOption Form
PrintTitle = Title;
RowsPerPage = 0;
printDoc.DocumentName = " ";
PrintDialog dia = new PrintDialog();
dia.PrintToFile = false;
dia.Document = printDoc;
dia.UseEXDialog = true;
if (dia.ShowDialog() != DialogResult.OK) return;
ppvw = new PrintPreviewDialog();
ppvw.WindowState = FormWindowState.Maximized;
ppvw.Document = printDoc;
// Showing the Print Preview Page
printDoc.BeginPrint += new System.Drawing.Printing.PrintEventHandler(PrintGridDoc_BeginPrint);
printDoc.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(PrintGridDoc_PrintPage);
if (ppvw.ShowDialog() != DialogResult.OK)
{
printDoc.BeginPrint -= new System.Drawing.Printing.PrintEventHandler(PrintGridDoc_BeginPrint);
printDoc.PrintPage -= new System.Drawing.Printing.PrintPageEventHandler(PrintGridDoc_PrintPage);
return;
}
// Printing the Documnet
printDoc.Print();
printDoc.BeginPrint -= new System.Drawing.Printing.PrintEventHandler(PrintGridDoc_BeginPrint);
printDoc.PrintPage -= new System.Drawing.Printing.PrintPageEventHandler(PrintGridDoc_PrintPage);
}
catch (Exception ex)
{
}
finally
{
}
}
private void PrintGridDoc_BeginPrint(object sender,
System.Drawing.Printing.PrintEventArgs e)
{
try
{
StrFormat = new StringFormat();
StrFormat.Alignment = StringAlignment.Near;
StrFormat.LineAlignment = StringAlignment.Center;
StrFormat.Trimming = StringTrimming.EllipsisCharacter;
ColumnLefts.Clear();
ColumnWidths.Clear();
CellHeight = 0;
RowsPerPage = 0;
PageNo = 1;
NewPage = true;
RowPos = 0;
}
catch (Exception ex)
{
}
}
private void PrintGridDoc_PrintPage(object sender,
System.Drawing.Printing.PrintPageEventArgs e)
{
int tmpWidth, i;
int tmpTop = e.MarginBounds.Top;
int tmpLeft = e.MarginBounds.Left;
Font font = new Font("宋体", 9);
try
{
// Before starting first page, it saves Width & Height of Headers and CoulmnType
if (PageNo == 1)
{
foreach (DataGridViewColumn GridCol in grid.Columns)
{
// Skip if the current column not selected
// Detemining whether the columns are fitted to page or not.
if (GridCol.Visible)
{
tmpWidth = GridCol.Width;
HeaderHeight = 33;
// Save width & height of headres and ColumnType
ColumnLefts.Add(tmpLeft);
ColumnWidths.Add(tmpWidth);
tmpLeft += tmpWidth;
}
}
}
// Printing Current Page, Row by Row
while (RowPos <= grid.Rows.Count - 1)
{
DataGridViewRow GridRow = grid.Rows[RowPos];
CellHeight = 22;
if (tmpTop + CellHeight >= e.MarginBounds.Height + e.MarginBounds.Top)
{
DrawGridFooter(e, RowsPerPage);
NewPage = true;
PageNo++;
e.HasMorePages = true;
return;
}
else
{
if (NewPage)
{
// Draw Header
e.Graphics.DrawString(PrintTitle, new Font(font, FontStyle.Bold),
Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top -
e.Graphics.MeasureString(PrintTitle, new Font(font,
FontStyle.Bold), e.MarginBounds.Width).Height - 13);
String s = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToShortTimeString();
e.Graphics.DrawString(s, new Font(font, FontStyle.Bold),
Brushes.Black, e.MarginBounds.Left + (e.MarginBounds.Width -
e.Graphics.MeasureString(s, new Font(font,
FontStyle.Bold), e.MarginBounds.Width).Width), e.MarginBounds.Top -
e.Graphics.MeasureString(PrintTitle, new Font(new Font(font,
FontStyle.Bold), FontStyle.Bold), e.MarginBounds.Width).Height - 13);
// Draw Columns
tmpTop = e.MarginBounds.Top;
i = 0;
foreach (DataGridViewColumn GridCol in grid.Columns)
{
e.Graphics.FillRectangle(new SolidBrush(Color.LightGray),
new Rectangle((int)ColumnLefts[i], tmpTop,
(int)ColumnWidths[i], HeaderHeight));
e.Graphics.DrawRectangle(Pens.Black,
new Rectangle((int)ColumnLefts[i], tmpTop,
(int)ColumnWidths[i], HeaderHeight));
e.Graphics.DrawString(GridCol.HeaderText, font,
new SolidBrush(Color.Black),
new RectangleF((int)ColumnLefts[i], tmpTop,
(int)ColumnWidths[i], HeaderHeight), StrFormat);
i++;
}
NewPage = false;
tmpTop += HeaderHeight;
}
// Draw Columns Contents
i = 0;
foreach (DataGridViewCell Cel in GridRow.Cells)
{
e.Graphics.DrawString(Cel.Value.ToString(), font,
new SolidBrush(Color.Black),
new RectangleF((int)ColumnLefts[i], (float)tmpTop,
(int)ColumnWidths[i], (float)CellHeight), StrFormat);
// Drawing Cells Borders
e.Graphics.DrawRectangle(Pens.Black, new Rectangle((int)ColumnLefts[i],
tmpTop, (int)ColumnWidths[i], CellHeight));
i++;
}
tmpTop += CellHeight;
}
RowPos++;
// For the first page it calculates Rows per Page
if (PageNo == 1) RowsPerPage++;
}
if (RowsPerPage == 0) return;
// Write Footer (Page Number)
DrawGridFooter(e, RowsPerPage);
e.HasMorePages = false;
printDoc.DocumentName = PrintTitle;
}
catch (Exception ex)
{
}
}
private void DrawGridFooter(System.Drawing.Printing.PrintPageEventArgs e,
int RowsPerPage)
{
double cnt = 0;
cnt = grid.Rows.Count; // When the DataGridView allows adding rows
// Writing the Page Number on the Bottom of Page
string PageNum = " 第 " + PageNo.ToString()
+ " 页,共 " + Math.Ceiling((double)(cnt / RowsPerPage)).ToString()
+ " 页";
Font font = new Font("宋体", 9);
e.Graphics.DrawString(PageNum, font, Brushes.Black,
e.MarginBounds.Left + (e.MarginBounds.Width -
e.Graphics.MeasureString(PageNum, font,
e.MarginBounds.Width).Width) / 2, e.MarginBounds.Top +
e.MarginBounds.Height + 31);
}
private void PrintDoc_BeginPrint(object sender,
System.Drawing.Printing.PrintEventArgs e)
{
try
{
StrFormat = new StringFormat();
StrFormat.Alignment = StringAlignment.Near;
StrFormat.LineAlignment = StringAlignment.Center;
StrFormat.Trimming = StringTrimming.EllipsisCharacter;
ColumnLefts.Clear();
ColumnWidths.Clear();
CellHeight = 0;
RowsPerPage = 0;
PageNo = 1;
NewPage = true;
RowPos = 0;
}
catch (Exception ex)
{
}
}
private void PrintDoc_PrintPage(object sender,
System.Drawing.Printing.PrintPageEventArgs e)
{
int tmpWidth, i;
int tmpTop = e.MarginBounds.Top;
int tmpLeft = e.MarginBounds.Left;
Font font = new Font("宋体", 9);
try
{
// Before starting first page, it saves Width & Height of Headers and CoulmnType
if (PageNo == 1)
{
foreach (DataColumn GridCol in dgv.Columns)
{
// Skip if the current column not selected
// Detemining whether the columns are fitted to page or not.
if (ColWith.ContainsKey(GridCol.ColumnName))
tmpWidth = ColWith[GridCol.ColumnName];
else
tmpWidth = 100;
HeaderHeight = 33;
// Save width & height of headres and ColumnType
ColumnLefts.Add(tmpLeft);
ColumnWidths.Add(tmpWidth);
tmpLeft += tmpWidth;
}
}
// Printing Current Page, Row by Row
while (RowPos <= dgv.Rows.Count - 1)
{
DataRow GridRow = dgv.Rows[RowPos];
CellHeight = 22;
if (tmpTop + CellHeight >= e.MarginBounds.Height + e.MarginBounds.Top)
{
DrawFooter(e, RowsPerPage);
NewPage = true;
PageNo++;
e.HasMorePages = true;
return;
}
else
{
if (NewPage)
{
// Draw Header
e.Graphics.DrawString(PrintTitle, new Font(font, FontStyle.Bold),
Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top -
e.Graphics.MeasureString(PrintTitle, new Font(font,
FontStyle.Bold), e.MarginBounds.Width).Height - 13);
String s = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToShortTimeString();
e.Graphics.DrawString(s, new Font(font, FontStyle.Bold),
Brushes.Black, e.MarginBounds.Left + (e.MarginBounds.Width -
e.Graphics.MeasureString(s, new Font(font,
FontStyle.Bold), e.MarginBounds.Width).Width), e.MarginBounds.Top -
e.Graphics.MeasureString(PrintTitle, new Font(new Font(font,
FontStyle.Bold), FontStyle.Bold), e.MarginBounds.Width).Height - 13);
// Draw Columns
tmpTop = e.MarginBounds.Top;
i = 0;
foreach (DataColumn GridCol in dgv.Columns)
{
e.Graphics.FillRectangle(new SolidBrush(Color.LightGray),
new Rectangle((int)ColumnLefts[i], tmpTop,
(int)ColumnWidths[i], HeaderHeight));
e.Graphics.DrawRectangle(Pens.Black,
new Rectangle((int)ColumnLefts[i], tmpTop,
(int)ColumnWidths[i], HeaderHeight));
e.Graphics.DrawString(GridCol.ColumnName, font,
new SolidBrush(Color.Black),
new RectangleF((int)ColumnLefts[i], tmpTop,
(int)ColumnWidths[i], HeaderHeight), StrFormat);
i++;
}
NewPage = false;
tmpTop += HeaderHeight;
}
// Draw Columns Contents
i = 0;
foreach (Object Cel in GridRow.ItemArray)
{
e.Graphics.DrawString(Cel.ToString(), font,
new SolidBrush(Color.Black),
new RectangleF((int)ColumnLefts[i], (float)tmpTop,
(int)ColumnWidths[i], (float)CellHeight), StrFormat);
// Drawing Cells Borders
e.Graphics.DrawRectangle(Pens.Black, new Rectangle((int)ColumnLefts[i],
tmpTop, (int)ColumnWidths[i], CellHeight));
i++;
}
tmpTop += CellHeight;
}
RowPos++;
// For the first page it calculates Rows per Page
if (PageNo == 1) RowsPerPage++;
}
if (RowsPerPage == 0) return;
// Write Footer (Page Number)
DrawFooter(e, RowsPerPage);
e.HasMorePages = false;
printDoc.DocumentName = PrintTitle;
}
catch (Exception ex)
{
}
}
private void DrawFooter(System.Drawing.Printing.PrintPageEventArgs e,
int RowsPerPage)
{
double cnt = 0;
cnt = dgv.Rows.Count; // When the DataGridView allows adding rows
// Writing the Page Number on the Bottom of Page
string PageNum = " 第 " + PageNo.ToString()
+ " 页,共 " + Math.Ceiling((double)(cnt / RowsPerPage)).ToString()
+ " 页";
Font font = new Font("宋体", 9);
e.Graphics.DrawString(PageNum, font, Brushes.Black,
e.MarginBounds.Left + (e.MarginBounds.Width -
e.Graphics.MeasureString(PageNum, font,
e.MarginBounds.Width).Width) / 2, e.MarginBounds.Top +
e.MarginBounds.Height + 31);
}
}
}