1

我正在用 C# 构建一个程序,它读取 3 个 PDF 文件,根据用户 ID 执行一些排序并生成一个输出 PDF 文件。它目前生成 1254 个 pdf 文件(每个大约 5 MB),当我尝试加入它们时,会抛出 Out Of Memmory Exception 。

考虑到文件大小为 4 GB,如何加入这些文件?以下代码将所有 PDF 文件连接到一个输出文件中。

public void CombineMultiplePDFs(string[] fileNames, string outFile)
    {
        int pageOffset = 0;
        ArrayList master = new ArrayList();
        int f = 0;
        Document document = null;
        PdfCopy writer = null;
        while (f < fileNames.Length)
        {
            // we create a reader for a certain document
            PdfReader reader = new PdfReader(fileNames[f]);
            reader.ConsolidateNamedDestinations();
            // we avisorieve the total number of pages
            int n = reader.NumberOfPages;
            pageOffset += n;
            if (f == 0)
            {
                // step 1: creation of a document-object
                document = new Document(reader.GetPageSizeWithRotation(1));
                // step 2: we create a writer that listens to the document
                writer = new PdfCopy(document, new FileStream(outFile, FileMode.Create));
                // step 3: we open the document
                document.Open();
            }
            // step 4: we add content
            for (int i = 0; i < n; )
            {
                ++i;
                if (writer != null)
                {


                    PdfImportedPage page = writer.GetImportedPage(reader, i);
                    writer.AddPage(page);


                }
            }
            PRAcroForm form = reader.AcroForm;
            if (form != null && writer != null)
            {
                writer.CopyAcroForm(reader);
            }
            f++;
        }
        // step 5: we close the document
        if (document != null)
        {
            document.Close();
        }
    }
4

0 回答 0