Search code examples
pdftextitextfilestream

iText FileStream overwirtes


I am in the process of putting together some code that will merge pdf's based on the file name prefix. I currently have the below code that grabs the filename and doesn't merge, but overwrites. I believe my problem is the FileStream placement, but if I move it out of the current location, I can't get the filename. Any suggestions? Thanks.

static void CreateMergedPDFs() 
    {
        string srcDir = "C:/PDFin/";
        string resultPDF = "C:/PDFout/";
        {
            var files = System.IO.Directory.GetFiles(srcDir);
            string prevFileName = null;

            int i = 1;
            foreach (string file in files)
            {
                string filename = Left(Path.GetFileName(file), 8);
                using (FileStream stream = new FileStream(resultPDF  + filename + ".pdf", FileMode.Create))
                {

                    if (prevFileName == null || filename == prevFileName)
                    {
                        Document pdfDoc = new Document(PageSize.A4);
                        PdfCopy pdf = new PdfCopy(pdfDoc, stream); 
                        pdfDoc.Open();
                        {
                            pdf.AddDocument(new PdfReader(file));
                            i++;
                        }
                        if (pdfDoc != null)
                            pdfDoc.Close();
                        Console.WriteLine("Merges done!");
                    }

                }
            }
        }
    }
}

}


Solution

  • The behavior you are describing is consistent with your code. You are creating the loop in an incorrect way.

    Try this:

    static void CreateMergedPDFs() 
        {
            string srcDir = "C:/PDFin/";
            string resultPDF = "C:/PDFout/merged.pdf";
            FileStream stream = new FileStream(resultPDF, FileMode.Create);
            Document pdfDoc = new Document(PageSize.A4);
            PdfCopy pdf = new PdfCopy(pdfDoc, stream); 
            pdfDoc.Open();
            var files = System.IO.Directory.GetFiles(srcDir);
            foreach (string file in files)
            {
                pdf.AddDocument(new PdfReader(file));
            }
            pdfDoc.Close();
            Console.WriteLine("Merges done!");
        }
    }
    

    That makes more sense, doesn't it?

    If you want to group files based on their prefix, you should read the answer to the question Group files in a directory based on their prefix

    In the answer to this question, it is assumed that the prefix and the rest of the filename are separated by a - character. For instance 1-abc.pdf and 1-xyz.pdf have the prefix 1 whereas 2-abc.pdf and 2-xyz.pdf have the prefix 2. In your case, it's not clear how you'd determine the prefix, but it's easy to get a list of all the files, sort them and make groups of files based on whatever algorithm you want to determine the prefix.