Created
January 22, 2015 12:33
-
-
Save viniciusjarina/cc6b4cc37bbd1c175132 to your computer and use it in GitHub Desktop.
PrintDataGridView
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Runtime.InteropServices; | |
using System.ComponentModel; | |
using System.Drawing; | |
using System.Drawing.Printing; | |
using System.Windows.Forms; | |
namespace LibComponentes | |
{ | |
public class ReportHeadersTypeConverter : ExpandableObjectConverter | |
{ | |
public override bool GetCreateInstanceSupported(ITypeDescriptorContext context) | |
{ | |
return true; | |
} | |
public override object CreateInstance(ITypeDescriptorContext context, System.Collections.IDictionary propertyValues) | |
{ | |
return new ReportHeaders((string)propertyValues["Main"], | |
(string)propertyValues["Sub"]);//, | |
//(Font)propertyValues["MainFont"], | |
//(Font)propertyValues["SubFont"]); | |
} | |
} | |
[Serializable] | |
[ComVisible(true)] | |
// [TypeConverter(typeof(ReportHeadersTypeConverter))] | |
[TypeConverter(typeof(ExpandableObjectConverter))] | |
[DesignTimeVisible(false)] | |
public class ReportHeaders | |
{ | |
private string _Main; | |
private string _Sub; | |
private Font _MainFont; | |
private Font _SubFont; | |
[Description("Cabeçalho principal da página")] | |
public string Main | |
{ | |
get { return _Main; } | |
set { _Main = value; } | |
} | |
[Description("Sub-título da ágina")] | |
public string Sub | |
{ | |
get { return _Sub; } | |
set { _Sub = value; } | |
} | |
[Description("Fonte do cabeçalho principal da página")] | |
public Font MainFont | |
{ | |
get { return _MainFont; } | |
set { _MainFont = (Font)value.Clone(); } | |
} | |
[Description("Fonte do cabeçalho sub-título da página")] | |
public Font SubFont | |
{ | |
get { return _SubFont; } | |
set { _SubFont = (Font)value.Clone(); } | |
} | |
public ReportHeaders() | |
{ | |
_Main = "Main Title"; | |
_Sub = "Sub Title"; | |
_MainFont = new Font("Arial", 14, FontStyle.Bold); | |
_SubFont = new Font("Arial", 12, FontStyle.Bold); | |
} | |
public ReportHeaders(string main, string sub) | |
{ | |
_Main = main; | |
_Sub = sub; | |
_MainFont = new Font("Arial", 14, FontStyle.Bold); | |
_SubFont = new Font("Arial", 12, FontStyle.Bold); | |
} | |
public ReportHeaders(string main, string sub, Font mainFont, Font subFont) | |
{ | |
_Main = main; | |
_Sub = sub; | |
MainFont = mainFont; | |
SubFont = subFont; | |
} | |
~ReportHeaders() | |
{ | |
_MainFont.Dispose(); | |
_SubFont.Dispose(); | |
} | |
public override string ToString() | |
{ | |
return "[" + Main + "]" + ";" + "[" + Sub + "]";// +";" + MainFont.ToString() + ";" + SubFont.ToString(); | |
} | |
} | |
public class PrintDataGridView : Component | |
{ | |
private struct GridColsToPageCols | |
{ | |
public float Left; | |
public float Width; | |
public GridColsToPageCols(float left, float width) | |
{ | |
Left = left; | |
Width = width; | |
} | |
} | |
private DataGridView _dataGridView; | |
private PrintDocument _printDocument; | |
private PrintPreviewDialog _printPreviewDialog; | |
private PageSetupDialog _pageSetupDialog; | |
private List<GridColsToPageCols> lstColPos = new List<GridColsToPageCols>(); | |
private float _yPos; | |
public float YPos | |
{ | |
get { return _yPos; } | |
set { _yPos = value; } | |
} | |
private float _xPos; | |
private float _margTop; | |
private float _dpiXGrid; | |
private bool _striped; | |
private Color _stripedColor; | |
//--------------------------------------- Eventos | |
public event PrintPageEventHandler PrintSummary; // fim do relatório | |
public event PrintPageEventHandler BeforePrintColumnHeader; | |
public event PrintPageEventHandler AfterPrintColumnHeader; | |
//--------------------------------------- Eventos | |
public float MargTop | |
{ | |
get { return _margTop; } | |
set { _margTop = value; } | |
} | |
private float _margLeft; | |
public float MargLeft | |
{ | |
get { return _margLeft; } | |
set { _margLeft = value; } | |
} | |
private float _margBottom; | |
public float MargBottom | |
{ | |
get { return _margBottom; } | |
set { _margBottom = value; } | |
} | |
private ReportHeaders _reportHeaders; | |
private int rowIndex; | |
[Category("Principais")] | |
[Description("DataGridView que terá os seus dados impresso")] | |
public DataGridView DataGridView | |
{ | |
get { return _dataGridView; } | |
set { _dataGridView = value; } | |
} | |
[Category("Principais")] | |
[Description("Cabeçalho de página")] | |
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)] | |
public ReportHeaders Headers | |
{ | |
get { return _reportHeaders; } | |
set { _reportHeaders = value; } | |
} | |
[Category("Principais")] | |
[Description("Define se a impressão será zebrada (listrada) ou não")] | |
public bool Striped | |
{ | |
get { return _striped; } | |
set { _striped = value; } | |
} | |
[Category("Principais")] | |
[Description("Cor de fundo das listras")] | |
public Color StripedColor | |
{ | |
get { return _stripedColor; } | |
set { _stripedColor = value; } | |
} | |
public PrintDataGridView() | |
{ | |
_printDocument = new PrintDocument(); | |
_printPreviewDialog = new PrintPreviewDialog(); | |
_pageSetupDialog = new PageSetupDialog(); | |
_pageSetupDialog.Document = _printDocument; | |
_printPreviewDialog.Document = _printDocument; | |
_striped = true; | |
_stripedColor = Color.FromArgb(200, 200, 200); | |
_reportHeaders = new ReportHeaders(); | |
_reportHeaders.Main = "Main Title"; | |
_reportHeaders.Sub = "Sub Title"; | |
_printDocument.PrintPage += new PrintPageEventHandler(printDocument_PrintPage); | |
_margTop = 20; | |
_margLeft = 20; | |
_margBottom = 20; | |
} | |
private void CalcColPos() | |
{ | |
float x = _margLeft; | |
Graphics g = _dataGridView.CreateGraphics(); | |
_dpiXGrid = g.DpiX; | |
lstColPos.Clear(); | |
x = _margLeft; | |
for (int i = 0; i < _dataGridView.Columns.Count; i++) | |
{ | |
if (_dataGridView.Columns[i].Visible) | |
{ | |
// largura da coluna do grid em pontos | |
float w = _dataGridView.Columns[i].Width; | |
// converte para polegada | |
w = w / _dpiXGrid; | |
// converte para milímetros | |
w = (float)(w * 25.4); | |
// adiciona na lista | |
lstColPos.Add(new GridColsToPageCols(x, w)); | |
x += w; | |
} | |
} | |
} | |
// imprime o cabeçalho de página | |
private void PrintHeader(PrintPageEventArgs e, Brush br) | |
{ | |
SizeF s; | |
string data; | |
//--------------------- Imprimir cabeçalho de página ---------------------- | |
//-- TÍTULO PRINCIPAL | |
_yPos = _margTop; | |
// mede o tamanho do título | |
s = e.Graphics.MeasureString(_reportHeaders.Main, _reportHeaders.MainFont); | |
// imprime centralizado | |
e.Graphics.DrawString(_reportHeaders.Main, _reportHeaders.MainFont, br, | |
(float)(25.4 * e.PageBounds.Width / 100 - s.Width) / 2, _yPos); | |
//-- SUB-TÍTULO | |
_yPos += s.Height; | |
// mede o tamanho do título | |
s = e.Graphics.MeasureString(_reportHeaders.Sub, _reportHeaders.SubFont); | |
// imprime centralizado | |
e.Graphics.DrawString(_reportHeaders.Sub, _reportHeaders.SubFont, br, | |
(float)(25.4 * e.PageBounds.Width / 100 - s.Width) / 2, _yPos); | |
// -- TÍTULOS DE COLUNA | |
_yPos += s.Height + 2; | |
s = e.Graphics.MeasureString("AAA", _dataGridView.ColumnHeadersDefaultCellStyle.Font); | |
int idxLst = 0; | |
//--------------------- verificando se existe método no evento | |
if (BeforePrintColumnHeader != null) | |
BeforePrintColumnHeader(this, e); | |
//------------------------------------------------------------ | |
for (int i = 0; i < _dataGridView.Columns.Count; i++) | |
{ | |
if (_dataGridView.Columns[i].Visible) | |
{ | |
data = _dataGridView.Columns[i].HeaderText; | |
s = e.Graphics.MeasureString(data, _dataGridView.ColumnHeadersDefaultCellStyle.Font); | |
if (_dataGridView.Columns[i].DefaultCellStyle.Alignment == DataGridViewContentAlignment.MiddleRight || | |
_dataGridView.Columns[i].DefaultCellStyle.Alignment == DataGridViewContentAlignment.BottomRight || | |
_dataGridView.Columns[i].DefaultCellStyle.Alignment == DataGridViewContentAlignment.TopRight) | |
{ | |
_xPos = lstColPos[idxLst].Left + lstColPos[idxLst].Width - s.Width; | |
} | |
else if (_dataGridView.Columns[i].DefaultCellStyle.Alignment == DataGridViewContentAlignment.MiddleCenter || | |
_dataGridView.Columns[i].DefaultCellStyle.Alignment == DataGridViewContentAlignment.BottomCenter || | |
_dataGridView.Columns[i].DefaultCellStyle.Alignment == DataGridViewContentAlignment.TopCenter) | |
{ | |
_xPos = lstColPos[idxLst].Left + (lstColPos[idxLst].Width - s.Width) / 2; | |
} | |
else | |
_xPos = lstColPos[idxLst].Left; | |
e.Graphics.DrawString(data, _dataGridView.ColumnHeadersDefaultCellStyle.Font, | |
br, _xPos, _yPos); | |
idxLst++; | |
} | |
} | |
_yPos += s.Height + 1; | |
//--------------------- verificando se existe método no evento | |
if (AfterPrintColumnHeader != null) | |
AfterPrintColumnHeader(this, e); | |
//------------------------------------------------------------ | |
} | |
private void printDocument_PrintPage(object sender, PrintPageEventArgs e) | |
{ | |
Brush br = Brushes.Black; | |
string data; | |
SizeF s; | |
_margLeft = (float)25.4 * e.MarginBounds.Left / 100; | |
_margTop = (float)25.4 * e.MarginBounds.Top / 100; | |
e.Graphics.PageUnit = GraphicsUnit.Millimeter; | |
PrintHeader(e, br); | |
s = e.Graphics.MeasureString("AAA", _dataGridView.DefaultCellStyle.Font); | |
while (rowIndex < _dataGridView.Rows.Count) | |
{ | |
int idxLst = 0; | |
if (_striped) | |
{ | |
if ((rowIndex % 2) == 0) | |
e.Graphics.FillRectangle(new SolidBrush(_stripedColor), _margLeft, _yPos, (float)25.4 * e.MarginBounds.Width / 100, _yPos + s.Height); | |
else | |
e.Graphics.FillRectangle(new SolidBrush(_dataGridView.DefaultCellStyle.BackColor), _margLeft, _yPos, (float)25.4 * e.MarginBounds.Width / 100, _yPos + s.Height); | |
} | |
for (int c = 0; c < _dataGridView.Columns.Count; c++) | |
{ | |
if (_dataGridView.Columns[c].Visible) | |
{ | |
data = (_dataGridView.Rows[rowIndex].Cells[c].Value == null ? "" : | |
_dataGridView.Rows[rowIndex].Cells[c].FormattedValue.ToString()); | |
s = e.Graphics.MeasureString(data, _dataGridView.DefaultCellStyle.Font); | |
if (_dataGridView.Columns[c].DefaultCellStyle.Alignment == DataGridViewContentAlignment.MiddleRight || | |
_dataGridView.Columns[c].DefaultCellStyle.Alignment == DataGridViewContentAlignment.BottomRight || | |
_dataGridView.Columns[c].DefaultCellStyle.Alignment == DataGridViewContentAlignment.TopRight) | |
{ | |
_xPos = lstColPos[idxLst].Left + lstColPos[idxLst].Width - s.Width; | |
} | |
else if (_dataGridView.Columns[c].DefaultCellStyle.Alignment == DataGridViewContentAlignment.MiddleCenter || | |
_dataGridView.Columns[c].DefaultCellStyle.Alignment == DataGridViewContentAlignment.BottomCenter || | |
_dataGridView.Columns[c].DefaultCellStyle.Alignment == DataGridViewContentAlignment.TopCenter) | |
{ | |
_xPos = lstColPos[idxLst].Left + (lstColPos[idxLst].Width - s.Width) / 2; | |
} | |
else | |
_xPos = lstColPos[idxLst].Left; | |
e.Graphics.DrawString(data, _dataGridView.DefaultCellStyle.Font, | |
br, _xPos, _yPos); | |
idxLst++; | |
} | |
} | |
_yPos += s.Height; | |
rowIndex++; | |
if (_yPos > 25.4 * e.MarginBounds.Height / 100 - _margBottom) | |
break; | |
} | |
e.Graphics.FillRectangle(new SolidBrush(_dataGridView.DefaultCellStyle.BackColor), _margLeft, _yPos, (float)25.4 * e.MarginBounds.Width / 100, _yPos + s.Height); | |
e.HasMorePages = rowIndex < _dataGridView.Rows.Count - 1; | |
//---------- Se acabou o relatório E tem método em PrintSummary | |
if (!e.HasMorePages && PrintSummary != null) | |
PrintSummary(this, e); | |
} | |
public void Preview() | |
{ | |
if (_pageSetupDialog.ShowDialog() == DialogResult.OK) | |
{ | |
rowIndex = 0; | |
CalcColPos(); | |
_printPreviewDialog.WindowState = FormWindowState.Maximized; | |
_printPreviewDialog.ShowDialog(); | |
} | |
} | |
public void Print() | |
{ | |
if (_pageSetupDialog.ShowDialog() == DialogResult.OK) | |
{ | |
rowIndex = 0; | |
CalcColPos(); | |
_printDocument.Print(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment