使用Windows打印后台处理程序的API,我们可以打印出XPS文件。
问题是,打印后台处理程序忽略 默认的打印机设置 。
(我们已经放弃了尝试应用打印机设置 。默认打印机设置将不得不就够了。)
例如...打印输出总是出来的颜色和每一个页纸张,无论什么设置在控制面板设置为:黑白/彩色,双面打印/双面不是每纸上打印多页/单页每片。
如MS Word和Adobe等应用尊重默认的打印机设置。
我们采用Delphi XE2和Windows 7 64位。
这个测试代码是自包含的,所以你可以将其粘贴到测试...
填充使用的打印机名称组合框:
uses
Printers
ComboBox1.Items.Assign(Printer.Printers);
打印步骤:
uses
Winapi.WinSpool
procedure PrintXPS(PrinterName, FileNameXPS: string; ParentFormHandle: THandle = 0);
// Printer handle
procedure Printer_Open(out Printer: THandle; Defaults: PPrinterDefaultsW = nil);
begin
if not OpenPrinterW(PWideChar(PrinterName), Printer, Defaults) then
RaiseLastOSError;
end;
procedure Printer_Close(Printer: THandle);
begin
if not ClosePrinter(Printer) then
RaiseLastOSError;
end;
// Print jobs
function JobCreate(Printer: THandle; FileName: string): Cardinal;
var
lBufferSize: Cardinal;
lAddJobInfo: PAddJobInfo1W;
begin
// Create job
AddJobW(Printer, 1, nil, 0, lBufferSize);
GetMem(lAddJobInfo, lBufferSize);
try
if not AddJobW(Printer, 1, lAddJobInfo, lBufferSize, lBufferSize) then
RaiseLastOSError;
Result := lAddJobInfo.JobId;
// Copy the file into place
CopyFile(PWideChar(FileName), lAddJobInfo.Path, True);
finally
FreeMem(lAddJobInfo, lBufferSize);
end;
end;
procedure JobStart(Printer: THandle; JobID: Cardinal);
begin
if not ScheduleJob(Printer, JobID) then
RaiseLastOSError;
end;
var
PrinterA: THandle;
JobID: Cardinal;
begin
if not FileExists(FileNameXPS) then
raise Exception.Create('File not found: ' + FileNameXPS);
Printer_Open(PrinterA, nil);
try
JobID := JobCreate(PrinterA, FileNameXPS);
JobStart(PrinterA, JobID);
finally
Printer_Close(PrinterA);
end;
end;