使用文件重写功能进行Delphi打印

使用文件重写功能进行Delphi打印

问题描述:

在我的应用程序中,所有打印机均使用 printer.printers 命令列出.仅列出打印机名称.选择后,它将保存在数据库中.

In my application, all printers are listed using printer.printers command. This lists only printer names. Upon selection, it is saved in the Database.

此后,该打印机名称使用 AssignFile 功能分配给文本文件.然后使用 Rewrite 函数完成打印.

Later on, this printer name is assigned using the AssignFilefunction to a text file. And printing is done using Rewrite function.

如果我将选定的打印机另存为数据库中的 \\ PCname \ printer name ,然后将其与 Rewrite 函数一起使用,则它将起作用.

If I save the selected printer as \\PCname\printer name in the database and then use it with Rewrite function then it works.

但是,如果我们仅将打印机名称保存在数据库中,则不会进行打印.是否需要保存 \\ PCname \ printer name 路径?或还有其他解决方案吗?

But if we save only printer name in the database then printing is not happening. Is it necessary to save \\PCname\printer name path? or Is there any other solution.

使用Pascal文件访问功能进行打印的另一种方法是将Windows API用于后台打印程序.

Anotherway than printing using the Pascal file access functions is to use the Windows API for the spooler.

function PrintWithSpooler(const Name: string; const Data: AnsiString): integer;
var
  hPrinter: THandle;
  DocInfo: TDocInfo1;
  bSuccess: boolean;
  dwBytesWritten: DWORD;
begin
  result := S_OK;
  bSuccess := false;

  DocInfo.pOutputFile := nil;
  DocInfo.pDatatype := 'RAW';
  DocInfo.pDocName := 'Label';

  if OpenPrinter(PChar(Trim(Name)), hPrinter, nil) then
  begin
    try
      if StartDocPrinter(hPrinter, 1, @DocInfo) > 0 then
      begin
        try
          if StartPagePrinter(hPrinter) then
          begin
            try
              bSuccess := WritePrinter(hPrinter, Pointer(Data), Length(Data), dwBytesWritten);
            finally
              EndPagePrinter(hPrinter);
            end;
          end;
        finally
          EndDocPrinter(hPrinter);
        end;
      end;
    finally
      ClosePrinter(hPrinter);
    end;
  end;

  if not bSuccess then
  begin
    result := GetLastError;

    // in case there was no error from GetLastError
    if result = S_OK then
      result := S_FALSE;
  end;
end;