我有一个关于创建大型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);
}