简体   繁体   中英

Corrupted file after merging pdf using iTextSharp

Getting merged pdf but corrupted file that I can't open using the below code. The 'targetPDF' is the final merged pdf file and 'fileNames' has all the single pdfs. Please help. Thanks in advance.

 Using (FileStream stream = new FileStream(targetPDF, FileMode.Create, FileAccess.Write))
                {

                    Document document = new Document();
                    PdfCopy pdf = new PdfCopy(document, stream);
                    if (pdf == null)
                    {
                        return;
                    }
                    document.Open();

                    foreach (string file in fileNames)
                    {
                        PdfReader reader = new PdfReader(file);
                        reader.ConsolidateNamedDestinations();

                        for (int i = 1; i <= reader.NumberOfPages; i++)
                        {
                            PdfImportedPage page = pdf.GetImportedPage(reader, i);
                            pdf.AddPage(page);
                            //pdf.AddDocument(new PdfReader(file));
                            // pdf.AddPage(pdf.GetImportedPage(reader, 1));
                        }


                        reader.Close();
                    }
                }

Change this lines

Document document = new Document();
PdfCopy pdf = new PdfCopy(document, stream);

To :

using(Document document = new Document())
{
    using(PdfCopy pdf = new PdfCopy(document, stream))
    { 
        //do staff here...
    }
}

So that after the work is done all streams close and files were not locked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM