procedure printdbgrid(dg:tdbgrid);
var
pl,pr,pt,pb:integer;//页边距
px,py:integer;//打印机分辨率
ps:integer;//打印机与显示器分辨率之比
lh:integer;//行高
i:integer;
x,y:integer;//打印坐标
rowb,colb:integer;//行距,列距
begin
//初始化界面
pl:=1;
pr:=1;
pt:=1;
pb:=1;
rowb:=6;
colb:=6;
//将打印机的分辨率由厘米转换为英寸
px:=trunc(GetDeviceCaps(printer.handle,LOGPIXELSX)/2.54);
py:=trunc(GetDeviceCaps(printer.handle,LOGPIXELSY)/2.54);
//将屏幕分辨率转换为打印机
ps:=trunc(GetDeviceCaps(printer.handle,LOGPIXELSY)/screen.PixelsPerInch);
//设置打印方向
Printer.Orientation:=poPortrait;//纵向打印
//获得打印机的字体和大小
Printer.Canvas.Font.Name:='宋体';
Printer.Canvas.Font.Size:=10;
Printer.Canvas.Font.Color:=clRed;
Printer.Canvas.Pen.Color:=clBlue;
//设置行高
lh:=Printer.Canvas.TextHeight(dg.Font.Name);
//打印的起始位置(打印机画布上的位置)
x:=px*pl;
y:=py*pl;
//打印dbgrid的内容
if (dg.DataSource.DataSet.Active) and (dg.DataSource.DataSet.RecordCount>0) then
begin
//设置打印机的标题
printer.Title:='表格内容打印';
with printerdo
begin
begin
doc;
dg.DataSource.DataSet.First;
while not dg.DataSource.DataSet.Eofdo
begin
for i:=0 to dg.FieldCount -1do
begin
//设定打印的宽度
if (x+dg.Columns.Items.Width*ps)<=(pagewidth-px*pr) then
begin
//画出表格线
printer.Canvas.Rectangle(x,y,x+dg.Columns.Items.Width*ps,y+lh);
//如果第一行,打印db的标题
if y=py*pt then
canvas.TextOut(x+rowb,y+colb,dg.Columns.Items.Title.Caption)
else
//其他行打印每行的内容
printer.Canvas.TextOut(x+rowb,y+colb,dg.Fields.AsString);
end;
//下一列的横坐标,下一列的纵坐标不变
x:=x+dg.Columns.Items.Width*ps;
end;
//打印下一记录
if not (y=py*pt) then
dg.DataSource.DataSet.Next;
x:=px*pl;//打印下一行时,横坐标回到行首
y:=y+lh;
//打印满一页时,新建一页
if (y+lh)>(pageheight-py*pr) then
begin
newpage;
x:=px*pl;
y:=py*pt;
end;
end;
EndDoc;
end;
end;
end;
上面的有些变量你可以写个配置窗口配置一下,也可以直接用.