I have a soap method that on the fly creates and respond with a PDF content.
On method finally
, the temporary pdf file It is deleted.
It is finally
the right place for perform this operation?
procedure TWbModule.WbModuleGetPDFAction(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean);
var
aPDFFileTemp : string;
begin
try
// getTempPdf() creates and returns the PDF path, eg.: C:\files\foo.pdf
aPDFFileTemp := getTempPdf();
// set response content stream with file stream
Response.ContentStream := TFileStream.Create(aPDFFileTemp, fmOpenRead or fmShareDenyNone);
Response.ContentType := 'application/pdf';
finally
// delete temporary file
// It is the right place for perform this operation?
if FileExists(aPDFFileTemp) then DeleteFile(aPDFFileTemp );
end;
end;
If you only want to have a temporary file then you should create it as a temporary file.
This class creates a stream with a temporary and self destructing file.
uses
System.Classes;
type
TTempFileStream = class( THandleStream )
public
constructor Create( );
destructor Destroy; override;
end;
implementation
uses
System.IOUtils,
System.SysUtils,
Winapi.Windows;
{ TTempFileStream }
constructor TTempFileStream.Create;
var
fileName : string;
fileHandle: THandle;
begin
fileName := TPath.GetTempFileName( );
fileHandle := CreateFile(
PChar( fileName ),
GENERIC_ALL,
0,
nil,
CREATE_ALWAYS,
FILE_ATTRIBUTE_TEMPORARY or FILE_FLAG_DELETE_ON_CLOSE,
0 );
if fileHandle = INVALID_HANDLE_VALUE
then
RaiseLastOSError( GetLastError, sLineBreak + fileName );
inherited Create( fileHandle );
end;
destructor TTempFileStream.Destroy;
begin
CloseHandle( Handle );
inherited;
end;
The best option would be to write the data (PDF content) into this TTempFileStream
and return the instance from getTempPdf()
function getTempPdf() : TStream;
begin
Result := TTempFileStream.Create;
// create the PDF document and write into the result stream
end;
procedure TWbModule.WbModuleGetPDFAction(Sender: TObject; Request: TWebRequest; Response: TWebResponse; var Handled: Boolean);
begin
Response.ContentStream := getTempPdf();
Response.ContentType := 'application/pdf';
end;
When the response is sent the stream will be freed and the file will be deleted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With