`

推荐一款DataGridView的打印解决方案

 
阅读更多


转自:http://www.cnblogs.com/heekui/archive/2007/05/29/764531.html

在CS的WinForm中如何打印DataGridView中的内容。
网上搜索一番之后,还是在藏宝库CodeProject中找到一篇好文章《DataGridView Printing by Selecting Columns and Rows》(http://www.codeproject.com/KB/grid/PrintDataGrid_CS.aspx

效果图
【打印设置画面】



【打印预览画面】


解决方案构成
这个打印解决方案由一个打印设置的窗体,及一个打印类组成。
可用于以下场景:
1、显示的数据量较大,但又没有必要打印全部数据的时候
2、希望打印出的列宽能自动适应页面宽度

打印类主要方法
Print_DataGridView(共有): 被外部类调用的主方法.
PrintDoc_BeginPrint(私有):初始化一些打印变量
PrintDoc_PrintPage(私有):执行打印工作
DrawFooter(私有):页脚的处理部分

打印类代码

/****************************************************
*DataGridView打印类
*原作者:AfrasiabCheraghi.
*修改者:何奎
*
**************************************************
*/


usingSystem;
usingSystem.Collections.Generic;
usingSystem.Windows.Forms;
usingSystem.Drawing;
usingSystem.Collections;
usingSystem.Data;
usingSystem.Text;

namespacetestPrint
{
classPrintDGV
{
privatestaticStringFormatStrFormat;//HoldscontentofaTextBoxCelltowritebyDrawString
privatestaticStringFormatStrFormatComboBox;//HoldscontentofaBooleanCelltowritebyDrawImage
privatestaticButtonCellButton;//HoldstheContentsofButtonCell
privatestaticCheckBoxCellCheckBox;//HoldstheContentsofCheckBoxCell
privatestaticComboBoxCellComboBox;//HoldstheContentsofComboBoxCell

privatestaticintTotalWidth;//SummationofColumnswidths
privatestaticintRowPos;//Positionofcurrentlyprintingrow
privatestaticboolNewPage;//Indicatesifanewpagereached
privatestaticintPageNo;//Numberofpagestoprint
privatestaticArrayListColumnLefts=newArrayList();//LeftCoordinateofColumns
privatestaticArrayListColumnWidths=newArrayList();//WidthofColumns
privatestaticArrayListColumnTypes=newArrayList();//DataTypeofColumns
privatestaticintCellHeight;//HeightofDataGridCell
privatestaticintRowsPerPage;//NumberofRowsperPage
privatestaticSystem.Drawing.Printing.PrintDocumentprintDoc=
newSystem.Drawing.Printing.PrintDocument();//PrintDocumnetObjectusedforprinting

privatestaticstringPrintTitle="";//Headerofpages
privatestaticDataGridViewdgv;//HoldsDataGridViewObjecttoprintitscontents
privatestaticList<string>SelectedColumns=newList<string>();//TheColumnsSelectedbyusertoprint.
privatestaticList<string>AvailableColumns=newList<string>();//AllColumnsavaiableinDataGrid
privatestaticboolPrintAllRows=true;//True=printallrows,False=printselectedrows
privatestaticboolFitToPageWidth=true;//True=Fitsselectedcolumnstopagewidth,False=Printcolumnsasshowed
privatestaticintHeaderHeight=0;

publicstaticvoidPrint_DataGridView(DataGridViewdgv1)
{
PrintPreviewDialogppvw;
try
{
//GettingDataGridViewobjecttoprint
dgv=dgv1;

//GettingallCoulmnsNamesintheDataGridView
AvailableColumns.Clear();
foreach(DataGridViewColumncindgv.Columns)
{
if(!c.Visible)continue;
AvailableColumns.Add(c.HeaderText);
}


//ShowingthePrintOptionForm
PrintOptionsdlg=newPrintOptions(AvailableColumns);
if(dlg.ShowDialog()!=DialogResult.OK)return;

PrintTitle
=dlg.PrintTitle;
PrintAllRows
=dlg.PrintAllRows;
FitToPageWidth
=dlg.FitToPageWidth;
SelectedColumns
=dlg.GetSelectedColumns();

RowsPerPage
=0;

ppvw
=newPrintPreviewDialog();
ppvw.Document
=printDoc;

//ShowingthePrintPreviewPage
printDoc.BeginPrint+=newSystem.Drawing.Printing.PrintEventHandler(PrintDoc_BeginPrint);
printDoc.PrintPage
+=newSystem.Drawing.Printing.PrintPageEventHandler(PrintDoc_PrintPage);
if(ppvw.ShowDialog()!=DialogResult.OK)
{
printDoc.BeginPrint
-=newSystem.Drawing.Printing.PrintEventHandler(PrintDoc_BeginPrint);
printDoc.PrintPage
-=newSystem.Drawing.Printing.PrintPageEventHandler(PrintDoc_PrintPage);
return;
}


//PrintingtheDocumnet
printDoc.Print();
printDoc.BeginPrint
-=newSystem.Drawing.Printing.PrintEventHandler(PrintDoc_BeginPrint);
printDoc.PrintPage
-=newSystem.Drawing.Printing.PrintPageEventHandler(PrintDoc_PrintPage);
}

catch(Exceptionex)
{
MessageBox.Show(ex.Message,
"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
}

finally
{

}

}


privatestaticvoidPrintDoc_BeginPrint(objectsender,
System.Drawing.Printing.PrintEventArgse)
{
try
{
//FormattingtheContentofTextCelltoprint
StrFormat=newStringFormat();
StrFormat.Alignment
=StringAlignment.Near;
StrFormat.LineAlignment
=StringAlignment.Center;
StrFormat.Trimming
=StringTrimming.EllipsisCharacter;

//FormattingtheContentofComboCellstoprint
StrFormatComboBox=newStringFormat();
StrFormatComboBox.LineAlignment
=StringAlignment.Center;
StrFormatComboBox.FormatFlags
=StringFormatFlags.NoWrap;
StrFormatComboBox.Trimming
=StringTrimming.EllipsisCharacter;

ColumnLefts.Clear();
ColumnWidths.Clear();
ColumnTypes.Clear();
CellHeight
=0;
RowsPerPage
=0;

//Forvariouscolumntypes
CellButton=newButton();
CellCheckBox
=newCheckBox();
CellComboBox
=newComboBox();

//CalculatingTotalWidths
TotalWidth=0;
foreach(DataGridViewColumnGridColindgv.Columns)
{
if(!GridCol.Visible)continue;
if(!PrintDGV.SelectedColumns.Contains(GridCol.HeaderText))continue;
TotalWidth
+=GridCol.Width;
}

PageNo
=1;
NewPage
=true;
RowPos
=0;
}

catch(Exceptionex)
{
MessageBox.Show(ex.Message,
"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
}

}


privatestaticvoidPrintDoc_PrintPage(objectsender,
System.Drawing.Printing.PrintPageEventArgse)
{
inttmpWidth,i;
inttmpTop=e.MarginBounds.Top;
inttmpLeft=e.MarginBounds.Left;

try
{
//Beforestartingfirstpage,itsavesWidth&HeightofHeadersandCoulmnType
if(PageNo==1)
{
foreach(DataGridViewColumnGridColindgv.Columns)
{
if(!GridCol.Visible)continue;
//Skipifthecurrentcolumnnotselected
if(!PrintDGV.SelectedColumns.Contains(GridCol.HeaderText))continue;

//Deteminingwhetherthecolumnsarefittedtopageornot.
if(FitToPageWidth)
tmpWidth
=(int)(Math.Floor((double)((double)GridCol.Width/
(
double)TotalWidth*(double)TotalWidth*
((
double)e.MarginBounds.Width/(double)TotalWidth))));
else
tmpWidth
=GridCol.Width;

HeaderHeight
=(int)(e.Graphics.MeasureString(GridCol.HeaderText,
GridCol.InheritedStyle.Font,tmpWidth).Height)
+11;

//Savewidth&heightofheadresandColumnType
ColumnLefts.Add(tmpLeft);
ColumnWidths.Add(tmpWidth);
ColumnTypes.Add(GridCol.GetType());
tmpLeft
+=tmpWidth;
}

}


//PrintingCurrentPage,RowbyRow
while(RowPos<=dgv.Rows.Count-1)
{
DataGridViewRowGridRow
=dgv.Rows[RowPos];
if(GridRow.IsNewRow||(!PrintAllRows&&!GridRow.Selected))
{
RowPos
++;
continue;
}


CellHeight
=GridRow.Height;

if(tmpTop+CellHeight>=e.MarginBounds.Height+e.MarginBounds.Top)
{
DrawFooter(e,RowsPerPage);
NewPage
=true;
PageNo
++;
e.HasMorePages
=true;
return;
}

else
{
if(NewPage)
{
//DrawHeader
e.Graphics.DrawString(PrintTitle,newFont(dgv.Font,FontStyle.Bold),
Brushes.Black,e.MarginBounds.Left,e.MarginBounds.Top
-
e.Graphics.MeasureString(PrintTitle,
newFont(dgv.Font,
FontStyle.Bold),e.MarginBounds.Width).Height
-13);

Strings
=DateTime.Now.ToLongDateString()+""+DateTime.Now.ToShortTimeString();

e.Graphics.DrawString(s,
newFont(dgv.Font,FontStyle.Bold),
Brushes.Black,e.MarginBounds.Left
+(e.MarginBounds.Width-
e.Graphics.MeasureString(s,
newFont(dgv.Font,
FontStyle.Bold),e.MarginBounds.Width).Width),e.MarginBounds.Top
-
e.Graphics.MeasureString(PrintTitle,
newFont(newFont(dgv.Font,
FontStyle.Bold),FontStyle.Bold),e.MarginBounds.Width).Height
-13);

//DrawColumns
tmpTop=e.MarginBounds.Top;
i
=0;
foreach(DataGridViewColumnGridColindgv.Columns)
{
if(!GridCol.Visible)continue;
if(!PrintDGV.SelectedColumns.Contains(GridCol.HeaderText))
continue;

e.Graphics.FillRectangle(
newSolidBrush(Color.LightGray),
newRectangle((int)ColumnLefts[i],tmpTop,
(
int)ColumnWidths[i],HeaderHeight));

e.Graphics.DrawRectangle(Pens.Black,
newRectangle((int)ColumnLefts[i],tmpTop,
(
int)ColumnWidths[i],HeaderHeight));

e.Graphics.DrawString(GridCol.HeaderText,GridCol.InheritedStyle.Font,
newSolidBrush(GridCol.InheritedStyle.ForeColor),
newRectangleF((int)ColumnLefts[i],tmpTop,
(
int)ColumnWidths[i],HeaderHeight),StrFormat);
i
++;
}

NewPage
=false;
tmpTop
+=HeaderHeight;
}


//DrawColumnsContents
i=0;
foreach(DataGridViewCellCelinGridRow.Cells)
{
if(!Cel.OwningColumn.Visible)continue;
if(!SelectedColumns.Contains(Cel.OwningColumn.HeaderText))
continue;

//FortheTextBoxColumn
if(((Type)ColumnTypes[i]).Name=="DataGridViewTextBoxColumn"||
((Type)ColumnTypes[i]).Name
=="DataGridViewLinkColumn")
{
e.Graphics.DrawString(Cel.Value.ToString(),Cel.InheritedStyle.Font,
newSolidBrush(Cel.InheritedStyle.ForeColor),
newRectangleF((int)ColumnLefts[i],(float)tmpTop,
(
int)ColumnWidths[i],(float)CellHeight),StrFormat);
}

//FortheButtonColumn
elseif(((Type)ColumnTypes[i]).Name=="DataGridViewButtonColumn")
{
CellButton.Text
=Cel.Value.ToString();
CellButton.Size
=newSize((int)ColumnWidths[i],CellHeight);
Bitmapbmp
=newBitmap(CellButton.Width,CellButton.Height);
CellButton.DrawToBitmap(bmp,
newRectangle(0,0,
bmp.Width,bmp.Height));
e.Graphics.DrawImage(bmp,
newPoint((int)ColumnLefts[i],tmpTop));
}

//FortheCheckBoxColumn
elseif(((Type)ColumnTypes[i]).Name=="DataGridViewCheckBoxColumn")
{
CellCheckBox.Size
=newSize(14,14);
CellCheckBox.Checked
=(bool)Cel.Value;
Bitmapbmp
=newBitmap((int)ColumnWidths[i],CellHeight);
GraphicstmpGraphics
=Graphics.FromImage(bmp);
tmpGraphics.FillRectangle(Brushes.White,
newRectangle(0,0,
bmp.Width,bmp.Height));
CellCheckBox.DrawToBitmap(bmp,
newRectangle((int)((bmp.Width-CellCheckBox.Width)/2),
(
int)((bmp.Height-CellCheckBox.Height)/2),
CellCheckBox.Width,CellCheckBox.Height));
e.Graphics.DrawImage(bmp,
newPoint((int)ColumnLefts[i],tmpTop));
}

//FortheComboBoxColumn
elseif(((Type)ColumnTypes[i]).Name=="DataGridViewComboBoxColumn")
{
CellComboBox.Size
=newSize((int)ColumnWidths[i],CellHeight);
Bitmapbmp
=newBitmap(CellComboBox.Width,CellComboBox.Height);
CellComboBox.DrawToBitmap(bmp,
newRectangle(0,0,
bmp.Width,bmp.Height));
e.Graphics.DrawImage(bmp,
newPoint((int)ColumnLefts[i],tmpTop));
e.Graphics.DrawString(Cel.Value.ToString(),Cel.InheritedStyle.Font,
newSolidBrush(Cel.InheritedStyle.ForeColor),
newRectangleF((int)ColumnLefts[i]+1,tmpTop,(int)ColumnWidths[i]
-16,CellHeight),StrFormatComboBox);
}

//FortheImageColumn
elseif(((Type)ColumnTypes[i]).Name=="DataGridViewImageColumn")
{
RectangleCelSize
=newRectangle((int)ColumnLefts[i],
tmpTop,(
int)ColumnWidths[i],CellHeight);
SizeImgSize
=((Image)(Cel.FormattedValue)).Size;
e.Graphics.DrawImage((Image)Cel.FormattedValue,
newRectangle((int)ColumnLefts[i]+(int)((CelSize.Width-ImgSize.Width)/2),
tmpTop
+(int)((CelSize.Height-ImgSize.Height)/2),
((Image)(Cel.FormattedValue)).Width,((Image)(Cel.FormattedValue)).Height));

}


//DrawingCellsBorders
e.Graphics.DrawRectangle(Pens.Black,newRectangle((int)ColumnLefts[i],
tmpTop,(
int)ColumnWidths[i],CellHeight));

i
++;

}

tmpTop
+=CellHeight;
}


RowPos
++;
//ForthefirstpageitcalculatesRowsperPage
if(PageNo==1)RowsPerPage++;
}


if(RowsPerPage==0)return;

//WriteFooter(PageNumber)
DrawFooter(e,RowsPerPage);

e.HasMorePages
=false;
}

catch(Exceptionex)
{
MessageBox.Show(ex.Message,
"Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
}

}


privatestaticvoidDrawFooter(System.Drawing.Printing.PrintPageEventArgse,
intRowsPerPage)
{
doublecnt=0;

//Deteminingrowsnumbertoprint
if(PrintAllRows)
{
if(dgv.Rows[dgv.Rows.Count-1].IsNewRow)
cnt
=dgv.Rows.Count-2;//WhentheDataGridViewdoesn'tallowaddingrows
else
cnt
=dgv.Rows.Count-1;//WhentheDataGridViewallowsaddingrows
}

else
cnt
=dgv.SelectedRows.Count;

//WritingthePageNumberontheBottomofPage
stringPageNum=""+PageNo.ToString()
+"页,共"+Math.Ceiling((double)(cnt/RowsPerPage)).ToString()
+"";

e.Graphics.DrawString(PageNum,dgv.Font,Brushes.Black,
e.MarginBounds.Left
+(e.MarginBounds.Width-
e.Graphics.MeasureString(PageNum,dgv.Font,
e.MarginBounds.Width).Width)
/2,e.MarginBounds.Top+
e.MarginBounds.Height
+31);
}

}

}


示例工程下载:
testPrint

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics