笔者设计了一段程序。首先在窗体上添加一个DBGrid来显示我们所要打印的数据,在这里,DBGrid不只是起到显示数据的作用,而且用户对DBGrid作的调整,例如改变了各字段的排列顺序,各字段的显示宽度等,都将直接反映到打印结果中去,也就是说,我们实际上就是要把DBGrid的内容直接输出到打印机。以下程序在Win 98+Delphi 4下编译通过,代码如下:
procedure TForm1.Button2Click(Sender: TObject);const LeftBlank=1; //定义页边距,单位厘米 RightBlank=1; TopBlank=1; BottomBlank=1;var PointX,PointY:integer; PointScale,PrintStep:integer; s:string; x,y:integer; i:integer;begin //获取当前打印机的分辨率PointX:=Trunc(GetDeviceCaps(Printer.Handle,LOGPIXELSX)/2.54); PointY:=Trunc(GetDeviceCaps(Printer.Handle,LOGPIXELSY)/2.54); //根据打印机和屏幕的分辨率计算出从屏幕转换到打印机的比例 PointScale:=Trunc(GetDeviceCaps(Printer.Handle,LOGPIXELSX)/Screen.PixelsPerInch+0.5); //横向打印 printer.Orientation:=poLandscape; //打印的字体和大小 printer.Canvas.Font.Name:=′宋体′; printer.canvas.Font.Size:=10; //根据字体的大小确定每行的高度 s:=′漳州市刑警支队′; PrintStep:=printer.canvas.TextHeight(s)+16; //打印的起点位置 x:=PointX*LeftBlank; y:=PointY*TopBlank; //DataSource1是DBGrid1所连接的数据源 if ((DataSource1.DataSet).Active=true) and ((DataSource1.DataSet).RecordCount〉0) then begin printer.BeginDoc; (DataSo e1.DataSet).First; while not (DataSource1.DataSet).Eof do begin //打印DBGrid中的所有列 for i:=0 to DBGrid1.FieldCount-1 do begin //假如所要打印的列超出了打印范围,则忽略该列 if (x+DBGrid1.Columns.Items[i].Width*PointScale)〈=(Printer.PageWidth-PointX*RightBlank) then begin //画表格线//每页的第一行打印表头 Printer.Canvas.Rectangle(x,y,x+DBGrid1.Columns.Items[i].Width*PointScale,y+PrintStep); if y=PointY*TopBlank then Printer.Canvas.TextOut(x+8,y+8,DBGrid1.Columns[i].Title.Caption) else Printer.Canvas.TextOut(x+8,y+8,DBGrid1.Fields[i].asString); end; //计算下一列的横坐标 x:=x+DBGrid1.Columns.Items[i].Width*PointScale; end; if not (y=PointY*TopBlank) then(DataSource1.DataSet).next; x:=PointX*LeftBlank; y:=y+PrintStep; //换页 if (y+PrintStep)〉(Printer.PageHeight-PointY*BottomBlank) then begin Printer.NewPage; y:=PointY*TopBlank; end; end; printer.EndDoc; (DataSource1.DataSet).First; Application.MessageBox(′打印完成′,′打印′,32); end;end;(本文来源于图老师网站,更多请访问http://m.tulaoshi.com/bianchengyuyan/)