Repeatedly open and close a PDF document to perform various operations
IMO there is a problem with the try...catch statement. If an exception is thrown you'll have to deal with communicating the error to the client. You can't rethrow it because then the Save() and Close() aren't called, so you'll have to have a kind of logging or event to notify through and that could make it all unnecessarily complicated. Besides that: if an exception is thrown, you may not want to save the document in an unknown state, but you should close it anyway.

You can handle that in the following way:

  try
  {
    perform(loadedDocument);
    loadedDocument.Save();
  }
  finally
  {
    loadedDocument.Close();
  }


Here the document is only saved if the process went well, but closed in any case. And the caller can handle the exception as needed.



Alternatively you can make a wrapper like:

  class PdfDocumentExecuter : IDisposable
  {
    private PdfLoadedDocument document;

    public PdfDocumentExecuter(string fileName)
    {
      document = new PdfLoadedDocument(fileName);
    }

    public void Execute(Action&lt;PdfLoadedDocument&gt; action)
    {
      action(document);
      document.Save();
    }

    public T Execute&lt;T&gt;(Func&lt;PdfLoadedDocument, T&gt; function)
    {
      T result = function(document);
      document.Save();
      return result;
    }

    public void Dispose()
    {
      if (document != null)
      {
        document.Close();
        document = null;
      }
    }
  }


called as:

  using (PdfDocumentExecuter executer = new PdfDocumentExecuter("path"))
  {
    annotations = executer.Execute(Build);
  }