PDFtoolkit VCL
Edit, enhance, secure, merge, split, view, print PDF and AcroForms documents
Compatibility
Delphi C++Builder

Best Programming Practices with PDFtoolkit VCL (Part 1)

Learn how to use methods that return objects in a clean and efficient way.
By Mohammed Najeemudheen

The term memory leak is used to refer to a situation where a computer seems to run out of memory. Free memory on a computer can get exhausted really quickly when programs fail to free memory they have acquired. It is a good programming practice to free memory-allocated objects when the program logic no longer needs them.

To illustrate this, let us take the method GetPageElements() of class TgtExProPDFDocument. This method is used to obtain a list of page elements from a specified page in a PDF document. The method allocates memory for the list object it returns.

In the code snippet below, we load a PDF document and retrieve page elements from each page using GetPageElements(). After processing page elements from a page, we free the memory used by the list.

var
  LPageElementList : TgtPDFPageElementList;
  Item, PageNo : Integer;
begin
  // Load PDF document
  PDFDoc.LoadFromFile('InputFile.pdf');
  // Iterate through all pages in the document
  for PageNo := 1 to PDFDoc.PageCount do
  begin
    // Load all page elements in current page
    // in a page element list
    LPageElementList :=
       PDFDoc.GetPageElements(
                 PageNo,
                 [etText, etImage,etFormField,etPath],
                 muPoints);
    // Process list items
    try
      for Item := 0 to LPageElementList.Count - 1 do
      begin
        ...
      end;
    finally
      // Free list items 
      for Item := 0 to LPageElementList.Count - 1 do 
      begin 
        LPageElementList.Items[Item].Free; 
      end; 
      // Free list 
      FreeAndNil(LPageElementList); 
    end;
  end;
end;

What can happen if you fail to free the list in each of those iterations? Well, if the PDF document has a thousand of pages, GetPageElements() will keep on asking the computer for more memory, as it tries to store page elements from each of those thousand pages. At some point in the iteration, virtual memory will run out and your program will begin to stall.

Thus, it is a good clean programming practice to free objects returned by methods that allocate memory.

Privacy | Legal | Feedback | Newsletter © 2002-2010 Gnostice Information Technologies Private Limited. All rights reserved.

This site is best viewed on a screen with minimum resolution of 1152 x 864 pixels. Windows users are advised to use Microsoft ClearType Tuning for optimal experience. Linux and other users can enable font smoothing, as supported by their OS. Also, please use the latest version of a standards-compliant browser such as Opera, FireFox, Chrome or Safari.