iTextsharp PDF export System.OutOfMemoryException Ошибка для массовых записей - PullRequest
0 голосов
/ 18 января 2019

Я использую iTextsharp PDF для экспорта отчета. Когда у меня менее 30000 записей, файл PDF экспортируется без ошибок. Но если у меня более 30000 записей, я получаю исключение System.OutOfMemoryException при добавлении таблицы в документ.

Я что-то здесь упускаю? Любая помощь будет очень признательна.

Вот мой код.

var pdfDoc = new Document(PageSize.A4, 70f, 70f, 80f, 10f);

using (var mStream = new MemoryStream())
{
    var writer = PdfWriter.GetInstance(pdfDoc, mStream);
    var cols = selected.Columns.Count;
    var rows = selected.Rows.Count;
    var footer = new HeaderFooter(new Phrase("Page "), true)
    {
        Border = Element.ALIGN_RIGHT,
        Alignment = Element.ALIGN_RIGHT
    };
    pdfDoc.Footer = footer;
    pdfDoc.Open();
    pdfDoc.SetMargins(70f, 70f, 50f, 10f);
    pdfDoc.NewPage();
    var logoIbot = HttpContext.Current.Server.MapPath(@"~/UI_Assests/img/report_top.png");
    var ibot = iTextSharp.text.Image.GetInstance(logoIbot);
    ibot.ScaleAbsolute(770, 35f);
    ibot.SetAbsolutePosition(0, 807);
    pdfDoc.Add(ibot);
    var logoPts = HttpContext.Current.Server.MapPath(ImagePath);
    iTextSharp.text.Image pts = iTextSharp.text.Image.GetInstance(logoPts);
    pts.ScaleAbsoluteHeight(15);
    pts.ScaleAbsoluteWidth(130);
    pts.SetAbsolutePosition(445, 815);
    pdfDoc.Add(pts);
    var user = HttpContext.Current.Server.MapPath(@"~/UI_Assests/img/userx32.png");
    iTextSharp.text.Image users = iTextSharp.text.Image.GetInstance(user);
    users.ScaleAbsolute(15, 15f);
    users.SetAbsolutePosition(24, 780);
    pdfDoc.Add(users);
    var report = HttpContext.Current.Server.MapPath(@"~/UI_Assests/img/report.png");
    iTextSharp.text.Image reports = iTextSharp.text.Image.GetInstance(report);
    reports.ScaleAbsolute(15, 15f);
    reports.SetAbsolutePosition(225, 780);
    pdfDoc.Add(reports);
    var reportTime = HttpContext.Current.Server.MapPath(@"~/UI_Assests/img/report_timex32.png");
    var reportime = iTextSharp.text.Image.GetInstance(reportTime);
    reportime.ScaleAbsolute(15, 15f);
    reportime.SetAbsolutePosition(440, 780);
    pdfDoc.Add(reportime);
    var cb = writer.DirectContent;
    cb.BeginText();
    cb.SetRGBColorFill(r, g, b);
    var baseFont = BaseFont.CreateFont(fontsType_PDF, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    cb.SetFontAndSize(baseFont, Convert.ToInt32(fontsSize) + 3);
    cb.SetRGBColorFill(0, 191, 255);
    cb.ShowTextAligned(1, name, 295, 785, 0);
    cb.SetFontAndSize(baseFont, 40f);
    var baseFont1 = BaseFont.CreateFont(fontsType_PDF, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
    cb.SetFontAndSize(baseFont1, Convert.ToInt32(fontsSize));
    cb.SetRGBColorFill(0, 0, 0);
    string text = "Report Generated Time ";
    cb.ShowTextAligned(4, text, 460, 790, 0);

    cb.SetRGBColorFill(0, 0, 0);
    DateTime dateTime = DateTime.Now;
    string text1 = dateTime.ToString("dd-MM-yyyy HH:mm:ss");
    cb.ShowTextAligned(4, text1, 460, 775, 0);

    cb.SetRGBColorFill(0, 0, 0);
    string text2 = customerName; ;
    if (!string.IsNullOrWhiteSpace(text2) && text2 != "All")
        text2 = "UserName: " + text2;
    else
        text2 = "UserName: " + "All";
    //model.DataModel";//model.DataModel
    cb.ShowTextAligned(4, text2, 43, 785, 0);


    cb.EndText();

    var pdfTable = new iTextSharp.text.Table(cols, rows)
    {
        Width = 120,
        Padding = 1,
        Spacing = 4
    };

    var widths = new[] { 200, 280, 250, 350, 350, 350, 350 };
    pdfTable.SetWidths(widths);
    pdfTable.LastHeaderRow = 0;
    pdfTable.SpaceBetweenCells = 0;
    pdfTable.CellsFitPage = true;

    for (int i = 0; i < cols; i++)
    {
        Cell cellCols = new Cell();
        Cell cellRows = new Cell();
        cellCols.Border = iTextSharp.text.Rectangle.NO_BORDER;
        Chunk chunkCols = new Chunk();
        cellCols.BackgroundColor = new iTextSharp.text.Color(System.Drawing.Color.FromArgb(rh, gh, bh));
        iTextSharp.text.Font ColFont = FontFactory.GetFont(fontsType_PDF, Convert.ToInt32(fontsSize), iTextSharp.text.Font.BOLD, new iTextSharp.text.Color(System.Drawing.Color.FromArgb(r, g, b)));
        cellCols.HorizontalAlignment = align_PDF;
        cellCols.Width = 100;
        // chunkCols = new Chunk(selected.Columns[i].ColumnName, ColFont);
        if (i == 0)
        {
            chunkCols = new Chunk("Sr.No", ColFont);
        }
        else
        {
            chunkCols = new Chunk(columnNames[i - 1], ColFont);
        }

        cellCols.Add(chunkCols);
        pdfTable.AddCell(cellCols);
    }
    int Sr = 1;
    for (int k = 0; k < rows - 1; k++)
    {
        for (int j = 0; j < cols; j++)
        {
            Cell cellRows = new Cell();
            cellRows.Border = 0;
            cellRows.HorizontalAlignment = align_PDF;
            if (k % 2 == 0)
            {
                cellRows.BackgroundColor = new iTextSharp.text.Color(System.Drawing.Color.FromArgb(r1, g1, b1)); ;
            }
            else { cellRows.BackgroundColor = new iTextSharp.text.Color(System.Drawing.Color.FromArgb(r2, g2, b2)); }
            iTextSharp.text.Font RowFont = FontFactory.GetFont(fontsType_PDF, Convert.ToInt32(fontsSize), biu_PDF, new iTextSharp.text.Color(System.Drawing.Color.FromArgb(r, g, b)));
            Chunk chunkRows = new Chunk(selected.Rows[k][j].ToString(), RowFont);
            cellRows.Add(chunkRows);
            pdfTable.AddCell(cellRows);
        }
    }
    pdfTable.Border = 0;
    pdfDoc.Add(pdfTable); //I am getting error here.
    pdfDoc.Close();
    HttpContext.Current.Response.ContentType = "application/octet-stream";
    HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + "ChatLog Report" + ".pdf");
    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.BinaryWrite(mStream.ToArray());
    //Response.End();
    HttpContext.Current.Response.Flush(); // Sends all currently buffered output to the client.
    HttpContext.Current.Response.SuppressContent = true;  // Gets or sets a value indicating whether to send HTTP content to the client.
    HttpContext.Current.ApplicationInstance.CompleteRequest();
...