Export student report to PDF using iTextSharp in Windows Application

Last Reply 4 months ago By pandeyism

Posted 4 months ago

I have a following data

AdmissionNo

Class

Section

Subject

Max

Obtain

%

Pos

Grade

R-01

One

A

Urdu

50

24

50

3

C

R-01

One

A

English

50

28

55

2

B

R-01

One

A

Math

50

43

80

1

A

I want to generate reports like this [Desired Output]

1-Urdu:

Exam:

A1. T1

A2.T1

A1. T2

A2.T2

Max

50

 

 

 

 

24

 

 

 

%

50

 

 

 

Grade

C

 

 

 

2-English:

Exam:

A1. T1

A2.T1

A1. T2

A2.T2

Max

50

 

 

 

 

28

 

 

 

%

55

 

 

 

Grade

B

 

 

 

3-Math:

Exam:

A1. T1

A2.T1

A1. T2

A2.T2

Max

50

 

 

 

 

43

 

 

 

%

80

 

 

 

Grade

A

 

 

 

i wrote the following code

        private void tbTest_Click(object sender, EventArgs e)
        {
            con = new SqlDbConnect();
            con.SqlQuery(@"SELECT SPic,SessionName,ExamType,fa.AdmissionNo,ReferenceNo,SName,FName,FPhone,AcademicName,ClassName,SectionName,SubjectName,Max,Mark 
                ,Round((Mark) * 100/ (Max),1) as SubPer
                ,dense_rank() over(partition BY SUM(Max) order by SUM(Mark) DESC) AS SubPos
                ,(CASE WHEN  Round((SUM(Mark)) * 100/ SUM([Max]),1) >= 90 THEN 'A+'
                WHEN  Round((SUM(Mark)) * 100/ SUM([Max]),1) >= 80 THEN 'A'
                WHEN  Round((SUM(Mark)) * 100/ SUM([Max]),1) >= 70 THEN 'B'
                WHEN  Round((SUM(Mark)) * 100/ SUM([Max]),1) >= 60 THEN 'C'
                WHEN  Round((SUM(Mark)) * 100/ SUM([Max]),1) >= 50 THEN 'D'
                WHEN  Round((SUM(Mark)) * 100/ SUM([Max]),1) >= 40 THEN 'E'
                ELSE 'FAIL' END ) AS Grade
 
                ,(CASE WHEN  Round((SUM(Mark)) * 100/ SUM([Max]),1) >= 90 THEN 'OutStanding'
                WHEN  Round((SUM(Mark)) * 100/ SUM([Max]),1) >= 80 THEN 'Excellent'
                WHEN  Round((SUM(Mark)) * 100/ SUM([Max]),1) >= 70 THEN 'Very Good'
                WHEN  Round((SUM(Mark)) * 100/ SUM([Max]),1) >= 60 THEN 'Good'
                WHEN  Round((SUM(Mark)) * 100/ SUM([Max]),1) >= 50 THEN 'Satisfactory'
                WHEN  Round((SUM(Mark)) * 100/ SUM([Max]),1) >= 40 THEN 'Work Hard'
                ELSE 'FAIL' END ) AS Remarks
 
                FROM tblSetMarks as fa
                            inner join tblSession as ses on fa.SessionID=ses.SessionID
                            inner join tblSetExam as st on fa.SetExamID=st.SetExamID
                            inner join tblStdReg as sr on fa.AdmissionNo=sr.AdmissionNo
                            inner join tblAssignSubjects as fh on fa.SubjectID=fh.ASID inner join tblDefSubject as df on fh.SubjectID=df.SubjectID
                            inner join tblAcademicYear as ay on sr.YearID=ay.YearID
                            inner join tblDefClass as dc on sr.ClassID=dc.ClassID
                            inner join tblDefSection as ds on sr.SectionID=ds.SectionID where fa.AdmissionNo='R-000015'                           
                            group by SPic,SessionName,ExamType,fa.AdmissionNo,ReferenceNo,SName,FName,FPhone,AcademicName,ClassName,SectionName,SubjectName,Max,Mark order by AdmissionNo asc;");

            paging.SelectCommand = con.Cmd;
            sBuilder = new SqlCommandBuilder(paging);
            ds = new DataSet();
            paging.Fill(ds, "tblSetMarks");
            sTable = ds.Tables["tblSetMarks"];
            dGV.DataSource = ds.Tables["tblSetMarks"].DefaultView;
            dGV.ReadOnly = true;

            int i = 0;
            string AdNo = null;
            string Name = null;
            string FName = null;
            string Class = null;
            string Section = null;
            string Roll = null;
            string Subject = null;
            string Total = null;
            string Obt = null;
            string Per = null;
            string Grade = null;
            Byte[] bytess = null;
                    
            string pdfpath = @"C:\Reports\";
            if (!Directory.Exists(pdfpath))
            {
                Directory.CreateDirectory(pdfpath);
            }
            Document doc = new Document(PageSize.A4);
            PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(pdfpath + "TestCard on " + DateTime.Now.ToShortDateString() + ".pdf", FileMode.Create));
            doc.Open();
            con = new SqlDbConnect();
            con.SqlQuery("select logo,SystemName,Address,Phone,Email FROM tblSystem");
            con.RdrEx();
            while (con.Rdr.Read())
            {
                PdfPTable table1 = new PdfPTable(2);
                table1.DefaultCell.Padding = 10f;
                table1.DefaultCell.BackgroundColor = iTextSharp.text.Color.WHITE;
                table1.DefaultCell.Border = 0;
                table1.HorizontalAlignment = Element.ALIGN_CENTER;
                table1.TotalWidth = 500f;
                table1.LockedWidth = true;
                float[] widths1 = new float[] { 0.7f, 3f };
                table1.SetWidths(widths1);
                Byte[] bytes = (Byte[])con.Rdr[0];
                iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(bytes);
                image.ScaleAbsolute(90f, 70f);
                PdfPCell bottom1 = new PdfPCell((image));
                bottom1.Padding = 5f;
                bottom1.BackgroundColor = iTextSharp.text.Color.WHITE;
                bottom1.Border = 0;
                bottom1.HorizontalAlignment = 1;
                table1.AddCell(bottom1);
                PdfPTable nested1 = new PdfPTable(1);
                float[] width = new float[] { 0.1f };
                nested1.SetWidths(width);
                nested1.DefaultCell.BackgroundColor = iTextSharp.text.Color.WHITE;
                nested1.DefaultCell.Padding = 7f;
                nested1.DefaultCell.HorizontalAlignment = 1;
                nested1.DefaultCell.Border = 0;
                nested1.AddCell(new Phrase(con.Rdr[1].ToString(), FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 15)));
                nested1.AddCell(new Phrase(con.Rdr[2].ToString(), FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 14)));
                nested1.AddCell(new Phrase("Email: " + con.Rdr[4].ToString() + "\t Phone No: " + con.Rdr[3].ToString(), FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 12)));
                // nested1.AddCell(new Phrase("Phone No: " + con.Rdr[3].ToString(), FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 14)));
                PdfPCell nesthousing1 = new PdfPCell(nested1);
                nesthousing1.Colspan = 2;
                nesthousing1.Padding = 0f;
                nesthousing1.Border = 0;
                table1.AddCell(nesthousing1);
                doc.Add(table1);
                Paragraph p = new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(1.0F, 100.0F, iTextSharp.text.Color.BLACK, Element.ALIGN_LEFT, 1)));
                doc.Add(p);
            }
            con.conClose();

            PdfPTable table112 = new PdfPTable(5);
            table112.TotalWidth = 580f;
            table112.LockedWidth = true;
            table112.DefaultCell.NoWrap = true;
            PdfPCell cell112 = new PdfPCell(new Phrase("Result"));
            cell112.Colspan = 5;
            cell112.BackgroundColor = Color.YELLOW;
            cell112.HorizontalAlignment = Element.ALIGN_CENTER;
            table112.AddCell(cell112);
            table112.AddCell("Subject");
            table112.AddCell("A1.T1");
            table112.AddCell("A2.T1");
            table112.AddCell("A1.T2");
            table112.AddCell("A2.T2");

            for (i = 0; i <= sTable.Rows.Count - 1; i++)
            {
                Total= sTable.Rows[i].ItemArray[12].ToString();
                Obt= sTable.Rows[i].ItemArray[13].ToString();
                Per= sTable.Rows[i].ItemArray[14].ToString();
                Grade = sTable.Rows[i].ItemArray[16].ToString();             
                table112.AddCell("");
                table112.AddCell(" Max "+Total);
                table112.AddCell("Obt" + Obt);
                table112.AddCell("Per" + Per);
                table112.AddCell("Grade" + Grade);
            }   
            doc.Add(table112);
            doc.Close();
            MessageBox.Show("Assessment Result Card Generated Successfully", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return;
        }

 

Posted 4 months ago Modified on 4 months ago

Hi smile,

Refer below sample.

Namespaces

C#

using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Data;

VB.Net

Imports System.IO
Imports System.Data
Imports iTextSharp.text
Imports iTextSharp.text.pdf

Code

C#

private static DataTable GetData()
{
    DataTable dt = new DataTable();
    dt.Columns.AddRange(new DataColumn[] { 
        new DataColumn("SessionName", typeof(string)),
        new DataColumn("ExamType", typeof(string)),
        new DataColumn("SName", typeof(string)),
        new DataColumn("FName", typeof(string)),
        new DataColumn("AcademicName", typeof(string)),
        new DataColumn("FPhone", typeof(string)),
        new DataColumn("AdmissionNo", typeof(string)), 
    new DataColumn("ClassName", typeof(string)),
    new DataColumn("SectionName", typeof(string)),
    new DataColumn("Subject", typeof(string)),
    new DataColumn("Max", typeof(int)),
    new DataColumn("Obtain", typeof(int)),
    new DataColumn("%", typeof(int)),
    new DataColumn("Pos", typeof(int)),
    new DataColumn("Grade", typeof(string)) });
    dt.Rows.Add("2019", "Internal", "s1", "f1", "t1t1t", "654165465", "R-01", "One", "A", "Urdu", 50, 24, 50, 3, "C");
    dt.Rows.Add("2019", "Internal", "s1", "f1", "t1t1t", "654165465", "R-01", "One", "A", "English", 50, 28, 55, 2, "B");
    dt.Rows.Add("2019", "Internal", "s1", "f1", "t1t1t", "654165465", "R-01", "One", "A", "Math", 50, 43, 80, 1, "A");
    dt.Rows.Add("2019", "Internal", "s1", "f1", "t1t1t", "654165465", "R-02", "One", "A", "Urdu", 50, 24, 50, 3, "C");
    dt.Rows.Add("2019", "Internal", "s1", "f1", "t1t1t", "654165465", "R-02", "One", "A", "English", 50, 28, 55, 2, "B");
    dt.Rows.Add("2019", "Internal", "s1", "f1", "t1t1t", "654165465", "R-02", "One", "A", "Math", 50, 43, 80, 1, "A");
    return dt;
}

protected void tbFront_Click(object sender, EventArgs e)
{
    string pdfpath = @"C:\Users\anand\Desktop\Test\\";
    if (!Directory.Exists(pdfpath))
    {
        Directory.CreateDirectory(pdfpath);
    }
    string folderPath = @"C:\Users\anand\Desktop\Test\\";
    FileStream stream = new FileStream(folderPath + "DataGridViewExport.pdf", FileMode.Create);
    Document doc = new Document();
    PdfWriter.GetInstance(doc, stream);
    doc.Open();

    DataTable sTable = GetData();
    var grouped = from x in sTable.AsEnumerable()
                    group x by new { a = x["AdmissionNo"] } into g
                    select new
                    {
                        Value = g.Key,
                        ColumnValues = g
                    };
    DataTable dtfinal = null;
    foreach (var key in grouped)
    {
        dtfinal = sTable.Clone();
        foreach (var columnValue in key.ColumnValues)
        {
            dtfinal.ImportRow(columnValue);
        }

        PdfPTable table1 = new PdfPTable(2);
        table1.DefaultCell.Padding = 10f;
        table1.DefaultCell.BackgroundColor = iTextSharp.text.Color.WHITE;
        table1.DefaultCell.Border = 0;
        table1.HorizontalAlignment = Element.ALIGN_CENTER;
        table1.TotalWidth = 500f;
        table1.LockedWidth = true;
        float[] widths1 = new float[] { 0.7f, 3f };

        PdfPTable tableb = new PdfPTable(4);
        float[] widthim = new float[] { 0.1f, 0.1f, 0.1f, 0.05f };
        tableb.SetWidths(widthim);
        tableb.DefaultCell.Padding = 10f;
        tableb.HorizontalAlignment = Element.ALIGN_CENTER;
        tableb.TotalWidth = 550f;
        tableb.LockedWidth = true;
        PdfPCell header = new PdfPCell(new Phrase("Student Details", FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 12)));
        header.Indent = 10;
        header.HorizontalAlignment = 1;
        header.Padding = 10f;
        header.Colspan = 4;
        tableb.AddCell(header);

        PdfPTable nested = new PdfPTable(3);
        float[] widthi = new float[] { 0.1f, 0.1f, 0.1f };
        nested.SetWidths(widthi);
        nested.DefaultCell.Padding = 10f;

        nested.AddCell(new Phrase("Session: " + dtfinal.Rows[0]["SessionName"], FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 10)));
        nested.AddCell(new Phrase("Exam: " + sTable.Rows[0]["ExamType"], FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 10)));
        nested.AddCell(new Phrase("Reg No. " + dtfinal.Rows[0]["AdmissionNo"], FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 10)));
        nested.AddCell(new Phrase("Student: " + dtfinal.Rows[0]["SName"], FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 10)));
        nested.AddCell(new Phrase("Father: " + dtfinal.Rows[0]["FName"], FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 10)));
        nested.AddCell(new Phrase("AcademicYear: " + dtfinal.Rows[0]["AcademicName"], FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 10)));
        nested.AddCell(new Phrase("Class: " + dtfinal.Rows[0]["ClassName"], FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 10)));
        nested.AddCell(new Phrase("Section: " + dtfinal.Rows[0]["SectionName"], FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 10)));
        nested.AddCell(new Phrase("Phone No. " + dtfinal.Rows[0]["FPhone"], FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 10)));

        doc.Add(tableb);
        doc.Add(nested);
        for (int j = 0; j < dtfinal.Rows.Count; j++)
        {
            PdfPTable table = new PdfPTable(5);
            table.TotalWidth = 500f;
            table.LockedWidth = true;
            float[] widths = new float[] { 0.1f, 0.1f, 0.1f, 0.1f, 0.1f };
            table.SetWidths(widths);
            table.DefaultCell.Padding = 7f;
            table.HorizontalAlignment = Element.ALIGN_CENTER;
            table.SpacingBefore = 5f;

            table.AddCell(dtfinal.Rows[j]["Subject"].ToString());
            table.AddCell("A1.T1");
            table.AddCell("A2.T1");
            table.AddCell("A1.T2");
            table.AddCell("A2.T2");
            table.AddCell("Max ");
            table.AddCell(dtfinal.Rows[j]["Max"].ToString());
            table.AddCell("");
            table.AddCell("");
            table.AddCell("");
            table.AddCell("Obt");
            table.AddCell(dtfinal.Rows[j]["Obtain"].ToString());
            table.AddCell("");
            table.AddCell("");
            table.AddCell("");
            table.AddCell("Per");
            table.AddCell(dtfinal.Rows[j]["%"].ToString());
            table.AddCell("");
            table.AddCell("");
            table.AddCell("");
            table.AddCell("Grade");
            table.AddCell(dtfinal.Rows[j]["Grade"].ToString());
            table.AddCell("");
            table.AddCell("");
            table.AddCell("");
            doc.Add(table);
        }
        doc.NewPage();
    }
    doc.Close();
}

VB.Net

Private Shared Function GetData() As DataTable
    Dim dt As DataTable = New DataTable()
    dt.Columns.AddRange(New DataColumn() {New DataColumn("SessionName", GetType(String)), New DataColumn("ExamType", GetType(String)), New DataColumn("SName", GetType(String)), New DataColumn("FName", GetType(String)), New DataColumn("AcademicName", GetType(String)), New DataColumn("FPhone", GetType(String)), New DataColumn("AdmissionNo", GetType(String)), New DataColumn("ClassName", GetType(String)), New DataColumn("SectionName", GetType(String)), New DataColumn("Subject", GetType(String)), New DataColumn("Max", GetType(Integer)), New DataColumn("Obtain", GetType(Integer)), New DataColumn("%", GetType(Integer)), New DataColumn("Pos", GetType(Integer)), New DataColumn("Grade", GetType(String))})
    dt.Rows.Add("2019", "Internal", "s1", "f1", "t1t1t", "654165465", "R-01", "One", "A", "Urdu", 50, 24, 50, 3, "C")
    dt.Rows.Add("2019", "Internal", "s1", "f1", "t1t1t", "654165465", "R-01", "One", "A", "English", 50, 28, 55, 2, "B")
    dt.Rows.Add("2019", "Internal", "s1", "f1", "t1t1t", "654165465", "R-01", "One", "A", "Math", 50, 43, 80, 1, "A")
    dt.Rows.Add("2019", "Internal", "s1", "f1", "t1t1t", "654165465", "R-02", "One", "A", "Urdu", 50, 24, 50, 3, "C")
    dt.Rows.Add("2019", "Internal", "s1", "f1", "t1t1t", "654165465", "R-02", "One", "A", "English", 50, 28, 55, 2, "B")
    dt.Rows.Add("2019", "Internal", "s1", "f1", "t1t1t", "654165465", "R-02", "One", "A", "Math", 50, 43, 80, 1, "A")
    Return dt
End Function

Protected Sub tbFront_Click(ByVal sender As Object, ByVal e As EventArgs)
    Dim pdfpath As String = "C:\Users\anand\Desktop\Test\\"

    If Not Directory.Exists(pdfpath) Then
        Directory.CreateDirectory(pdfpath)
    End If

    Dim folderPath As String = "C:\Users\anand\Desktop\Test\\"
    Dim stream As FileStream = New FileStream(folderPath & "DataGridViewExport.pdf", FileMode.Create)
    Dim doc As Document = New Document()
    PdfWriter.GetInstance(doc, stream)
    doc.Open()
    Dim sTable As DataTable = GetData()
    Dim grouped = From x In sTable.AsEnumerable()
            Group x By Value = x.Field(Of String)("AdmissionNo") Into g = Group
            Select New With {
                .Value = Value,
                .ColumnValues = g}
    For Each key In grouped
        Dim dtfinal As DataTable = sTable.Clone()
        For Each columnValue In key.ColumnValues
            dtfinal.ImportRow(columnValue)
        Next
        dtfinal = sTable.Clone()

        For Each columnValue In key.ColumnValues
            dtfinal.ImportRow(columnValue)
        Next

        Dim table1 As PdfPTable = New PdfPTable(2)
        table1.DefaultCell.Padding = 10.0F
        table1.DefaultCell.BackgroundColor = iTextSharp.text.Color.WHITE
        table1.DefaultCell.Border = 0
        table1.HorizontalAlignment = Element.ALIGN_CENTER
        table1.TotalWidth = 500.0F
        table1.LockedWidth = True
        Dim widths1 As Single() = New Single() {0.7F, 3.0F}
        Dim tableb As PdfPTable = New PdfPTable(4)
        Dim widthim As Single() = New Single() {0.1F, 0.1F, 0.1F, 0.05F}
        tableb.SetWidths(widthim)
        tableb.DefaultCell.Padding = 10.0F
        tableb.HorizontalAlignment = Element.ALIGN_CENTER
        tableb.TotalWidth = 550.0F
        tableb.LockedWidth = True
        Dim header As PdfPCell = New PdfPCell(New Phrase("Student Details", FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 12)))
        header.Indent = 10
        header.HorizontalAlignment = 1
        header.Padding = 10.0F
        header.Colspan = 4
        tableb.AddCell(header)
        Dim nested As PdfPTable = New PdfPTable(3)
        Dim widthi As Single() = New Single() {0.1F, 0.1F, 0.1F}
        nested.SetWidths(widthi)
        nested.DefaultCell.Padding = 10.0F
        nested.AddCell(New Phrase("Session: " & dtfinal.Rows(0)("SessionName"), FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 10)))
        nested.AddCell(New Phrase("Exam: " & sTable.Rows(0)("ExamType"), FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 10)))
        nested.AddCell(New Phrase("Reg No. " & dtfinal.Rows(0)("AdmissionNo"), FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 10)))
        nested.AddCell(New Phrase("Student: " & dtfinal.Rows(0)("SName"), FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 10)))
        nested.AddCell(New Phrase("Father: " & dtfinal.Rows(0)("FName"), FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 10)))
        nested.AddCell(New Phrase("AcademicYear: " & dtfinal.Rows(0)("AcademicName"), FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 10)))
        nested.AddCell(New Phrase("Class: " & dtfinal.Rows(0)("ClassName"), FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 10)))
        nested.AddCell(New Phrase("Section: " & dtfinal.Rows(0)("SectionName"), FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 10)))
        nested.AddCell(New Phrase("Phone No. " & dtfinal.Rows(0)("FPhone"), FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 10)))
        doc.Add(tableb)
        doc.Add(nested)

        For j As Integer = 0 To dtfinal.Rows.Count - 1
            Dim table As PdfPTable = New PdfPTable(5)
            table.TotalWidth = 500.0F
            table.LockedWidth = True
            Dim widths As Single() = New Single() {0.1F, 0.1F, 0.1F, 0.1F, 0.1F}
            table.SetWidths(widths)
            table.DefaultCell.Padding = 7.0F
            table.HorizontalAlignment = Element.ALIGN_CENTER
            table.SpacingBefore = 5.0F
            table.AddCell(dtfinal.Rows(j)("Subject").ToString())
            table.AddCell("A1.T1")
            table.AddCell("A2.T1")
            table.AddCell("A1.T2")
            table.AddCell("A2.T2")
            table.AddCell("Max ")
            table.AddCell(dtfinal.Rows(j)("Max").ToString())
            table.AddCell("")
            table.AddCell("")
            table.AddCell("")
            table.AddCell("Obt")
            table.AddCell(dtfinal.Rows(j)("Obtain").ToString())
            table.AddCell("")
            table.AddCell("")
            table.AddCell("")
            table.AddCell("Per")
            table.AddCell(dtfinal.Rows(j)("%").ToString())
            table.AddCell("")
            table.AddCell("")
            table.AddCell("")
            table.AddCell("Grade")
            table.AddCell(dtfinal.Rows(j)("Grade").ToString())
            table.AddCell("")
            table.AddCell("")
            table.AddCell("")
            doc.Add(table)
        Next
        doc.NewPage()
    Next
    doc.Close()
End Sub

Screenshot