I succeeded in creating a single pdf, but how can I design a loop for file names? The Problem is every Loop my file will be overwritten
I tried to add a variable to the file, but it doesn't work:
var filename = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
+ strGPNrVar + DateTime.Now + "Report.pdf";
Here's the code so far:
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(
Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/Report.pdf", FileMode.Create));
PdfPTable table = new PdfPTable(5);
document.Opem();
foreach (var f in transactions)
{
//MessageBox.Show("Das ist die Menge" + f.CurrencyAmount);
table.AddCell(f.ID.ToString());
table.AddCell(f.TransactionType);
table.AddCell(f.UserName);
table.AddCell(f.EuroAmount);
table.AddCell(f.GPNummer);
document.Add(table);
}
document.Close();
System.Diagnostics.Process.Start(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/Report.pdf");
MessageBox.Show("Pdfs erfolgreich erstellt");
I need to loop this for every customer. The filename should be astring GpNrvar and also datetime.now
You said "it doesn't work", but you didn't describe why it doesn't work. If you tell us what happened we can better help you solve the problem. However I think your issue is the default formatting of dates contains characters that are in the list of invalid filename characters.
Your code uses
DateTime.Now
by directly adding it to a string:This is identical to saying:
Notice the
ToString()
part - aDateTime
value needs to be converted to a string and the default format usually includes slashes and colons, both not allowed in a filename on Windows filesystems. In your case, (ifstrGPNrVar
is "123") you will end up with a filename like this (on a system in the US):You need to manually specify the date format to get rid of the invalid characters. The second problem this illustrates, as others have pointed out, you should use
Path.Combine
to combine directory paths and filenames - this will take care of adding slashes where they are needed:Thanks, you helped me a lot! This is the Code that works for me: