0

I have a method which will convert a datatable in pdf. In pdf, I will have a table. Now what I want to do is to add some data above that table. How can I do that in C#?

My code is as follows.

    public void ExportToPdf(DataTable dt, string htmlFilepath)
    {

        Document document = new Document();
        PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(htmlFilepath, FileMode.Create));
        document.Open();
        iTextSharp.text.Font fontbold = iTextSharp.text.FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 10);
        iTextSharp.text.Font font5 = iTextSharp.text.FontFactory.GetFont(FontFactory.HELVETICA, 7);


        PdfPTable table = new PdfPTable(dt.Columns.Count);
        PdfPRow row = null;
        float[] widths = new float[] { 4f, 4f, 4f ,4f ,4f ,4f};
        table.SetWidths(widths);
        table.WidthPercentage = 100;
        int iCol = 0;
        string colname = "";
        PdfPCell cell = new PdfPCell(new Phrase("Products"));
        cell.Colspan = dt.Columns.Count;

        foreach (DataColumn c in dt.Columns)
        {

            table.AddCell(new Phrase(c.ColumnName, fontbold));
        }

        foreach (DataRow r in dt.Rows)
        {
            if (dt.Rows.Count > 0)
            {
                table.AddCell(new Phrase(r[0].ToString(), font5));
                table.AddCell(new Phrase(r[1].ToString(), font5));
                table.AddCell(new Phrase(r[2].ToString(), font5));
                table.AddCell(new Phrase(r[3].ToString(), font5));
                table.AddCell(new Phrase(r[4].ToString(), font5));
                table.AddCell(new Phrase(r[5].ToString(), font5));

            }
        } document.Add(table);

        document.Close();
    }

1 Answer 1

1

You can use "Paragraph" for adding data like following

Chunk ch= new Chunk("Here is your data");
Phrase ph = new Phrase(beginning);
Paragraph p = new Paragraph();
p.Add(ph);
document.Add(p);//this line must be added before you add table to document.

Now Note that as i mention above. paragraph object must added to document before you add table as you want this data above the table.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.