Click here to Skip to main content
14,869,378 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to keep html tables properly alligned while rendering to PDF using Itextsharp. The table contents are coming vertically instead of coming horizontally for 2 tables left and right and so on while rendering in PDF.

Below is my html code:
ASP.NET
<div style="width: 760px">
        
    <table width="760px"><tbody><tr><td align="center">
             <asp:Panel ID="pnlGridExport" runat="server" Width="820px" Visible="false">
            <table border="1" style="font-family: Arial; font-size: 10pt; width: 400px; float: left" align="left"><tbody><tr><td colspan="2" style="height: 18px; color: black">
                        Outward
                    </td></tr><tr><td>No: of OCEs</td><td><asp:Label ID="lblOCECount" runat="server"></td></tr><tr><td>Amount</td><td><asp:Label ID="lblOCEAmount" runat="server"></td></tr><tr><td style="color: blue">CR</td></tr></tbody></table>
            <table border="1" style="font-family: Arial; font-size: 10pt; width: 400px; float: right" align="right"><tbody><tr><td colspan="2" style="height: 18px; color: black">
                        Inward</td></tr><tr><td>No: of ICEs</td><td><asp:Label ID="lblICECount" runat="server"></td></tr><tr><td>Amount</td><td><asp:Label ID="lblICEAmount" runat="server"></td></tr><tr><td style="color: red">DR</td></tr></tbody></table>
              
            <table border="1" style="font-family: Arial; font-size: 10pt; width: 400px; float: left" align="left"><tbody><tr><td colspan="2" style="height: 18px; color: black">
                        Outward
                    Return</td></tr><tr><td>No: of IREs</td><td><asp:Label ID="lblIRECount" runat="server"></td></tr><tr><td>Amount</td><td><asp:Label ID="lblIREAmount" runat="server"></td></tr><tr><td style="color: red">DR</td></tr></tbody></table>
            <table border="1" style="font-family: Arial; font-size: 10pt; width: 400px; float: right" align="right"><tbody><tr><td colspan="2" style="height: 18px; color: black">
                        Inward</td></tr><tr><td>No: of RCEs</td><td><asp:Label ID="lblRCECount" runat="server"></td></tr><tr><td>Amount</td><td><asp:Label ID="lblRCEAmount" runat="server"></td></tr><tr><td style="color: blue">CR</td></tr></tbody></table>
            <table border="1" style="font-family: Arial; font-size: 10pt; width: 400px; float: left" align="left"><tbody><tr><td colspan="2" style="height: 18px; color: black">
                        Net of Outward</td></tr><tr><td>No: of Recods</td><td><asp:Label ID="lblNetOutwardRecords" runat="server"></td></tr><tr><td>Amount</td><td><asp:Label ID="lblNetOutwardAmount" runat="server"></td></tr><tr><td style="color: blue">CR</td></tr></tbody></table>
            <table border="1" style="font-family: Arial; font-size: 10pt; width: 400px; float: right" align="right"><tbody><tr><td colspan="2" style="height: 18px; color: black">
                        Net of Inward</td></tr><tr><td>No: of Records</td><td><asp:Label ID="lblNetInwardRecords" runat="server"></td></tr><tr><td>Amount</td><td><asp:Label ID="lblNetInwardAmount" runat="server"></td></tr><tr><td style="color: red">DR</td></tr></tbody></table>          
            <table border="1" style="font-family: Arial; font-size: 10pt; width: 400px" align="center"><tbody><tr><td colspan="2" style="height: 18px; color: black">
                        Net Amount</td><td colspan="2" style="height: 18px; color: black">
                       <asp:Label ID="lblNetAmount" runat="server"></td></tr></tbody></table>
            </td></tr></tbody></table>
</div>


What I have tried:

I am rendering PDF File via Itextsharp dll. Code to render the same to PDF are as below:
C#
#region View PDF Report
/// <summary>
/// populate the report using the search criteria.
/// 
private void ViewPDFReport()
{
    try
    {

        BLL_MISReports objMisReport = new BLL_MISReports();
        DateTime FromDate = DateTime.ParseExact(txtFromDate.Value.Trim(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
        DateTime ToDate = DateTime.ParseExact(txtToDate.Value.Trim(), "dd/MM/yyyy", CultureInfo.InvariantCulture);
        DataSet ds = objMisReport.BusinessDaySettlementReport(FromDate, ToDate, Convert.ToInt32(Session["USER"].ToString()));

        DataTable dt = new DataTable();
        if (ds.Tables[0].Rows.Count > 0)
        {
            dt = ds.Tables[0];
            pnlGridExport.Visible = true;
            //Bind Datatable to Labels
            lblOCECount.Text = dt.Rows[0]["OCERecordCount"].ToString();
            lblOCEAmount.Text = dt.Rows[0]["OCEAmount"].ToString();

            lblICECount.Text = dt.Rows[0]["ICERecordCount"].ToString();
            lblICEAmount.Text = dt.Rows[0]["ICEAmount"].ToString();

            lblIRECount.Text = dt.Rows[0]["RCERecordCount"].ToString();
            lblIREAmount.Text = dt.Rows[0]["IREAmount"].ToString();

            lblRCECount.Text = dt.Rows[0]["RCERecordCount"].ToString();
            lblRCEAmount.Text = dt.Rows[0]["RCEAmount"].ToString();


            lblNetOutwardRecords.Text = dt.Rows[0]["NetOutWardRecordCount"].ToString();
            lblNetOutwardAmount.Text = dt.Rows[0]["NetOutWardAmount"].ToString();


            lblNetInwardRecords.Text = dt.Rows[0]["NetInWardRecordCount"].ToString();
            lblNetInwardAmount.Text = dt.Rows[0]["NetInWardAmount"].ToString();


            lblNetAmount.Text = dt.Rows[0]["NetAmount"].ToString();

            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=BusinessDaySummary_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf");
            //Response.Cache.SetCacheability(HttpCacheability.NoCache);
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);

            pnlGridExport.RenderControl(hw);
            // grdExport.HeaderStyle.Width = "1";
            // grdExport.HeaderRow.Style.Add("font-size", "10px");
            //pnlGridExport.Style.Add("text-decoration", "none");
            //pnlGridExport.Style.Add("font-family", "Arial, Helvetica, sans-serif;");
            //pnlGridExport.Style.Add("font-size", "8px");
            //string strHead = strReportHeading + " FOR USER " + drdUserId.SelectedItem.Text.ToString();
            string strHead = strReportHeading;
            StringBuilder strbn = new StringBuilder();
            string Imagepath = Common.SITE_URL + "loginLogo.jpg";
            strbn.Append("<div style="float: right"></div> <span style="float: right; text-align: right; font-weight: bold">Date:" + DateTime.Today.ToString("dd-MMM-yyyy") + "</span><div style="text-align: center; font-weight: bold; background-color: White; width: 100%; font-size: 20px; text-decoration: underline"> " + strHead + "</div> <br>");
            strbn.Append(sw.ToString());
            StringReader sr = new StringReader(strbn.ToString());
            //Document pdfDoc = new Document(PageSize.A2, 7f, 7f, 7f, 0f);
            Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);
            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
            PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
            pdfDoc.Open();
            htmlparser.Parse(sr);
            pdfDoc.Close();
            Response.Flush();
            Response.Write(pdfDoc);
            Response.Flush();
            Response.Close();
        }
        else
        {
            pnlGridExport.Visible = false;
            Common.showMessage("No Records Found", this);
            return;
        }


    }
    catch (Exception ex)
    {
        Common.handleErrorLog(ex);
    }
}
#endregion
Posted
v2
Comments
Suvendu Shekhar Giri 3-Jan-17 4:33am
   
Is it rendering correctly in your browser?

1 solution

C#
<pre lang="c#"><pre lang="c#"><pre lang="c#"><pre lang="c#">
You try to pdf table concept using this type of code

      public string AssessmentInfopdfTwo(EntityStudentAssessment oStudentAssmInfo)
        {

            var FontColour = new BaseColor(181, 171, 134);
            var innerColour = new BaseColor(204, 197, 166);
            var tblwidth = 550f;
   FontFactory.RegisterDirectories();
            Font Defaultfont = new Font(FontFactory.GetFont("helvetica", 9, Font.NORMAL));
            Font MainHeading = new Font(FontFactory.GetFont("helvetica", 16, Font.BOLD));
            Font SubHeading = new Font(FontFactory.GetFont("helvetica", 14, Font.NORMAL));
            Font DateHeading = new Font(FontFactory.GetFont("helvetica", 12, Font.NORMAL));
            Font ExamDateHeading = new Font(FontFactory.GetFont("helvetica", 14, Font.NORMAL));
            Font PageHeading = new Font(FontFactory.GetFont("helvetica", 16, Font.BOLD));
            Font TableHeading = new Font(FontFactory.GetFont("helvetica", 9, Font.BOLD));
            Font TableContent = new Font(FontFactory.GetFont("helvetica", 9, Font.NORMAL));
            Font TableQualitativeContent = new Font(FontFactory.GetFont("helvetica", 8, Font.ITALIC));
iTextSharp.text.Font Default = Defaultfont; //for Document Header


            string PdfName = "schloud" + DateTime.Now.Ticks + ".pdf";
           Document doc = new Document(iTextSharp.text.PageSize.A4, 5, 5, 50, 25);
            string pdfFilePath = Server.MapPath("\\Temp\\");
            PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(pdfFilePath + PdfName, FileMode.Create));
            doc.Open();
            iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(Server.MapPath("../../Img/logo/ReportLogo.png"));
            iTextSharp.text.Image footerlogo = iTextSharp.text.Image.GetInstance(Server.MapPath("../../Img/logo/footerlogo.png"));

            float[] FirstPage = new float[2];
            FirstPage[0] = 65f;
            FirstPage[1] = 265f;

            PdfPTable dammy = new PdfPTable(1);
            PdfPCell Dummycell = new PdfPCell(new Phrase("  ", Defaultfont));
            Dummycell.BorderWidth = 0;
            dammy.AddCell(Dummycell);
            doc.Add(dammy);

            PdfPTable schooldetails = new PdfPTable(2);
            schooldetails.TotalWidth = 550f;
            schooldetails.LockedWidth = true;
            schooldetails.DefaultCell.BackgroundColor = FontColour;
            schooldetails.SetWidths(FirstPage);
            jpg.ScaleAbsolute(65f, 85f);
            PdfPCell Schoollogo = new PdfPCell(jpg);
            Schoollogo.Left = 0;
            Schoollogo.PaddingLeft = 0;
            Schoollogo.BorderWidth = 0;
            Schoollogo.BackgroundColor = FontColour;
            Schoollogo.HorizontalAlignment = Element.ALIGN_LEFT;
            schooldetails.AddCell(Schoollogo);

            PdfPTable schoolNameDetails = new PdfPTable(1);
            schoolNameDetails.TotalWidth = 550f;
            schoolNameDetails.DefaultCell.BackgroundColor = FontColour;
            PdfPCell SchoolName = new PdfPCell(new Phrase(" International", MainHeading));
            SchoolName.BorderWidth = 0;
            SchoolName.PaddingTop = 5f;
            SchoolName.PaddingBottom = 5f;
            SchoolName.PaddingLeft= 0;
            schoolNameDetails.AddCell(SchoolName);
 PdfPCell SchoolCenter = new PdfPCell(new Phrase("  CENTRE NO: 10721", ExamDateHeading));
            SchoolCenter.BorderWidth = 0;
            SchoolCenter.PaddingTop = 10f;
            SchoolCenter.PaddingBottom = 5f;
            SchoolCenter.PaddingLeft = 5f;
            schoolNameDetails.AddCell(SchoolCenter);

             PdfPCell SchoolTable = new PdfPCell(schoolNameDetails);
              SchoolTable.BorderWidth = 0;
         
              SchoolTable.BackgroundColor = FontColour;
              schooldetails.AddCell(SchoolTable);
              doc.Add(schooldetails);
float[] SubjecttableWidths = new float[4];
            SubjecttableWidths[0] = 80f;
            SubjecttableWidths[1] = 80f;
            SubjecttableWidths[2] = 40f;
            SubjecttableWidths[3] = 40f;
          //  SubjecttableWidths[4] = 200f;

            PdfPTable SubjectTableRight = new PdfPTable(4);

            SubjectTableRight.TotalWidth = 260f;
            SubjectTableRight.LockedWidth = true;
            SubjectTableRight.SetWidths(SubjecttableWidths);



            //subject table Head cells
            PdfPCell Subject = new PdfPCell(new Phrase("SUBJECTS", TableHeading)) { HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE };
            Subject.Padding = 10f;
            Subject.BackgroundColor = FontColour;
            SubjectTableRight.AddCell(Subject);
            PdfPCell Personnal = new PdfPCell(new Phrase("FACILITATOR", TableHeading)) { HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, BackgroundColor = FontColour };
            SubjectTableRight.AddCell(Personnal);
            PdfPCell Mark = new PdfPCell(new Phrase("%MARK", TableHeading)) { HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, BackgroundColor = FontColour };
            SubjectTableRight.AddCell(Mark);
            PdfPCell Grade = new PdfPCell(new Phrase("GRADE", TableHeading)) { HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, BackgroundColor = FontColour };
            SubjectTableRight.AddCell(Grade);
            SubjectTableRight.SpacingBefore = 10;


            PdfPTable SubjectTableLeft = new PdfPTable(4);

            SubjectTableLeft.TotalWidth = 260f;
            SubjectTableLeft.LockedWidth = true;
            SubjectTableLeft.SetWidths(SubjecttableWidths);

            //subject table Head cells
            PdfPCell Subject1 = new PdfPCell(new Phrase("SUBJECTS", TableHeading)) { HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE };
            Subject1.Padding = 10f;
            Subject1.BackgroundColor = FontColour;
            SubjectTableLeft.AddCell(Subject1);
            PdfPCell Personnal1 = new PdfPCell(new Phrase("FACILITATOR", TableHeading)) { HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, BackgroundColor = FontColour };
            SubjectTableLeft.AddCell(Personnal1);
            PdfPCell Mark1 = new PdfPCell(new Phrase("%MARK", TableHeading)) { HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, BackgroundColor = FontColour };
            SubjectTableLeft.AddCell(Mark1);
            PdfPCell Grade1 = new PdfPCell(new Phrase("GRADE", TableHeading)) { HorizontalAlignment = Element.ALIGN_CENTER, VerticalAlignment = Element.ALIGN_MIDDLE, BackgroundColor = FontColour };
            SubjectTableLeft.AddCell(Grade1);
          
            SubjectTableLeft.SpacingBefore = 10;

<pre>
            if (oStudentAssmInfo.oExamList.Count() > 0)
            {
                int i = 0;
                foreach (EntitySubject oProj in oStudentAssmInfo.oSubjectList)
                {
                    i++;
                    int index = oStudentAssmInfo.oExamList.FindIndex(f => f.oSubject.SubjectId == oProj.SubjectId);
                    if (index >= 0)
                    {
                        EntityExam oExam = oStudentAssmInfo.oExamList.Where(c => c.oSubject.SubjectId == oProj.SubjectId).First();
                        PdfPCell Subjects = new PdfPCell();
                        Subjects = new PdfPCell(new Phrase(oExam.oSubject.SubjectName, TableHeading));
                        Subjects.BackgroundColor = FontColour;
                        Subjects.VerticalAlignment = Element.ALIGN_MIDDLE;
                        Subjects.Padding = 10f;
                        PdfPCell persannals = new PdfPCell();
                        persannals = new PdfPCell(new Phrase(oExam.oStaff.FullName, Defaultfont));
                        persannals.VerticalAlignment = Element.ALIGN_MIDDLE;


                        PdfPCell Marks = new PdfPCell();
                        if (oExam.TotalMark != "-1")
                        {
                            Marks = new PdfPCell(new Phrase(oExam.TotalMark, Defaultfont));
                        }
                        else
                        {
                            Marks = new PdfPCell(new Phrase("absent", Defaultfont));
                        }
                        Marks.VerticalAlignment = Element.ALIGN_MIDDLE;
                        Marks.HorizontalAlignment = Element.ALIGN_CENTER;


                        PdfPCell Grades = new PdfPCell();
                        Grades = new PdfPCell(new Phrase(oExam.Grade, Defaultfont));
                        Grades.HorizontalAlignment = Element.ALIGN_CENTER;
                        Grades.VerticalAlignment = Element.ALIGN_MIDDLE;



                        PdfPCell Remarks = new PdfPCell();
                        Remarks = new PdfPCell(new Phrase(oExam.Remarks, Defaultfont));
                        Remarks.ExtraParagraphSpace = 5f;
                        Remarks.VerticalAlignment = Element.ALIGN_MIDDLE;
                        if (i % 2 == 0)
                        {
                            SubjectTableRight.AddCell(Subjects);
                            SubjectTableRight.AddCell(persannals);
                            SubjectTableRight.AddCell(Marks);
                            SubjectTableRight.AddCell(Grades);
                            //SubjectTableRight.AddCell(Remarks);
                        }
                        else
                        {

                            SubjectTableLeft.AddCell(Subjects);
                            SubjectTableLeft.AddCell(persannals);
                            SubjectTableLeft.AddCell(Marks);
                            SubjectTableLeft.AddCell(Grades);
                        }
                    }
                    else
                    {
                        PdfPCell Subjects = new PdfPCell();
                        Subjects = new PdfPCell(new Phrase(oProj.SubjectName, TableHeading));
                        Subjects.BackgroundColor = FontColour;
                        Subjects.VerticalAlignment = Element.ALIGN_MIDDLE;
                        Subjects.Padding = 10f;
                        if (i % 2 == 0)
                        {
                            SubjectTableRight.AddCell(Subjects);
                            SubjectTableRight.AddCell(new PdfPCell(new Phrase(" ", Defaultfont)) { Padding = 3f, BackgroundColor = innerColour });
                            SubjectTableRight.AddCell(new PdfPCell(new Phrase(" ", Defaultfont)) { Padding = 3f, BackgroundColor = innerColour });
                            SubjectTableRight.AddCell(new PdfPCell(new Phrase(" ", Defaultfont)) { Padding = 3f, BackgroundColor = innerColour });
                            //SubjectTableRight.AddCell(new PdfPCell(new Phrase(" ", Defaultfont)) { Padding = 3f, BackgroundColor = innerColour });
                        }
                        else
                        {
                            SubjectTableLeft.AddCell(Subjects);
                            SubjectTableLeft.AddCell(new PdfPCell(new Phrase(" ", Defaultfont)) { Padding = 3f, BackgroundColor = innerColour });
                            SubjectTableLeft.AddCell(new PdfPCell(new Phrase(" ", Defaultfont)) { Padding = 3f, BackgroundColor = innerColour });
                            SubjectTableLeft.AddCell(new PdfPCell(new Phrase(" ", Defaultfont)) { Padding = 3f, BackgroundColor = innerColour });
                        }
                    }
                }

            }
            else
            {
                SubjectTableRight.AddCell(" ");
                SubjectTableRight.AddCell("");
                SubjectTableRight.AddCell("");
                SubjectTableRight.AddCell("");

                SubjectTableLeft.AddCell(" ");
                SubjectTableLeft.AddCell("");
                SubjectTableLeft.AddCell("");
                SubjectTableLeft.AddCell("");
            }
 PdfPTable SubjectTableParent = new PdfPTable(2);
            SubjectTableParent.TotalWidth = 560f;
            SubjectTableParent.LockedWidth = true;
            SubjectTableParent.DefaultCell.Border = 0;
            SubjectTableParent.SpacingBefore = 10;
            SubjectTableParent.AddCell(SubjectTableRight);
            SubjectTableParent.AddCell(SubjectTableLeft);
            SubjectTableParent.SpacingAfter = 18;
            doc.Add(SubjectTableParent);
doc.Close();

            return PdfName;
}

        public ActionResult PrintAssessment()
        {

            EntityStudentAssessment oStudentAssmInfo = new BSNSTest().GetStudentWiseResult(Request.QueryString["StudentId"].ToString(), Request.QueryString["TestId"].ToString(), Request.QueryString["BatchId"].ToString());
            string file = "";
         
                file = AssessmentInfopdfTwo(oStudentAssmInfo);
          
            var fileStream = new FileStream(Server.MapPath("\\Temp\\" + file),
                                     FileMode.Open,
                                     FileAccess.Read
                                   );
            var fsResult = new FileStreamResult(fileStream, "application/pdf");
            return fsResult;




        }<pre lang="c#"><pre lang="c#">
   
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900