我正在尝试创建一个函数,为 List
中属性的每个 不同 值创建一 (1) 个 PDF 发票我正在循环(使用 PDFSharp )。
我获取了 string
的值,并希望将其用作发票的抬头(这是开具发票的企业的名称)。
举例说明: 在下表中,我想获取 LicenseHolder1(一次)、LicenseHolder2(一次)和 LicenseHolder3(一次)的值。
这是我正在使用的方法:
using (SqlConnection con = new(ConnectionString.connectionString))
using (SqlCommand cmd = new("spCreateInvoice", con) {CommandType = CommandType.StoredProcedure})
using (SqlDataAdapter da = new(cmd))
// this is the name of my SQL table
using (DataTable dt = new("tblTripsPerMonth"))
using (DataSet ds = new()) {
con.Open();
da.Fill(dt);
ds.Tables.Add(dt);
/* adding the SQL table rows to my ObservableCollection (PaidTrips),
which is bound to properties in my holder class (PaidTrip): */
foreach (DataRow dr in ds.Tables[0].Rows {
PaidTrips.Add(new PaidTrip {
LicenseHolderID = dr[0].ToString(),
Value1 = (decimal)dr[1],
Value2 = (decimal)dr[2],
Value3 = dr[3].ToString(),
});
// Now I am instantiating a list, so that I can group
List<PaidTrip> paidTrip = PaidTrips
.GroupBy(p => new {p.LicenseHolderID})
.Select(g => g.First())
.ToList();
// this is copied code from another question, and this is where I fall of
foreach (PaidTrip PaidTrips in paidTrip) {
foreach (var LicenseHolderID in PaidTrips.GetType().GetProperties()) {
string n = LicenseHolderID.GetValue(PaidTrips).ToString();
如果我在这次抓取之后 string n
并将其传递给一个 MessageBox.Show
, 它显示 LicenseHolder1
, 正如它应该。
但是,如果我尝试将它传递到 PDF 中,就像这样......
(接上一个代码块)
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
PdfDocument pdf = new();
PdfPage page = pdf.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);
// drawing in the string value
gfx.DrawString(n, new XFont("Arial", 40, XFontStyle.Bold), myColor, new XPoint(40, 250));
// saving the PDF
pdf.Save("C:\File\Path\TestPDF.pdf");
}
}
}
}
...PDF创建好了,但是我画的字符串没有填充LicenseHolder1
,而是(看似)其他列的随机值(如 66
、 UF-2107
或 77
)。怎么会?
(哦,我知道这段代码只创建一 (1) 个 PDF 文件,我需要几个(LicenseHolderID
列中的每个不同值一个 - 但这是改天的问题)
最佳答案
您的数据表中是否有如上所示的 id 列?您的零列不会在那里取一个 ID 吗?
foreach (DataRow dr in ds.Tables[0].Rows {
PaidTrips.Add(new PaidTrip {
LicenseHolderID = dr[0].ToString(),
Value1 = (decimal)dr[1],
Value2 = (decimal)dr[2],
Value3 = dr[3].ToString(),
});
如果您按 LicenseHolderID 分组,则选择分组结果的第一个元素。这是故意的吗?
List<PaidTrip> paidTrip = PaidTrips
.GroupBy(p => new {p.LicenseHolderID})
.Select(g => g.First())
.ToList();
这将本质上返回一个包含多个包含相同 LicenseHolderID 的付费旅行对象的新对象。
通常如果你想使用组的字符串名称,你可以引用键值。
paidTrip.Key.ToString();
可能更好用,
var paidTrip = PaidTrips
.GroupBy(p => new {p.LicenseHolderID})
.ToList();
foreach (var tripFound in paidTrip)
{
string tripId = tripFound.Key.ToString();
//Generate your PDF File.
}
这应该为每组提供一个文件。如果我误会了你,我深表歉意。
https://stackoverflow.com/questions/69349177/