itextSharp数据表转换为pdf base64字符串-pdf损坏 [英] itextSharp datatable to pdf base64 string - pdf damaged
本文介绍了itextSharp数据表转换为pdf base64字符串-pdf损坏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从数据表中获取pdf并将其附加到CRM中的实体.为此,我使用此代码.不幸的是,创建的pdf损坏了,我无法打开它.有什么想法吗?
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;
}
}
推荐答案
您可以通过关闭文件来在文档完成之前检索文档字节:
You retrieve the document bytes before the document is finished by closing:
var bytes = memoryStream.ToArray();
var encodedPDF = Convert.ToBase64String(bytes);
document.Close();
将关闭调用移到ToArray调用之前.
Move the close call before the ToArray call.
这篇关于itextSharp数据表转换为pdf base64字符串-pdf损坏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文