加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何减少许多单元格的PdfPTable的内存消耗

发布时间:2020-12-16 01:21:16 所属栏目:百科 来源:网络整理
导读:我正在使用ITextSharp创建一个PDF,它由一个PdfTable组成.不幸的是,对于一个特定的数据集,由于创建了大量的PdfPCell,我得到了一个Out of memory Exception(我已经分析了内存使用情况 – 我已经有近一万个单元!) 在这种情况下有没有办法减少内存使用量? 我已
我正在使用ITextSharp创建一个PDF,它由一个PdfTable组成.不幸的是,对于一个特定的数据集,由于创建了大量的PdfPCell,我得到了一个Out of memory Exception(我已经分析了内存使用情况 – 我已经有近一万个单元!)

在这种情况下有没有办法减少内存使用量?
我已经尝试在各个点(每行之后)和完全压缩后进行刷新

PdfWriter基于FileStream

代码看起来非常像这样:

Document document = Document();
FileStream stream = new FileStream(fileName,FileMode.Create);                                   
pdfWriter = PdfWriter.GetInstance(document,stream);
document.Open();
PdfPTable table = new PdfPTable(nbColumnToDisplay);
foreach (GridViewRow row in gridView.Rows)
{
    j = 0;
    for (int i = 0; i < gridView.HeaderRow.Cells.Count; i++)
    {
        PdfPCell cell = new PdfPCell( new Phrase( text) );
        table.AddCell(cell);
    }   
}
document.Add(table);
document.Close();

解决方法

iTextSharp有一个非常酷的接口,叫做 ILargeElement,PdfPTable实现了.根据文件:

/**
* Interface implemented by Element objects that can potentially consume
* a lot of memory. Objects implementing the LargeElement interface can
* be added to a Document more than once. If you have invoked setCompleted(false),* they will be added partially and the content that was added will be
* removed until you've invoked setCompleted(true);
* @since   iText 2.0.8
*/

因此,您需要做的就是在创建PdfPTable之后,将Complete属性设置为false.在你的内循环中做一些形式的计数器,每隔一段时间就会添加一个表,从而清除内存.然后在循环结束时将Complete设置为true并再次添加它.

下面是显示此关闭的示例代码.没有计数器检查,此代码在我的机器上使用大约500MB的RAM.通过计数器检查每1,000个项目,它下降到16MB的RAM.您需要为计数器找到自己的最佳位置,这取决于您平均每个单元格添加多少文本.

string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),"table.pdf");
Document document = new Document();
FileStream stream = new FileStream(fileName,FileMode.Create);
var pdfWriter = PdfWriter.GetInstance(document,stream);
document.Open();

PdfPTable table = new PdfPTable(4);
table.Complete = false;
for (int i = 0; i < 1000000; i++) {
    PdfPCell cell = new PdfPCell(new Phrase(i.ToString()));
    table.AddCell(cell);
    if (i > 0 && i % 1000 == 0) {
        Console.WriteLine(i);
        document.Add(table);
    }
}
table.Complete = true;
document.Add(table);
document.Close();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读