itextSharp datatable to pdf base64 string - pdf damaged

微笑、不失礼 提交于 2021-02-17 05:50:13

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!