title: C# generated PDF files doesn't open in PDF readers. Error shows damaged or corrupt file
body: <p>I am trying to save imageData as pdf file on server directory. Html5Canvas imageData was sent to server and after conversion in bytes array, tried to save as PDF file. File generated successfully on specified path but the generated file doesn't open correctly in most of the PDF readers(i.e. Adobe Reader, Foxit reader etc) and show error that file is either damaged or corrupt but it open correctly in MS Edge browser. I want them to show in common PDF reader too. Can you please suggest the solution. Here is my server side code.</p>
  
  <pre><code>public static string SaveImage(string imageData, string userEmail, int quantity)
      {
          string completePath = @"~\user-images\";
          string imageName = "sample_file2.pdf";
          string fileNameWitPath = completePath + imageName;
          byte[] bytes = Convert.FromBase64String(imageData);
          File.WriteAllBytes(HttpContext.Current.Server.MapPath(fileNameWitPath), bytes);
      }
  </code></pre>
  
  <p>Same output generated for this code</p>
  
  <pre><code>        FileStream fs = new FileStream(HttpContext.Current.Server.MapPath(fileNameWitPath), FileMode.OpenOrCreate);
          fs.Write(bytes, 0, bytes.Length);
          fs.Close();
  </code></pre>
  
  <p>and for this too.</p>
  
  <pre><code> using (FileStream fs = new FileStream(HttpContext.Current.Server.MapPath(fileNameWitPath), FileMode.Create))
          {
  
              using (BinaryWriter bw = new BinaryWriter(fs))
              {
  
                  byte[] data = Convert.FromBase64String(imageData);
  
                  bw.Write(data);
  
                  bw.Close();
              }
  
          }
  </code></pre>