The author designed a program. First, add a dbgrid on the form to display the data we want to print, here, DBGrid not only plays a role in displaying data, but also the user's adjustments to the DBGrid, such as changing the order of each field, the display width of each field, and so on, will be directly reflected in the print results, that is to say , we're actually just going to output the DBGrid content directly to the printer. The following program is compiled under Win 98+delphi 4 with the following code:
procedure Tform1.button2click (sender:tobject);
Const
leftblank=1; Define margin, unit cm
rightblank=1;
topblank=1;
bottomblank=1;
var
Pointx,pointy:integer;
Pointscale,printstep:integer;
s:string;
X,y:integer;
I:integer;
Begin//Get the resolution of the current printer
Pointx:=trunc (GetDeviceCaps (printer.handle,logpixelsx)/2.54);
Pointy:=trunc (GetDeviceCaps (printer.handle,logpixelsy)/2.54);
//To calculate the ratio from screen to printer based on printer and screen resolution
Pointscale:=trunc (GetDeviceCaps (printer.handle,logpixelsx)
/screen.pixelsperinch+0.5); Horizontal Print
Printer. Orientation:=polandscape;
//Print fonts and sizes
printer. canvas.font.name:=′ song body;
printer.canvas.font.size:=10;
//Depending on the size of the font to determine the height of each row
s:=′ Zhangzhou Interpol detachment;
Printstep:=printer.canvas.textheight (s) +16;
//Print start position
X:=pointx*leftblank;
Y:=pointy*topblank;
//datasource1 is the data source that DBGRID1 is connected to
if ((Datasource1.dataset). Active=true) and ((Datasource1.dataset). recordcount〉0) Then
begin
printer. Begindoc;
(Dataso E1. DataSet). A;
while not (Datasource1.dataset). Eof do
Begin//Print all columns in the DBGrid
for i:=0 to Dbgrid1.fieldcount-1 do
begin
//If the column you want to print is outside the print range, ignore the column
if (X+dbgrid1.columns.items[i]. Width*pointscale) 〈= (Printer.pagewidth-pointx*rightblank) then
Begin//Draw form line
//The first line of each page prints the header
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; Calculate the horizontal axis of the next column
X:=x+dbgrid1.columns.items[i]. Width*pointscale;
end;
if not (Y=pointy*topblank) then
(Datasource1.dataset). Next;
X:=pointx*leftblank;
Y:=y+printstep; Change Page
if (y+printstep) (Printer.pageheight-pointy*bottomblank) then
begin
Printer.newpage;
Y:=pointy*topblank;
end;
end;
printer. EndDoc;
(Datasource1.dataset). A;
Application.messagebox (′,′ printing complete print ′,32);
end;
end;