如何使用 iTextSharp 在 PDF 中添加字符串列表?
How to add list of lists of string in PDF with iTextSharp?
我已经创建了二维字符串列表:
List<List<string>> questions = new List<List<string>>();
如何使用 iTextSharp 将此二维列表的元素添加到我的 PDF 文件中?
if (pdfFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Document document = new Document(iTextSharp.text.PageSize.LETTER, 20, 20, 42, 35);
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(pdfFile.FileName, FileMode.Create));
document.Open();
Paragraph paragraph = new Paragraph("Test");
document.Add(paragraph);
document.Close();
}
我已经用简单的 for 循环和命令试过了:document.Add(questions[i]);
但它不起作用。
先来看看C# What does List<List<string>> mean?
问题的答案
已接受的答案显示了如何输出此二维列表的内容:
List<List<string>> lists;
...
foreach (List<string> list in lists)
{
foreach (string s in list)
{
Console.WriteLine(s);
}
}
现在看How to create a table based on a two-dimensional array?
问题的答案
解释了如何使用List<List<string>>
的数据构造PdfPTable
:
PdfPTable table = new PdfPTable(numColumns);
foreach (List<string> question in questions) {
foreach (string field in question) {
table.AddCell(field);
}
}
现在您所要做的就是将 table
添加到 Document
实例:
document.add(table);
重要:我不知道numColumns
的值。您应该将 numColumns
替换为 question
对象的 string
值的数量。当您创建 questions
对象时,您(并且只有您)知道该问题的答案。实际上,您可以询问 questions
列表的第一个元素的大小;这样你就不必猜测了。请注意,假设每个 question
具有相同数量的元素。
更新: 如果您不想要 table,您应该将 string
值包含在段落中。例如:
foreach (List<string> question in questions) {
foreach (string field in question) {
document.Add(new Paragraph(field));
}
}
我已经创建了二维字符串列表:
List<List<string>> questions = new List<List<string>>();
如何使用 iTextSharp 将此二维列表的元素添加到我的 PDF 文件中?
if (pdfFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
Document document = new Document(iTextSharp.text.PageSize.LETTER, 20, 20, 42, 35);
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(pdfFile.FileName, FileMode.Create));
document.Open();
Paragraph paragraph = new Paragraph("Test");
document.Add(paragraph);
document.Close();
}
我已经用简单的 for 循环和命令试过了:document.Add(questions[i]);
但它不起作用。
先来看看C# What does List<List<string>> mean?
问题的答案已接受的答案显示了如何输出此二维列表的内容:
List<List<string>> lists;
...
foreach (List<string> list in lists)
{
foreach (string s in list)
{
Console.WriteLine(s);
}
}
现在看How to create a table based on a two-dimensional array?
问题的答案解释了如何使用List<List<string>>
的数据构造PdfPTable
:
PdfPTable table = new PdfPTable(numColumns);
foreach (List<string> question in questions) {
foreach (string field in question) {
table.AddCell(field);
}
}
现在您所要做的就是将 table
添加到 Document
实例:
document.add(table);
重要:我不知道numColumns
的值。您应该将 numColumns
替换为 question
对象的 string
值的数量。当您创建 questions
对象时,您(并且只有您)知道该问题的答案。实际上,您可以询问 questions
列表的第一个元素的大小;这样你就不必猜测了。请注意,假设每个 question
具有相同数量的元素。
更新: 如果您不想要 table,您应该将 string
值包含在段落中。例如:
foreach (List<string> question in questions) {
foreach (string field in question) {
document.Add(new Paragraph(field));
}
}