问题
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?
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<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 < 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;
}
}
回答1:
You retrieve the document bytes before the document is finished by closing:
var bytes = memoryStream.ToArray();
var encodedPDF = Convert.ToBase64String(bytes);
document.Close();
Move the close call before the ToArray call.
来源:https://stackoverflow.com/questions/42278162/itextsharp-datatable-to-pdf-base64-string-pdf-damaged