SecureBlackbox 16: How to Resolve OutOfMemory Errors when Loading Large PDF Documents

Note: This article applies only to SecureBlackbox Legacy. For future development please consider using the latest version.

In this case you should handle the TElPDFDocument.OnCreateTemporaryStream and/or TElPDFDocument.PDFFile.OnCreateTemporaryStream events, create a temporary file on the disk inside the handler, and then return the corresponding FileStream/TFileStream object back to the component. If the event is not handled, a memory stream is internally created and used. This can lead to out-of-memory exceptions on large files.

The TElPDFDocument.OnCreateTemporaryStream event handler is fired when the document is loaded, and the TElPDFDocument.PDFFile.OnCreateTemporaryStream event handler is fired on saving the document when the document is reassembled (for example during document encryption).

Sample code

VCL

PDFDocument.OnCreateTemporaryStream := DoCreateTemporaryStream;
PDFDocument.PDFFile.OnCreateTemporaryStream := DoCreateTemporaryStream;

procedure TfrmMain.DoCreateTemporaryStream(Sender: TObject; var Stream:
TStream; var FreeOnClose : boolean);
begin
   Stream := TFileStream.Create(GenerateTempFilename, fmOpenReadWrite or
fmShareDenyWrite)
   FreeOnClose := True;
end;

VB.NET

AddHandler PDFDocument.OnCreateTemporaryStream, AddressOf
HandleCreateTemporaryStream ' on opening document
AddHandler PDFDocument.PDFFile.OnCreateTemporaryStream, AddressOf
HandleCreateTemporaryStream ' on saving

Private Sub HandleCreateTemporaryStream(sender As Object, ByRef stream
As IO.Stream, ByRef freeOnClose As Boolean)
   stream = New FileStream(IO.Path.GetTempFileName, FileMode.Create)
   freeOnClose = True
End Sub

We appreciate your feedback.  If you have any questions, comments, or suggestions about this article please contact our support team at kb@nsoftware.com.