使用 Windows Print Spooler 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;