Concatenate files according to the order of the list C#

Asked

Viewed 134 times

4

I have a program that concatenates PDF files. First it does the SPLIT of all pages of each file and store them in a temporary folder. When I press the end button, it calls a function GetFiles() that fetches all files from that temporary folder and merges them into a single PDF file.

I also have a list of file names and I can sort them through Drag&drop, but I wanted it to be possible to sort the concatenation order. For example, in the list is

  • file 1;
  • file 2;
  • file 3.

And if the user changes to

  • file 2;
  • file 3;
  • file 1.

Then it will concatenate in that order and not in the order of the folder. Should I display every page of every PDF in the list and sort around or is there another possible way?

EDIT (code):

Function to do SPLIT:

        public void SplitPDf(string filename)
        {
        // Open the file
        PdfDocument inputDocument = PdfReader.Open(filename, PdfDocumentOpenMode.Import);

        string name = Path.GetFileNameWithoutExtension(filename);
        for (int idx = 0; idx<inputDocument.PageCount; idx++)
        {
            // Create new document
            PdfDocument outputDocument = new PdfDocument();
            outputDocument.Version = inputDocument.Version;
            outputDocument.Info.Title =
            String.Format("Page {0} of {1}", idx + 1, inputDocument.Info.Title);
            outputDocument.Info.Creator = inputDocument.Info.Creator;

            // Add the page and save it
            outputDocument.AddPage(inputDocument.Pages[idx]);
            outputDocument.Save(String.Format(@"E:\temporario\{0} - Page {1}_tempfile.pdf", name, idx + 1));
        }

Function to make concatenation (MERGE):

        public void MergePDF(string folder)
        {
        string[] files = GetFiles();

        // Open the output document
        PdfDocument outputDocument = new PdfDocument();

        // Iterate files
        foreach (string file in files)
        {
            // Open the document to import pages from it.
            PdfDocument inputDocument = PdfReader.Open(file, PdfDocumentOpenMode.Import);

            // Iterate pages
            int count = inputDocument.PageCount;
            for (int idx = 0; idx < count; idx++)
            {
                // Get the page from the external document...
                PdfPage page = inputDocument.Pages[idx];
                // ...and add it to the output document.
                outputDocument.AddPage(page);
            }
        }

        // Save the document...
        outputDocument.Save(folder);
    }

List code:

 this.listaPdf.AllowDrop = true;
 private void listaPdf_MouseDown(object sender, MouseEventArgs e)
 {
        if (this.listaPdf.SelectedItem == null) return;
        this.listaPdf.DoDragDrop(this.listaPdf.SelectedItem, DragDropEffects.Move);
 }

 private void listaPdf_DragOver(object sender, DragEventArgs e)
 {
        e.Effect = DragDropEffects.Move;
 }

 private void listaPdf_DragDrop(object sender, DragEventArgs e)
 {
        Point point = listaPdf.PointToClient(new Point(e.X, e.Y));
        int index = this.listaPdf.IndexFromPoint(point);
        if (index < 0) index = this.listaPdf.Items.Count - 1;
        object data = listaPdf.SelectedItem;
        this.listaPdf.Items.Remove(data);
        this.listaPdf.Items.Insert(index, data);
 }

Function GetFiles():

public string[] GetFiles()
    {
        if (!Directory.Exists(@"E:\temporario"))
        {
            Directory.CreateDirectory(@"E:\temporario");
        }

        DirectoryInfo dirInfo = new DirectoryInfo(@"E:\temporario");
        FileInfo[] fileInfos = dirInfo.GetFiles("*.pdf");
        ArrayList list = new ArrayList();
        foreach (FileInfo info in fileInfos)
        {
            //Just skip the protected samples file...
            if (info.Name.IndexOf("protected") == -1)
                list.Add(info.FullName);
        }
        return (string[])list.ToArray(typeof(string));
    }
  • 1

    Hello @Sofia. Edit your question and put the code you already have. It makes understanding the problem much easier.

  • I’ll add the code!

  • 1

    Sofia, the code of the list is the most important to help, I find it interesting if you leave it in the question also instead of the link. :)

  • Done! The code of the list is complete there.

  • I did not identify the event where the user changes the sort of the list... if you do not store this information and simply search the files in the directory, there is no way your routine know in what order the user would like to concatenate

  • Could Leandro Angelo be clearer? Should I store this information in an array for example? The user changes the sort of the list through Dragdrop. This code is in the events "listaPdf_MouseDown", "listaPdf_DragOver" and "listaPdf_DragDrop".

Show 1 more comment

1 answer

0


I solved this question after more than 1 month. I hope I can help someone with this issue too! Then I will explain:

1. I add the files to ListBox (without the path to the folder where it is located)

2. I store that file in a temporary folder

3. When doing the operation, I will fetch the items from that list for a list created in the program

4. For every file on that list, do the action I want.

For example, the list has these files:

  1. for example1.pdf
  2. exemplo2.pdf
  3. exemplo3.pdf

I’ll keep those names ("o\caminho\da\pasta\temporaria\" + item) in the new list and then compare them to the temporary folder names. So, first look for the file "exemplo1.pdf" and do the action, then the file "exemplo2.pdf" and do the action, and so on.

I’ll show you an example of a code I made - PDF Merge!

Add file in ListBox:

    private void add1_Click(object sender, EventArgs e)
    {
        openFile.Title = "Procurar ficheiros no computador"; //título da janela
        openFile.InitialDirectory = @"C:\"; //diretório inicial
        openFile.Filter = "Ficheiros PDF (.pdf) | *.pdf"; //filtro de ficheiros
        DialogResult resposta = openFile.ShowDialog();

        if(resposta == DialogResult.OK)
        {
            foreach (string file in openFile.FileNames) //para cada ficheiro aberto
            {
                string caminhoCompleto = file; //caminho completo do ficheiro

                SplitPDF1(caminhoCompleto); //separar o pdf pelas suas páginas
            }
        }
    }

Add files from ListBox on the list:

List<string> l = new List<string>();
foreach (string f in lista1.Items)
    l.Add("temporario\\" + f);

Finally, merge the Pdfs:

    public void MergePDF2(string folder, string[] e)
    {
        try
        {
            string[] files = e; //a variável e vai ser l.ToArray()
            using (FileStream stream = new FileStream(folder, FileMode.Create))
            {
                var document = new Document();
                document.SetPageSize(iTextSharp.text.PageSize.A4.Rotate());

                PdfCopy pdf = new PdfCopy(document, stream);
                iTextSharp.text.pdf.PdfReader reader = null;                   
                document.Open();
                foreach (string file in files) //para cada ficheiro no array
                {
                    iTextSharp.text.pdf.PdfReader.unethicalreading = true;
                    reader = new iTextSharp.text.pdf.PdfReader(file);

                    pdf.AddDocument(reader);
                    reader.Close();
                }

                if (document != null)
                    document.Close();

                succed = 1;
            }

        }
        catch (Exception ex)
        {
            succed = 0;
            MessageBox.Show(ex.ToString(), "Erro", MessageBoxButtons.OK);
        }
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.