title: Opening password-protected pdf file with iTextSharp
body: <p>I'm making an application that should display PDFs with password. This is my code:</p>
  
  <pre><code>protected void Page_Load(object sender, EventArgs e)
  {
      if (!Page.IsPostBack)
      {
          try
          {
              string filePath = Request.QueryString["filePath"];
              if (filePath.ToUpper().EndsWith("PDF"))
              {
                  copyPDF(filePath);
              }
          }
          catch
          {
              string message = "&lt;script language='Javascript'&gt;alert('File Not Found! Call Records Department for verification. ')&lt;/script&gt;";
              ScriptManager.RegisterStartupScript(Page, this.GetType(), message, message, false);
          }
      }
  }
  public void copyPDF(string filePath)
  {
      iTextSharp.text.pdf.RandomAccessFileOrArray ra = new iTextSharp.text.pdf.RandomAccessFileOrArray(Server.MapPath(ResolveUrl(filePath)));
      if (ra != null)
      {
          System.IO.MemoryStream ms = new System.IO.MemoryStream();
          byte[] password = System.Text.ASCIIEncoding.ASCII.GetBytes("Secretinfo");
          iTextSharp.text.pdf.PdfReader thepdfReader = new iTextSharp.text.pdf.PdfReader(ra, password);
          int pages = thepdfReader.NumberOfPages;
          iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document();
          iTextSharp.text.pdf.PdfCopy pdfCopy = new iTextSharp.text.pdf.PdfCopy(pdfDoc, ms);
  
          pdfDoc.Open();
          int i = 0;
          while (i &lt; pages)
          {
              pdfCopy.AddPage(pdfCopy.GetImportedPage(thepdfReader, i + 1));
              i += 1;
          }
          pdfDoc.Close();
          Byte[] byteInfo = ms.ToArray();
          Response.Clear();
          Response.ContentType = "application/pdf";
          Response.AddHeader("content-length", byteInfo.Length.ToString());
          Response.BinaryWrite(byteInfo);
          Response.Flush();
          Response.End();
      }
  }
  </code></pre>
  
  <p>My code has no problem opening pdf files without password but it can't open pdfs with password even though the password is supplied. The application executes the catch instead. What seems to be wrong with my code?</p>
  
  <p><strong>EDIT</strong>:
  I removed the <em>Catch</em> to see the exception thrown.</p>
  
  <blockquote>
    <p><strong>Exception Details</strong>: System.ArgumentException: PdfReader not opened with owner password</p>
  </blockquote>
  
  <p>It says the source of the error is Line 51.</p>
  
  <pre><code>Line 49:    while (i &lt; pages)
  Line 50:    {
  Line 51:         pdfCopy.AddPage(pdfCopy.GetImportedPage(thepdfReader, i + 1));
  Line 52:         i += 1;
  Line 53:    }
  </code></pre>