【问题标题】:How can I save a PDF-document for each distinct name found in a list?如何为列表中的每个不同名称保存 PDF 文档?
【发布时间】:2021-11-20 08:52:17
【问题描述】:

使用PDFSharp,我想为我正在循环的List 的属性中的每个不同值创建一个PDF 文档

对我的收藏进行分组,并创建一个List

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

尝试为listName 中的每个propertyName 执行我的PDFsharp 代码:

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);
}

这就是我认为我丢球的地方;如何将每个名字带到他们不同的 PDF 文档中?我错过了这种联系。 因此,在此之下,我开始创建我的 PDF 文档:

    // 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");

但正如我所说,这只会为找到的第一个名字保存一个 PDF。 我相信它会尝试为找到的每个名称保存一个文件,但它不能,因为该文件已使用指定的文件名创建。

所以我的问题是:我如何确保在创建 PDF 时将在 foreach 循环中找到的每个名称都带上,并为每个名称保存一个 PDF 文档?

【问题讨论】:

  • 当您保存到相同的文件名时,您如何期望有 n 个文件?您需要在第二个中为每个迭代执行第三个 sn-p,并确保输出文件具有不同的名称。
  • 您在创建列表时按propertyName 分组,遍历它,然后使用trip.Key 编写字符串/文本,然后按照Fildor 所说,将其保存到Test.pdf 的相同文件名在你的 foreach 循环内,你应该为 pdf 创建一个不同的名称,例如:$"{pnString}.pdf" 然后当它遍历列表时,它将为每个分组的 propertyName 创建一个新的 PDF 文件在列表中。
  • @ConnorTJ 非常感谢!代码在foreach 中,从我构建帖子的方式来看有点难以理解。因此,将{pnString} 添加到文件路径就可以了。伟大的!将您的评论添加为解决方案,我会接受。
  • @OleM 我已将其添加为答案,很高兴它有所帮助!

标签: c# list foreach ienumerable pdfsharp


【解决方案1】:

将您的代码放入 foreach 循环中:) 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
  }

【讨论】:

  • 另外,文件需要不同的名字...
  • 谢谢@smiech!我的代码在foreach 中,只是我设置问题的方式有点混乱。
【解决方案2】:

最后保存文件时,您需要将文件名更改为列表中的键,如下所示:

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

这将为您之前执行GroupBy 的每个不同的propertyName 键保存一个单独的文件。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-31
    • 1970-01-01
    • 1970-01-01
    • 2014-05-16
    • 2021-11-13
    • 2021-06-22
    • 2021-04-15
    • 1970-01-01
    相关资源
    最近更新 更多