Problems by creating Multiple PDFs

后端 未结 2 1925
旧巷少年郎
旧巷少年郎 2021-01-24 15:39

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

相关标签:
2条回答
  • 2021-01-24 16:06

    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:

    Environment.GetFolderPath(Environment.SpecialFolder.Desktop) 
    + strGPNrVar+ DateTime.Now + "Report.pdf";
    

    This is identical to saying:

    Environment.GetFolderPath(Environment.SpecialFolder.Desktop) 
    + strGPNrVar + DateTime.Now.ToString() + "Report.pdf";
    

    Notice the ToString() part - a DateTime 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, (if strGPNrVar is "123") you will end up with a filename like this (on a system in the US):

    C:\Users\YourUsername\Desktop1237/22/2019 9:46:06 PMReport.pdf
    

    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:

    var filename = 
        Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), 
      strGPNrVar + "_" + DateTime.Now.ToString("yyyy-MM-dd-hh.mm.ss")
      + $"_Report.pdf");
    
    0 讨论(0)
  • 2021-01-24 16:15

    Thanks, you helped me a lot! This is the Code that works for me:

    var pdf1 =
                Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
                strGPNrVar + "_" + DateTime.Now.ToString("yyyy-MM-dd-hh.mm.ss")
                + $"_Report.pdf");
                using (FileStream fs = new FileStream(pdf1, FileMode.Create,
                FileAccess.Write, FileShare.None))
               {
    
                Document document = new Document(PageSize.A4);
                PdfWriter writer = PdfWriter.GetInstance(document, fs);
    
    0 讨论(0)
提交回复
热议问题