2
PROBLEM
I made a code to concatenate (Merge) pdf files.
The code works in full but when there are more than 10 files, instead of doing in order: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10.
Does so: 1, 10, 2, 3, 4, 5, 6, 7, 8, 9
DOUBT
How can I get around this problem and do it in the right order?
CODE
My code is this:;:
public void MergePDF(string folder, string[] e)
{
try
{
string[] files = e;
using (FileStream stream = new FileStream(folder, FileMode.Create))
{
iTextSharp.text.Rectangle pageSize = new iTextSharp.text.Rectangle(842, 842);
Document pdfDoc = new Document(pageSize);
PdfCopy pdf = new PdfCopy(pdfDoc, stream);
pdfDoc.Open();
iTextSharp.text.pdf.PdfReader reader;
foreach (string file in files)
{
reader = new iTextSharp.text.pdf.PdfReader(file);
iTextSharp.text.pdf.PdfReader.unethicalreading = true;
iTextSharp.text.Rectangle mediabox = reader.GetPageSize(1);
pdfDoc.SetPageSize(mediabox);
pdf.AddDocument(reader);
reader.Dispose();
pbar.PerformStep();
}
pdfDoc.Close();
pdf.Dispose();
stream.Dispose();
succed = 1;
}
}
catch (Exception ex)
{
succed = 0;
MessageBox.Show(ex.ToString(), "Erro", MessageBoxButtons.OK);
}
}
Take a look at these solutions and see if they are useful to you: https://stackoverflow.com/questions/808670/combine-two-or-more-pdfs
– Marlon Pereira
@Marlonleandro Thanks for the link, but deep down these solutions are similar to my code...
– Sofia Rodrigues
Or do you think I should wear a cycle for instead of a cycle foreach ?
– Sofia Rodrigues
Use the
for
and post the return– Marlon Pereira
@Focos received the error in
CreationTime
string does not contain a Definition for Creationtime– Sofia Rodrigues
Yes, I’ve removed the comment,
CreationTime
would only work if it wereFileSystemInfo[]
, in your case isstring[]
.– Focos
@Right focus, thanks anyway.
– Sofia Rodrigues
I don’t understand... your error an Exception in executing the code or simply respecting the order of the files?
– Leandro Angelo
Test this way:
var files = e.OrderBy(f => new string(f.Where(char.IsLetter).ToArray()))
 .ThenBy(f =>
 {
 int number;
 if (int.TryParse(new string(f.Where(char.IsDigit).ToArray()), out number))
 return number;
 return -1;
 }).ToList();
In place ofstring[] files = e;
– Focos
@Leandroangelo is an error regarding the order of the files, it is not an Exception error.
– Sofia Rodrigues
That’s right @Focos ! Thank you. Could you post as a reply and explain the code please? It’s easy to copy and paste but it’s hard to understand what we’re using.
– Sofia Rodrigues