首页 > 解决方案 > 在 Web API 中将数十万条数据表记录转换为 PDF

问题描述

我正在尝试使用 ADO.Net 从 Web api 中的 DataTable 创建 PDF。不幸的是,有时基于过滤器,我可能会获得非常少的记录并且能够毫无问题地下载。有时可能非常庞大,例如 20 万条记录。当我在本地检查我的系统时,它在将 dt 转换为 PDF 时挂起。我的代码如下:

private FileContentResult ExportPDF(DataTable dataTable)
{
    string Name = "Logs";
    System.IO.MemoryStream mStream = new System.IO.MemoryStream();
    byte[] content = null;
    try
    {
        string[] columnNames = (from dc in dataTable.Columns.Cast<DataColumn>() select dc.ColumnName).ToArray();
        int count = columnNames.Length;
        object[] array = new object[count];

        dataTable.Rows.Add(array);

        Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 0f);

        PdfWriter writer = PdfWriter.GetInstance(pdfDoc, mStream);
        int cols = dataTable.Columns.Count;
        int rows = dataTable.Rows.Count;

        HeaderFooter header = new HeaderFooter(new Phrase(Name), false);

        // Remove the border that is set by default  
        header.Border = iTextSharp.text.Rectangle.TITLE;
        // Align the text: 0 is left, 1 center and 2 right.  
        header.Alignment = Element.ALIGN_CENTER;
        pdfDoc.Header = header;
        // Header.  
        pdfDoc.Open();
        iTextSharp.text.Table pdfTable = new iTextSharp.text.Table(cols, rows);
        pdfTable.BorderWidth = 1; pdfTable.Width = 100;
        pdfTable.Padding = 1; pdfTable.Spacing = 4;

        //creating table headers  
        for (int i = 0; i < cols; i++)
        {
            Cell cellCols = new Cell();
            Chunk chunkCols = new Chunk();
            iTextSharp.text.Font ColFont = FontFactory.GetFont(FontFactory.HELVETICA, 14, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.Black);

            chunkCols = new Chunk(dataTable.Columns[i].ColumnName, ColFont);

            cellCols.Add(chunkCols);
            pdfTable.AddCell(cellCols);
        }
        //creating table data (actual result)   

        for (int k = 0; k < rows; k++)
        {
            for (int j = 0; j < cols; j++)
            {
                Cell cellRows = new Cell();
                iTextSharp.text.Font RowFont = FontFactory.GetFont(FontFactory.HELVETICA, 12);
                Chunk chunkRows = new Chunk(dataTable.Rows[k][j].ToString(), RowFont);
                cellRows.Add(chunkRows);

                pdfTable.AddCell(cellRows);
            }
        }

        pdfDoc.Add(pdfTable);
        pdfDoc.Close();

        content = mStream.ToArray();
        return File(content, "application/pdf", "LogReports.pdf");
    }
    catch (Exception ex)
    {
        throw new Exception(ex.Message);
    }
}

标签: itextasp.net-core-webapi

解决方案


推荐阅读