如何使用delphi发送测试页打印到打印机?

时间:2011-03-04 21:02:56

标签: delphi printing

实际上我正在一个需要在特定打印机上打印测试页的项目中工作。测试页必须与选项打印机属性中的Windows打印相同 - >打印测试页。

我如何在德尔福中做到这一点?

2 个答案:

答案 0 :(得分:13)

此代码将打印默认打印机的测试页:

uses ShellAPI, printers;
{$R *.dfm}

procedure TForm2.Button1Click(Sender: TObject);
var
  Device, Driver, Port: Array [0..255] of Char;
  hDevMode: THandle;
begin
  Printer.GetPrinter(Device, Driver, Port, hDevmode);
  ShInvokePrinterCommand(handle, PRINTACTION_TESTPAGE, Device, nil, true );
end;

结果: Printer test page

享受:)

答案 1 :(得分:6)

您可以使用PrintTestPage wmi类

中的Win32_Printer方法

检查此示例

{$APPTYPE CONSOLE}

uses
  SysUtils,
  ActiveX,
  ComObj;

procedure  PrintTestPage(const PrinterName:string);
var
  FSWbemLocator : OLEVariant;
  FWMIService   : OLEVariant;
  FWbemObjectSet: OLEVariant;
  FWbemObject   : OLEVariant;
  oEnum         : IEnumvariant;
  iValue        : LongWord;
  PrintResult   : Integer;
begin;
  FSWbemLocator := CreateOleObject('WbemScripting.SWbemLocator');
  FWMIService   := FSWbemLocator.ConnectServer('localhost', 'root\CIMV2', '', '');
  FWbemObjectSet:= FWMIService.ExecQuery(Format('SELECT * FROM Win32_Printer Where Name="%s"',[PrinterName]),'WQL',0);
  oEnum         := IUnknown(FWbemObjectSet._NewEnum) as IEnumVariant;
  if oEnum.Next(1, FWbemObject, iValue) = 0 then
  begin
    PrintResult:=FWbemObject.PrintTestPage;
    if PrintResult=0 then
     Writeln('Success')
    else
     Writeln('An error occurred');
  end;
end;


begin
 try
    CoInitialize(nil);
    try
      PrintTestPage('MyPrinter');
    finally
      CoUninitialize;
    end;
 except
    on E:Exception do
        Writeln(E.Classname, ':', E.Message);
 end;

 Readln;
end.