When loading large PDF document, OutOfMemory error happens. How do I deal with it?

In this case you should handle 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 TElPDFDocument.PDFFile.OnCreateTemporaryStream event handler is fired on saving the document when the document is reassembled (for example during document encryption).

Sample code

VCL

  1. PDFDocument.OnCreateTemporaryStream := DoCreateTemporaryStream;
  2. PDFDocument.PDFFile.OnCreateTemporaryStream := DoCreateTemporaryStream;
  3. <span class="function"><span class="keyword">procedure</span> <span class="title">TfrmMain</span>.<span class="title">DoCreateTemporaryStream</span><span class="params">(Sender: TObject; <span class="keyword">var</span> Stream: </span></span>
  4. TStream; <span class="keyword">var</span> FreeOnClose : Boolean);
  5. <span class="keyword">begin</span>
  6. Stream := TFileStream.Create(GenerateTempFilename, fmOpenReadWrite <span class="keyword">or</span>
  7. fmShareDenyWrite)
  8. FreeOnClose := True;
  9. <span class="keyword">end</span>;

VB.NET

  1. <span class="keyword">AddHandler</span> PDFDocument.OnCreateTemporaryStream, <span class="keyword">AddressOf</span>
  2. HandleCreateTemporaryStream <span class="comment">' on opening document</span>
  3. <span class="keyword">AddHandler</span> PDFDocument.PDFFile.OnCreateTemporaryStream, <span class="keyword">AddressOf</span>
  4. HandleCreateTemporaryStream <span class="comment">' on saving</span>
  5. <span class="keyword">Private</span> <span class="keyword">Sub</span> HandleCreateTemporaryStream(sender <span class="keyword">As</span> <span class="keyword">Object</span>, <span class="keyword">ByRef</span> stream
  6. <span class="keyword">As</span> IO.Stream, <span class="keyword">ByRef</span> freeOnClose <span class="keyword">As</span> <span class="keyword">Boolean</span>)
  7. stream = <span class="keyword">New</span> FileStream(IO.Path.GetTempFileName, FileMode.Create)
  8. freeOnClose = <span class="literal">True</span>
  9. <span class="keyword">End</span> <span class="keyword">Sub</span>

Ready to get started?

Learn more about SecureBlackbox or download a free trial.

Download Now