首页  编辑  

添加打印任务的例子

Tags: /超级猛料/Print.打印/   Date Created:

添加打印任务的例子

uses printers, winspool;

{$R *.DFM}

{-- GetCurrentPrinterHandle

-------------------------------------------}

{: Retrieves the handle of the current printer

@Returns an API printer handle for the current printer

@Desc Uses WinSpool.OpenPrinter to get a printer handle. The caller

 takes ownership of the handle and <b>must</b> call ClosePrinter on it

 once the handle is no longer needed. Failing to do that creates a

 serious resource leak! <P>

 Requires Printers and WinSpool in the Uses clause.

@Raises EWin32Error if the OpenPrinter call fails.

}{ Created 30.9.2000 by P. Below

-----------------------------------------------------------------------

}

function GetCurrentPrinterHandle: THandle;

const

 Defaults: TPrinterDefaults = (

   pDatatype : nil;

   pDevMode  : nil;

   DesiredAccess : PRINTER_ACCESS_USE or PRINTER_ACCESS_ADMINISTER );

var

 Device, Driver, Port : array[0..255] of char;

 hDeviceMode: THandle;

begin { GetCurrentPrinterHandle }

 Printer.GetPrinter(Device, Driver, Port, hDeviceMode);

 Win32Check( OpenPrinter(@Device, Result, @Defaults));

end; { GetCurrentPrinterHandle }

{ Create and schedule a print job on the selected printer and store

 the passed streams content to the spool file.

 Returns the jobs ID, which the caller can use to check on the jobs

 status. }

function CreatePrintjob( aStream: TStream ): Cardinal;

var

 Printerhandle: THandle;

 JobData: record

   JobInfo: TAddJobInfo1;

   SpoolfilePath: array [0..MAX_PATH] of char;

 end;

 Dummy: Cardinal;

 Fs: TFileStream;

begin

 Printerhandle := GetCurrentPrinterHandle;

 try

   FillChar( JobData, Sizeof(JobData), 0);

   Win32Check(

     Winspool.AddJob(

       Printerhandle, 1, @JobData, Sizeof( JobData ), Dummy ));

   Fs:= TFileStream.Create( JobData.JobInfo.Path, fmCreate );

   try

     aStream.Position := 0;

     Fs.Copyfrom( aStream, aStream.Size );

     FlushFileBuffers( Fs.Handle );

   finally

     Fs.Free;

   end; { Finally }

   Win32Check(

     WinSpool.ScheduleJob( Printerhandle, JobData.JobInfo.JobId ));

   Result := JobData.JobInfo.JobId;

 finally

   ClosePrinter( Printerhandle );

 end; { Finally }

end;

procedure TForm1.Button1Click(Sender: TObject);

var

 sl: TStringlist;

 ms: TMemoryStream;

 ch: Char;

begin

 if not PrintDialog1.Execute then

   Exit;

 sl:= TStringlist.Create;

 try

   sl.Assign( memo1.lines );

   ms:= TMemoryStream.Create;

   try

     sl.SaveToStream(ms);

     ch:= #12;  // form feed to eject final page

     ms.Write(ch, 1);

     CreatePrintjob( ms );

   finally

     ms.Free;

   end; { Finally }

 finally

   sl.Free;

 end; { Finally }

end;