Alex395 Ответов: 1

Как сохранить HTML-таблицы правильно выровненными при рендеринге в PDF?


Я хочу, чтобы html-таблицы были правильно выровнены при рендеринге в PDF с помощью Itextsharp. Содержимое таблицы идет вертикально, а не горизонтально для 2 таблиц слева и справа и так далее при рендеринге в формате PDF.

Ниже приведен мой html-код:
<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>


Что я уже пробовал:

Я рендеринг PDF-файла через itextsharp dll. Код для рендеринга того же самого в PDF выглядит следующим образом:
#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

Suvendu Shekhar Giri

Правильно ли он отображается в вашем браузере?

1 Ответов

Рейтинг:
1

vinuvasahanponniah

<pre lang="c#"><pre lang="c#"><pre lang="c#"><pre lang="c#">
Вы пытаетесь создать концепцию таблицы pdf с помощью этого типа кода

      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(G