Home > Software design >  How can I save a PDF-document for each distinct name found in a list?
How can I save a PDF-document for each distinct name found in a list?

Time:09-28

Using PDFSharp, I would like to create one PDF-document for each distinct value in the property of the List I am looping through.

Grouping my collection, and creating a List:

var listName = collectionName
    .GroupBy(p => new { p.propertyName })
    .ToList();

Trying to execute my PDFsharp-code for every propertyName in listName:

foreach (var trip in paidTrip) {
    // Getting just the name string from the specific propertyName key
    string[] remove = { "{", "}", "propertyName", "=" };
    string pnString = trip.Key.ToString();
    foreach (string item in remove) {
        pnString = pnString.Replace(item, string.Empty);
}

Right here is where I believe I drop the ball; how can I bring each name with me to their distinct PDF-document? I am missing that connection. So, underneath this, I start creating my PDF-document(s):

    // Continued
    System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
    PdfDocument doc = new();
    PdfPage page = doc.AddPage();
    XGraphics gfx = XGraphics.FromPdfPage(page);
    // Adding fonts and brushes...
    
    // Adding some text, to check If I am able to grab the names of propertyName (which I am - but jut the first, once)...
    gfx.DrawString(pnString, new XFont("Arial", 40, XFontStyle.Bold), myGreen, new XPoint(5, 250));

    // And then, saving the PDF-document
    doc.Save("C:\My\File\Path\Test.pdf");

But as I said, this just saves one PDF for the first name found. I believe it is trying to save one file per name found, but it can't, because the file has already been created with the file name specified.

So my question is: how can I make sure that each name found in the foreach loop is brought with me to when I create the PDFs, and save one PDF-document for each of them?

CodePudding user response:

At the end when saving your file, you need to change the filename to be the key from your list like so:

// And then, saving the PDF-document
doc.Save($"C:\My\File\Path\{pnString}.pdf");

This will save an individual file for each of the different propertyName Keys you performed the GroupBy on previously.

CodePudding user response:

Put your code inside foreach loop :) PPAPed:

 foreach (var trip in paidTrip) {
        // Getting just the name string from the specific propertyName key
        string[] remove = { "{", "}", "propertyName", "=" };
        string pnString = trip.Key.ToString();
        foreach (string item in remove) {
            pnString = pnString.Replace(item, string.Empty);
        }

        // Continued 
        // [..] the rest of the code here
  }
  • Related