以下可以满足你:(记得给分)我在我的管理系统中使用的,没有问题。
procedure TMainForm.printdbgrid(var datasource1: tdatasource;
var dbgrid1: tdbgrid);
const //定义页边距,单位厘米
LeftBlank=1;
RightBlank=1;
TopBlank=1;
BottomBlank=1;
var
PointX,PointY:integer;
PointScale,PrintStep:integer;
s:string;
x,y,i:integer;
begin
Application.MessageBox('打印开始','打印',32);
//获取当前打印机的分辨率
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:=combobox1.text;
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
//(DataSource1.DataSet).DisableControls;
printer.begin
Doc;
//2002.50.28 新增 2句
printer.Canvas.TextOut(floor((printer.pagewidth)/2)-10,y,panel3.caption);
y:=y+printstep;
(DataSource1.DataSet).First;
while not (DataSource1.DataSet).Eofdo
begin
//打印DBGrid中的所有列
for i:=0 to DBGrid1.FieldCount-1do
begin
//假如所要打印的列超出了打印范围,则忽略该列
if (x+DBGrid1.Columns.Items.Width*PointScale)<=(Printer.PageWidth-PointX*RightBlank) then
begin
//画表格线
//每页的第一行打印表头
Printer.Canvas.Rectangle(x,y,x+DBGrid1.Columns.Items.Width*PointScale,y+PrintStep);
if y=(PointY*TopBlank)+printstep then
//2002.5.28新增printstep
Printer.Canvas.TextOut(x+8,y+8,DBGrid1.Columns.Title.Caption)
else
Printer.Canvas.TextOut(x+8,y+8,DBGrid1.Fields.asString);
end;
//计算下一列的横坐标
x:=x+DBGrid1.Columns.Items.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;
(DataSource1.DataSet).EnableControls;
Application.MessageBox('打印完成','打印',32);
end;
end;