筆者設計了一段程序。首先在窗體上添加一個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;