title: itextSharp datatable to pdf base64 string - pdf damaged
body: <p>I am trying to get a pdf from datatable and attach it to an entity in CRM. For that purpose I use this code. Unfortunately created pdf is broken, I am unable to open it. Any ideas?</p>
  
  <pre><code>private static string ExportToBase64Pdf(DataTable dt, string entityName)
      {
          using (MemoryStream memoryStream = new MemoryStream())
          {
              Document document = new Document(PageSize.A4);
              PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
              document.Open();
              Font font5 = FontFactory.GetFont(FontFactory.HELVETICA, 5);
  
              PdfPTable table = new PdfPTable(dt.Columns.Count);
              float[] widths = new float[dt.Columns.Count];
  
              for (int i =0; i&lt;dt.Columns.Count; i++) { widths[i] = 4f; }
              table.SetWidths(widths);
              table.WidthPercentage = 100;
  
              PdfPCell cell = new PdfPCell(new Phrase(entityName));
  
              cell.Colspan = dt.Columns.Count;
  
              foreach (DataColumn c in dt.Columns)
              {
                  table.AddCell(new Phrase(c.ColumnName, font5));
              }
  
              foreach (DataRow r in dt.Rows)
              {
                  for (int i = 0; i &lt; dt.Columns.Count; i++)
                  {
                      table.AddCell(new Phrase(r[i].ToString(), font5));
                  }
              }
              document.Add(table);
  
              var bytes = memoryStream.ToArray();
              var encodedPDF = Convert.ToBase64String(bytes);
  
              document.Close();
              return encodedPDF;
          }
      }
  </code></pre>