Warm tip: This article is reproduced from serverfault.com, please click

Delphi Printing using file rewrite function

发布于 2021-01-15 06:38:20

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

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

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

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.

Questioner
poonam
Viewed
0
Delphi Coder 2021-01-15 20:12:47

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;