title: iText PDFReader Extremely Slow To Open
body: <p>I have some code that combines a few pages of acro forms (with acrofields in tact) and then at the end writes some JS to the entire document.</p>
  
  <p>It is the <code>PdfReader</code> in the function adding the JS that is taking extremely long to instantiate (about 12 seconds for a 1MB file).</p>
  
  <p>Here is the code (pretty simple):</p>
  
  <pre><code>public static byte[] AddJavascript(byte[] document, string js)
      {
          PdfReader reader = new PdfReader(new RandomAccessFileOrArray(document), null);
          MemoryStream msOutput = new MemoryStream();
          PdfStamper stamper = new PdfStamper(reader, msOutput);
          PdfWriter writer = stamper.Writer;
  
          writer.AddJavaScript(js);
  
          stamper.Close();
          reader.Close();
  
          byte[] withJS = msOutput.GetBuffer();
          return withJS;
      }
  </code></pre>
  
  <p>I have benchmarked the above and the line that is slow is the first one.  I have tried reading it from a file instead of memory and tried using a <code>MemoryStream</code> instead of the <code>RandomAccessFileOrArray</code>.  Nothing makes it any faster.</p>
  
  <p>If I add JS to a single page document, it is very fast.  So my thought is that the code that combines the pages is somehow making the PDF slow to read for the <code>PdfReader</code>.  </p>
  
  <p>Here is the combine code:</p>
  
  <pre><code>public static byte[] CombineFiles(List&lt;byte[]&gt; sourceFiles)
      {
          MemoryStream output = new MemoryStream();
  
          PdfCopyFields copier = new PdfCopyFields(output);
  
          try
          {
              output.Position = 0;
  
              foreach (var fileBytes in sourceFiles)
              {
                  PdfReader fileReader = new PdfReader(fileBytes);
  
                  copier.AddDocument(fileReader);
              }
          }
          catch (Exception exception)
          {
              //throw
          }
          finally
          {
              copier.Close();
          }
  
          byte[] concat = output.GetBuffer();
  
          return concat;
      }
  </code></pre>
  
  <p>I am using <code>PdfCopyFields</code> because I need to preserve the form fields and so cannot use the <code>PdfCopy</code> or <code>PdfSmartCopy</code>.  This combine code is very fast (few ms) and produces working documents.  The AddJS code above is called after it and the <code>PdfReader</code> open is the slow piece.</p>
  
  <p>Any ideas?</p>