empira / PDFsharp-1.5

A .NET library for processing PDF
MIT License
1.28k stars 589 forks source link

merge several pdfs in order #150

Closed salvadorrenato closed 1 year ago

salvadorrenato commented 2 years ago

Hi, I'm concatenating several pdfs but they are not concatenated in the order I pass them.

Has anyone caught this situation?

public byte[] pdf (List){

        PdfSharp.Pdf.PdfDocument outputDocument = new PdfSharp.Pdf.PdfDocument();

        foreach (var pdf in PDFS)
        {
            using (MemoryStream stream = new MemoryStream(pdf ))
            {
                PdfSharp.Pdf.PdfDocument inputDocument = PdfReader.Open(stream, PdfDocumentOpenMode.Import);
                foreach (PdfSharp.Pdf.PdfPage page in inputDocument.Pages)
                {
                    outputDocument..AddPage( page);
                }
            }
        }
        MemoryStream mStream = new MemoryStream();
        outputDocument.Save(mStream,false);

        return mStream.ToArray();

}

this is the code I'm using. when trying to show on screen appears in random order

Can someone help me?

TH-Soft commented 2 years ago

Are the files not in the correct order or are pages within files not in the correct order or is it a mix of both?

salvadorrenato commented 2 years ago

it's a mixture of both. When I try to merge 3 files the order is always like this: the last file is on the first page then comes the first and second file.

when I try to merge more than 3 files the order is random.

TH-Soft commented 2 years ago

When the files do not come in the correct order, how can it be a problem of PDFsharp?

salvadorrenato commented 2 years ago

I always send the files in the order I would like them to be merged and save the new file for sharing.

However it seems to me that the AddPage() function is added to each page inserted in the new object with some sort of ordering from the PDFSharp library itself.

I would like each page added to go to the end.

I'm not claiming that the problem is with PDFSharp. It may be an error in use. Hence the request for help.

NXTwoThou commented 2 years ago
    foreach (var pdf in PDFS)

What is PDFS? foreach uses the IEnumerator for the given object. If PDFS is something like GetFiles() you aren't guaranteed any sort of order unless you do an OrderBy. Before your using statement you should log what file it's picking up. You'll likely find it to be in the same order that your outputDocument ends up being. I did a quick test here getting a bunch of files in a folder and until I sorted them by name, it was fairly random.