iTextSharp系统的OutOfMemoryException

4
我有一个关于创建大型PDF文件的问题。基本上我有一组字节数组,每个包含一个PDF文件的字节数组。我想把这些字节数组合并成一个PDF文件。对于小型文件(少于2000页),这非常有效,但是当我尝试创建一个1200页的文件时,它就会崩溃了。最初我使用的是MemoryStream,但经过一些研究,常见的解决方案是改用FileStream。所以我尝试了一种文件流方法,但是得到了类似的结果。列表中包含3800个记录,每个记录包含4页。在大约570条记录后MemoryStream就会崩溃。FileStream则在大约680条记录后崩溃。代码崩溃时当前文件大小为60MB。我做错了什么?以下是我的代码,并且代码在“for(”循环内的“copy.AddPage(curPg);”指令处崩溃。
    private byte[] MergePDFs(List<byte[]> PDFs)
    {
        iTextSharp.text.Document doc = new iTextSharp.text.Document();
        byte[] completePDF;
        Guid uniqueId = Guid.NewGuid();
        string tempFileName = Server.MapPath("~/" + uniqueId.ToString() + ".pdf");

        //using (MemoryStream ms = new MemoryStream())
        using(FileStream ms = new FileStream(tempFileName, FileMode.Create, FileAccess.Write, FileShare.Read))
        {
            iTextSharp.text.pdf.PdfCopy copy = new iTextSharp.text.pdf.PdfCopy(doc, ms);
            doc.Open();

            int i = 0;
            foreach (byte[] PDF in PDFs)
            {
                i++;
                // Create a reader
                iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(PDF);

                // Cycle through all the pages
                for (int currentPageNumber = 1; currentPageNumber <= reader.NumberOfPages; ++currentPageNumber)
                {
                    // Read a page
                    iTextSharp.text.pdf.PdfImportedPage curPg = copy.GetImportedPage(reader, currentPageNumber);

                    // Add the page over to the rest of them
                    copy.AddPage(curPg);
                }

                // Close the reader
                reader.Close();
            }

            // Close the document
            doc.Close();

            // Close the copier
            copy.Close();

            // Convert the memorystream to a byte array
            //completePDF = ms.ToArray();
        }

        //return completePDF;
        return GetPDFsByteArray(tempFileName);
    }
2个回答

5

几点注意事项:

  1. PdfCopy 实现了 iDisposable 接口,因此你可以尝试使用 using 语句。
  2. PdfCopy.FreeReader() 可以提高程序的性能。

无论你是在使用MVC还是WebForms,在这里提供一个简单可行的HTTP处理程序的示例,该示例已经测试通过,使用了一个15页125KB的测试文件,在我的工作站上运行良好。

<%@ WebHandler Language="C#" Class="MergeFiles" %>
using System;
using System.Collections.Generic;
using System.Web;
using System.IO; 
using iTextSharp.text; 
using iTextSharp.text.pdf; 

public class MergeFiles : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        List<byte[]> pdfs = new List<byte[]>();
        var pdf = File.ReadAllBytes(context.Server.MapPath("~/app_data/test.pdf"));
        for (int i = 0; i < 4000; ++i) pdfs.Add(pdf);

        var Response = context.Response;
        Response.ContentType = "application/pdf";
        Response.AddHeader(
            "content-disposition",
            "attachment; filename=MergeLotsOfPdfs.pdf"
        );
        Response.BinaryWrite(MergeLotsOfPdfs(pdfs));
    }

    byte[] MergeLotsOfPdfs(List<byte[]> pdfs)
    {
        using (var ms = new MemoryStream())
        {
            using (Document document = new Document())
            {
                using (PdfCopy copy = new PdfCopy(document, ms))
                {
                    document.Open();
                    for (int i = 0; i < pdfs.Count; ++i)
                    {
                        using (PdfReader reader = new PdfReader(
                            new RandomAccessFileOrArray(pdfs[i]), null))
                        {
                            copy.AddDocument(reader);
                            copy.FreeReader(reader);
                        }
                    }
                }
            }
            return ms.ToArray();
        }
    }

    public bool IsReusable { get { return false; } }
}

我尝试使输出文件与问题描述中的类似,但具体效果取决于您所处理的单个PDF文件的大小。这是我的运行测试输出:

输入图像说明


我正在使用较旧版本的iTextSharp,它不允许我在Document、PdfCopy和PdfReader中使用"using"关键字。但是,如果你需要处理将近半GB数据的60000页内容时,我希望人们首先看你的代码而不是我的。我给你打勾和点赞。谢谢kuujinbo! - Lukas
@Lukas - 很抱歉听到你不能使用这个解决方案,但是非常感谢你的好评。 :) 在此之前,从未尝试过生成超过约2000页的任何内容,因此你的问题很有趣,并且得到了我的赞同。 - kuujinbo

0
经过一番折腾,我意识到这个问题是无法绕过的。不过,我找到了一个解决办法。我不再返回字节数组,而是返回一个临时文件路径,然后在传输完成后将其删除。
    private string MergeLotsOfPDFs(List<byte[]> PDFs)
    {
        Document doc = new Document();
        Guid uniqueId = Guid.NewGuid();
        string tempFileName = Server.MapPath("~/__" + uniqueId.ToString() + ".pdf");

        using (FileStream ms = new FileStream(tempFileName, FileMode.Create, FileAccess.Write, FileShare.Read))
        {
            PdfCopy copy = new PdfCopy(doc, ms);
            doc.Open();

            int i = 0;
            foreach (byte[] PDF in PDFs)
            {
                i++;
                // Create a reader
                PdfReader reader = new PdfReader(new RandomAccessFileOrArray(PDF), null);

                // Cycle through all the pages
                for (int currentPageNumber = 1; currentPageNumber <= reader.NumberOfPages; ++currentPageNumber)
                {
                    // Read a page
                    PdfImportedPage curPg = copy.GetImportedPage(reader, currentPageNumber);

                    // Add the page over to the rest of them
                    copy.AddPage(curPg);

                    // This is a lie, it still costs money, hue hue hue :)~
                    copy.FreeReader(reader);
                }
                reader.Close();
            }

            // Close the document
            doc.Close();

            // Close the document
            copy.Close();
        }

        // Return temp file path
        return tempFileName;
    }

以下是我如何将这些数据发送给客户端的。

        // Send the merged PDF file to the user.
        System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
        response.ClearContent();
        Response.ClearHeaders();
        response.ContentType = "application/pdf";
        response.AddHeader("Content-Disposition", "attachment; filename=1094C.pdf;");
        response.WriteFile(tempFileName);
        HttpContext.Current.Response.Flush(); // Sends all currently buffered output to the client.
        DeleteFile(tempFileName); // Call right after flush but before close
        HttpContext.Current.Response.SuppressContent = true;  // Gets or sets a value indicating whether to send HTTP content to the client.
        HttpContext.Current.ApplicationInstance.CompleteRequest(); // Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event.

最后,这里有一个高级的DeleteFile方法。
    private void DeleteFile(string fileName)
    {
        if (File.Exists(fileName))
        {
            try
            {
                File.Delete(fileName);
            }
            catch (Exception ex)
            {
                //Could not delete the file, wait and try again
                try
                {
                    System.GC.Collect();
                    System.GC.WaitForPendingFinalizers();
                    File.Delete(fileName);
                }
                catch
                {
                    //Could not delete the file still
                }
            }
        }
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接