Denis Bokor Denis Bokor - 10 days ago 5
C# Question

Stack overflow exception on itextsharp document.close

I am merging multiple PDF into one single file.
here is my code:

string[] files = Directory.GetFiles(FolderName);
using (FileStream fs = new FileStream(PdfOutputFile, FileMode.Create))
{
Document doc = new Document();
PdfWriter writer = PdfWriter.GetInstance(doc, fs);
doc.Open();
foreach (string percorsoFile in files)
{
PdfContentByte cb = writer.DirectContent;
PdfReader reader = new PdfReader(percorsoFile);
int numpagine = reader.NumberOfPages - PageAddedByWord;
for (int pagina = 1; pagina <= numpagine; pagina++)
{
int rotazione = reader.GetPageSizeWithRotation(pagina).Rotation;
PdfImportedPage page = writer.GetImportedPage(reader, pagina);
doc.NewPage();
if (rotazione == 90 || rotazione == 270)
cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(pagina).Height);
else
cb.AddTemplate(page, 0f, 0f);
}
reader.Close();
}
doc.Close();
}


And I get stack overflow exception on the
doc.Close()
line, but I can't understand why. I close every reader as soon as I am done with that file. I get this exception only with large sets of pdf (like 2000).
thank's for the help.

Answer

SOLVED, I used PdfSmartCopy instead of pdfwriter. now the code looks like this

 Document doc = new Document();
            PdfSmartCopy pdfCopy = new PdfSmartCopy(doc, ms);
            doc.Open();
            foreach (var percorsoFilePdf in files)
            {
                PdfReader reader = new PdfReader(percorsoFilePdf);
                int numpagine = reader.NumberOfPages;
                for (int I = 1; I <= numpagine-PageAddedByWord; I++)
                {
                    doc.SetPageSize(reader.GetPageSizeWithRotation(1));
                    PdfImportedPage page = pdfCopy.GetImportedPage(reader, I);
                    pdfCopy.AddPage(page);
                }
                //Clean up
                //pdfCopy.FreeReader(reader);
                reader.Close();
            }
            //Clean up
            doc.Close();
            SharedMethods.MemoryStreamToFile(ms, PdfOutputFile);

also using a memorystream instead of a file stream is much faster, and the process doesn't get "to large".

Comments