Search code examples
delphi-7indy

How to respond with a pdf for browser with idhttpserver?


I' have a server application made in delphi7, i'm using idhttpserver and when a user of my website requests a report via GET passing parameters, i wish response to this client with a pdf version of report, how could i do that?


Solution

  • You have to generate the PDF report yourself, that is outside of Indy's scope. Just make sure you do it in a thread-safe manner, as TIdHTTPServer is a multi-threaded component that uses worker threads to process client requests.

    In the TIdHTTPServer.OnCommandGet event, you can access the requested parameters via the ARequestInfo.Params property if TIdHTTPServer.ParseParams is true, otherwise you can manually parse the value of the ARequestInfo.QueryParams property. To send the report back to the client, you can either:

    1. save the report to a .pdf file and then call the AResponseInfo.ServeFile() method. For example:

      procedure TForm1.IdHTTPServer1CommandGet(AContext: TIdContext;
        ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
      begin
         // handle request parameters...
         // generate PDF to file...
         AResponseInfo.ServeFile(AContext, 'C:\path to\report.pdf');
      end;
      
    2. save the report to a TStream object, assign that to the AResponseInfo.ContentStream property (TIdHTTPServer will take ownership of it), and set the AResponseInfo.ContentType property to 'application/pdf'. For example:

      procedure TForm1.IdHTTPServer1CommandGet(AContext: TIdContext;
        ARequestInfo: TIdHTTPRequestInfo; AResponseInfo: TIdHTTPResponseInfo);
      begin
         // handle request parameters...
         AResponseInfo.ContentType := 'application/pdf';
         AResponseInfo.ContentStream := TMemoryStream.Create;
         // generate PDF into ContentStream...
      end;