I have an IList
in c#, and I want to put it in PDF through IText. Is there any way to do this? I have been searching for it for a while now.
What i tried to do was:
s = BLLstudent.selectStudentById(Convert.ToInt16(Request.QueryString["s"]));
var data = BLLevk.selectEvkDetailsVanStudent(s.pk_studentID);
Document mySavedPDF = new Document();
FileStream fs = new FileStream(@"C:\Users\Toon\Documents\Visual Studio 2010\WebSites\LilyNoone-LessLes-503729a\prints\" + s.studentNaam + "_" + s.studentVoornaam + ".pdf", FileMode.Create);
PdfWriter.GetInstance(mySavedPDF, fs);
mySavedPDF.Open();
mySavedPDF.Add(data);
mySavedPDF.CloseDocument();
But this said
Error 2 Argument 1: cannot convert from 'System.Collections.Generic.IList' to 'System.IO.TextReader' C:\Users\Toon\Documents\Visual Studio 2010\WebSites\evk-applicatie-181211\web\admin\a_overzicht_student.aspx.cs 95 77 C:...\evk-applicatie-181211\
Is there any way to insert the list directly?
Thx in advance
No, there's no way to directly add a generic IList
to the Document
object directly. If you take a look at the Document.Add method, the only valid parameter is an Element object - that's why the Exception
is thrown. If you think about it, trying to add a generic IList to a PDF would be very difficult - at the minimum you would have to take into consideration both the IList elements type
, and also how to format each member property (after you determine both type and members using Reflection
) in the PDF.
So you have a couple of choices.
The second choice isn't so bad, and you have complete control of how to display your collection. Here's a simple example:
Response.ContentType = "application/pdf";
IList<Student> students = Student.GetStudents();
using (Document document = new Document()) {
PdfWriter writer = PdfWriter.GetInstance(
document, Response.OutputStream
);
document.Open();
foreach (Student s in students) {
document.Add(new Paragraph(string.Format(
"[{0:D8}] - {1}, {2}. MAJOR: {3}",
s.Id, s.NameLast, s.NameFirst, s.Major
)));
List list = new List(List.ORDERED);
foreach (string c in s.Classes) {
list.Add(new ListItem(c));
}
document.Add(list);
}
}
With a simple class like this:
public class Student {
public string NameLast, NameFirst, Major;
public int Id;
public string[] Classes;
public static IList<Student> GetStudents() {
string[] majors = {"Math", "Engineering", "CS"};
List<Student> l = new List<Student>();
for (int i = 0; i < majors.Length;) {
l.Add(new Student() {
Major = majors[i],
Id = ++i, NameLast = string.Format("LastNameStudent{0}", i),
NameFirst = string.Format("FirstnameStudent{0}", i),
Classes = new string[] {"Calc I", "Physics II", "Databases"}
});
}
return l;
}
}