如何设置下一页上的大表,如果包含大与iTextSharp

本文关键字:如果 包含大 iTextSharp 何设置 设置 一页 | 更新日期: 2023-09-27 18:12:55

我用PdfPageEventHelper在我的文档上添加了一个页眉和一个页脚

文档有几个在运行时填充的"大"表。

我试过简单地通过" document . add (table)"来添加这些表,但是我的页眉和页脚结果被覆盖了。

我已经尝试了两种方法来添加表(WriteSelectedRows和document.Add(myPdfPtable))。

下面是header的PageEventHelper的代码:

 public override void OnEndPage(PdfWriter writer, Document doc)
            {
                Phrase phrase = null;
                PdfPCell cell = null;           
                PdfPTable maintable = new PdfPTable(2);                
                maintable.TotalWidth = 500f;
                maintable.LockedWidth = true;
                maintable.SetWidths(new float[] { 50f, 400f });

                #region checklogo               
                if (IsLogo!=0)
                {
                   // code for display head like logo, etc
                }
                #endregion CheckSchoolNameandAddress
                maintable.WriteSelectedRows(0, -1, 50, 835, writer.DirectContent);
                Color color = new Color(System.Drawing.ColorTranslator.FromHtml("#A9A9A9"));
                DrawLine(writer, 25f,  780f, doc.PageSize.Width - 25f, 780f,color);
                DrawLine(writer, 25f, 780f, doc.PageSize.Width - 25f,  780f, color);
            }

下面是页脚的PageEventHelper的代码:

     public override void OnEndPage(PdfWriter writer, Document doc)
                {
                    Phrase phrase = null;
                    PdfPCell cell = null;
                    PdfPCell cell1 = null;
                    PdfPCell cell2 = null;
                    int pageN = writer.PageNumber;
                    String text = "Page " + pageN;
                    PdfPTable foootertable = new PdfPTable(3);
                    foootertable.TotalWidth = 500f;
                    foootertable.LockedWidth = true;
                    foootertable.SetWidths(new float[] { 50f, 60f, 50f });

                    #region checkprintedbyReportNamePageNo
                    if (Isfooter != 0)
                    {
                        // code for footer like pageno, etc
                    }
                    #endregion CheckprintedbyReportNamePageNo
                    foootertable.WriteSelectedRows(0, -1, 30,30, writer.DirectContent);
                    color = new Color(System.Drawing.ColorTranslator.FromHtml("#A9A9A9"));
                    DrawLine(writer, 25f, 32f, doc.PageSize.Width - 25f, 32f, color);
                    DrawLine(writer, 25f, 32f, doc.PageSize.Width - 25f, 32f, color);
                }

显示在所有页面上的表代码,如reportdisplay

    public ActionResult DetailReportPDF(int TempId, int ReportModuleId, string BoardStageId, string ShiftId, string ClassDivisionId, string Subjects)
        {
            try
            {
                var BaseUrl = string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, Url.Content("~"));
                IBoard board = Session["SchoolAdmin"] as IBoard;
                if (board != null)
                {
                    int yearid = 0; IYears currentyear = YearsDomain.GetCurrentYears(board.Board_Id); if (currentyear != null) yearid = currentyear.Year_Id;
                    string SchoolAddress = "";
                    string SchoolName = "";
                    string SchoolLogo = "";
                    SchoolName = board.Board_Name != null ? board.Board_Name.ToUpper() : "";
                    SchoolAddress = (board.Board_Address1 != null ? board.Board_Address1.ToUpper() + "," : "") + (board.Board_City != null ? board.Board_City + "," : "") + (board.Board_State != null ? board.Board_State + ", " : "") + (board.Board_Country != null ? board.Board_Country + " - " : "") + (board.Board_Pincode != null ? board.Board_Pincode + "." : "");
                    SchoolLogo = Session["SchoolLogo"] != null ? Session["SchoolLogo"].ToString() : "";
                    string filename = "";
                    DateTime now = DateTime.Now;
                    Document document = new Document(PageSize.A4);
                    document.SetMargins(88, 88, 80, 10f);
                    iTextSharp.text.Font NormalFont = FontFactory.GetFont("Arial Unicode MS,Arial", 12, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK);
                    iTextSharp.text.Font VNormalFont = FontFactory.GetFont("Arial Unicode MS,Arial", 10, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK);
                    iTextSharp.text.Font LARGFont = FontFactory.GetFont("Arial Unicode MS,Arial", 14, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK);
                    using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
                    {
                        PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
                        Phrase phrase = null;
                        PdfPCell cell = null;
                        PdfPTable maintable = null;
                        PdfPTable table = null;                       
                        PdfPTable secondTable = null;
                        PdfPCell TableCell = new PdfPCell();
                        PdfPCell secondTableCell = new PdfPCell();
                        secondTableCell.Border = iTextSharp.text.Rectangle.NO_BORDER;
                        iTextSharp.text.Color color = null;
                        document.Open();
                        List<ReportSetLayout> lst = new List<ReportSetLayout>();
                        IReportTemplate RTD = ReportTemplateDomain.GetReportTemplateFromId(TempId);
                        string Newstr = "";
                        int IsLogo = 0;
                        string LogoSize="";
                        string LogoPosition="";
                        int IsSchoolName=0;
                        int IsSchoolAddress=0;
                        string SchoolNameSize = "";
                        string SchoolNamePosition = "";
                        string SchoolAddressSize = "";
                        string SchoolAddressPosition = "";
                        int Isfooter = 0;
                        int IsPrintedBy =0;
                        int IsReportName =0;
                        int PageNo =0;
                        string ShowPrintedBy=""; 
                        string ShowReportName ="";
                        string ShowPageNo = "";
                        IReportModule ReportModule = ReportModuleDomain.GetReportModulesFromId(ReportModuleId);
                        IBoardUserRights boarduserrights = BoardUserRightsDomain.GetBoardUserRights(board.Board_Id, "Reports", Session["BoardUserName"].ToString());
                        IBoardUser BU = BoardUserDomain.getBoardUserById(Convert.ToInt32(boarduserrights.Board_User_Id));
                        if (RTD != null)
                        {
                            #region forLogo
                            // code for get value for header logo    
                            #endregion forLogo
                            #region forschoolName&address
                                // code for get value for header address
                            #endregion forschoolName&address
                            #region forprintedbyReportNamePageNo
                            // code for get value for footer 
                            #endregion forprintedbyReportNamePageNo

                        }

                        writer.PageEvent = new Header() { SName = SchoolName, SAddress = SchoolAddress, SLogo = SchoolLogo, IsLogo=IsLogo, LogoSize = LogoSize, LogoPosition = LogoPosition ,IsSchoolName=IsSchoolName , IsSchoolAddress=IsSchoolAddress, SchoolNameSize=SchoolNameSize ,SchoolNamePosition=SchoolNamePosition,SchoolAddressSize=SchoolAddressSize,SchoolAddressPosition=SchoolAddressPosition};
                       // writer.PageEvent = new Header();
                        writer.PageEvent = new Footer(){ Isfooter=Isfooter,IsPrintedBy=IsPrintedBy,IsReportName=IsReportName,IsPageNo=PageNo,PrintedBy=ShowPrintedBy,ReportName=ShowReportName};
                        #region ReportBind
                        string Shortby = "";
                        List<string> lstformat = new List<string>();
                        List<string> lstWrap = new List<string>();                   

                        List<ReportColumnDetails> lstReportColumn = new List<ReportColumnDetails>();
                        lstReportColumn = ReportColumnDomain.GetReportColumnsFromReportModule(ReportModuleId);

                        List<IReportTemplateColumn> lstRptempcol = new List<IReportTemplateColumn>();
                        lstRptempcol = ReportTemplateColumnDomain.GetAllReportTemplateColumnbyID(TempId);
                        List<int> colindexid = new List<int>();
                        List<int> ColWidth = new List<int>();
                        foreach (var col in lstRptempcol)
                        {
                            ColWidth.Add(Convert.ToInt32(col.ColumnWidth));
                            colindexid.Add(Convert.ToInt32(col.Column_Index_Id));
                        }
                        foreach (var shortName in lstRptempcol)
                        {
                            if (shortName.Sortby == Convert.ToByte(1))
                            {
                                Shortby = lstReportColumn.Where(x => x.ColumnId == shortName.Column_Id).Select(y => y.ColumnName).FirstOrDefault();
                            }
                            if (lstReportColumn.Where(x => x.ColumnId == shortName.Column_Id).Select(y => y.ColumnName).FirstOrDefault().Contains("Date"))
                            {
                                lstformat.Add(lstReportColumn.Where(x => x.ColumnId == shortName.Column_Id).Select(y => y.ColumnName).FirstOrDefault() + "_" + shortName.Format);
                            }
                            if (lstReportColumn.Where(x => x.ColumnId == shortName.Column_Id).Select(y => y.ColumnName).FirstOrDefault().Contains("Gender"))
                            {
                                lstformat.Add(lstReportColumn.Where(x => x.ColumnId == shortName.Column_Id).Select(y => y.ColumnName).FirstOrDefault() + "_" + shortName.Format);
                            }
                            if (shortName.Wrap == Convert.ToByte(1))
                            {
                                lstWrap.Add(lstReportColumn.Where(x => x.ColumnId == shortName.Column_Id).Select(y => y.ColumnName).FirstOrDefault());
                            }

                        }

                        //string[] cols = Columns.TrimEnd(',').Split(',');
                        //string[] colsindex = ColumnsIndex.TrimEnd(',').Split(',');
                        string str = "";
                        string str1 = "";
                      //  DataTable dt = new DataTable("ReportTable");

                        if (ReportModule != null)
                        {

                            if (ReportModule.Report_Module_Name == "Teacher")
                            {

                                var items = new List<int>(new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 });
                                string H1 = "Sr.No", H2 = "Teacher Name", H3 = "Contact No", H4 = "Address", H5 = "Gender", H6 = "Marital Status", H7 = "Join Date", H8 = "Leave Date", H9 = "Physically Challenged ", H10 = "Photo", H11 = "EmailId", H12 = "EmployeeId", H13 = "Group", H14 = "Religion", H15 = "Cast Category", H16 = "Cast", H17 = "Designation", H18 = "Service Category", H19 = "Anniversary Date", H20 = "Education";
                                #region trimdata
                                List<int> lstBoardStageId = new List<int>();
                                if (BoardStageId != "" || BoardStageId != null)
                                {
                                    string[] BSId = BoardStageId.TrimEnd(',').Split(',');

                                    for (int i = 0; i <= BSId.Count() - 1; i++)
                                    {
                                        if (BSId[i] != "")
                                            lstBoardStageId.Add(Convert.ToInt32(BSId[i]));
                                    }
                                }
                                List<int> lstShiftId = new List<int>();
                                if (ShiftId != "" || ShiftId != null)
                                {
                                    string[] ShiftIDs = ShiftId.TrimEnd(',').Split(',');

                                    for (int i = 0; i <= ShiftIDs.Count() - 1; i++)
                                    {
                                        if (ShiftIDs[i] != "")
                                            lstShiftId.Add(Convert.ToInt32(ShiftIDs[i]));
                                    }
                                }
                                List<int> lstClassDivisionId = new List<int>();
                                if (ClassDivisionId != "" || ClassDivisionId != null)
                                {
                                    string[] classDiv = ClassDivisionId.TrimEnd(',').Split(',');

                                    for (int i = 0; i <= classDiv.Count() - 1; i++)
                                    {
                                        if (classDiv[i] != "")
                                            lstClassDivisionId.Add(Convert.ToInt32(classDiv[i]));
                                    }
                                }
                                List<int> lstSubjects = new List<int>();
                                //if (Subjects != "" || Subjects != null)
                                //{
                                    string[] subjs = Subjects.TrimEnd(',').Split(',');
                                    for (int i = 0; i <= subjs.Count() - 1; i++)
                                    {
                                        if (subjs[i] != "")
                                            lstSubjects.Add(Convert.ToInt32(subjs[i]));
                                    }
                                //}

                                #endregion trimdata
                                List<ReportTecaherDetails> resultTeacher = new List<ReportTecaherDetails>();

                                resultTeacher = TeacherDomain.GetReportTeacher1(board.Board_Id, lstBoardStageId, lstShiftId, lstSubjects, lstClassDivisionId, Shortby, lstformat, yearid);
                                float[] widthArry = new float[20];
                                float widthCount = 0;

                                for (int i = 0; i < ColWidth.Count; i++)
                                {
                                    widthArry[i] = ColWidth[i];
                                    widthCount += ColWidth[i];
                                }
                                widthArry = widthArry.Where(x => x != 0).ToArray();
                                table = new PdfPTable(widthArry);
                                table.TotalWidth = 550f;
                                table.LockedWidth = true;
                                table.SetWidths(widthArry);
                                #region CheckHeaderText
                                foreach (var HeaderText in lstRptempcol)
                                {
                                    //code for headerText
                                }
                                #endregion CheckHeaderText
                                int Srno = 1;
                                int count = 0;
                                for (int a = 0; a < colindexid.Count; a = a + 1)
                                {
                                    if (colindexid.Contains(Convert.ToInt32(a.ToString())))
                                    {
                                        #region addcolumnHeadeName
                                        if (a.ToString() == Convert.ToString(0))
                                        {
                                            // dt.Columns.Add(new DataColumn(H1, typeof(string)));
                                            phrase = new Phrase();
                                            phrase.Add(new Chunk(H1, FontFactory.GetFont("Arial Unicode MS,Arial", 8, iTextSharp.text.Font.BOLD, iTextSharp.text.Color.BLACK)));
                                            cell = PhraseCell(phrase, PdfPCell.ALIGN_CENTER);
                                            cell.BorderColor = new iTextSharp.text.Color(229, 229, 229);
                                            cell.FixedHeight = 10f;
                                            table.AddCell(cell);
                                        }
                                        else if (a.ToString() == Convert.ToString(1))
                                        {
                                            // dt.Columns.Add(new DataColumn(H1, typeof(string)));
                                            phrase = new Phrase();
                                            phrase.Add(new Chunk(H2, FontFactory.GetFont("Arial Unicode MS,Arial", 8, iTextSharp.text.Font.BOLD, iTextSharp.text.Color.BLACK)));
                                            cell = PhraseCell(phrase, PdfPCell.ALIGN_CENTER);
                                            cell.BorderColor = new iTextSharp.text.Color(229, 229, 229);
                                            cell.FixedHeight = 10f;
                                            table.AddCell(cell);
                                        }
                                        // .... else if{}  same as above
                                        #endregion addcolumnHeadeName
                                    }                                    
                                }
                               document.Add(table);
                                secondTable = new PdfPTable(widthArry);
                                secondTable.TotalWidth = 550f;
                                secondTable.LockedWidth = true;
                                secondTable.SetWidths(widthArry);
                                foreach (var item in resultTeacher)
                                {

                                    #region rowadd
                                    if (colindexid.Contains(Convert.ToInt32(0)))
                                    {
                                        phrase = new Phrase();
                                        phrase.Add(new Chunk(Convert.ToString(Srno), FontFactory.GetFont("Arial Unicode MS,Arial", 8, iTextSharp.text.Font.BOLD, iTextSharp.text.Color.BLACK)));
                                        secondTableCell = PhraseCell(phrase, PdfPCell.ALIGN_CENTER);
                                        secondTableCell.BorderColor = new iTextSharp.text.Color(229, 229, 229);
                                        secondTableCell.FixedHeight = 50f;
                                        secondTable.AddCell(secondTableCell);
                                    }
                                    else
                                    {
                                    }
                                     // .... if{} same as above
                                    #endregion rowadd
                                    Srno++;

                                }

                                document.Add(secondTable);
                            }
                        }

                        #endregion ReportBind                      
                        filename = filename + now.Hour.ToString("00") + now.Minute.ToString("00") + now.Second.ToString("00") + now.Millisecond.ToString() + now.DayOfYear.ToString("000") + now.Day.ToString("00") + now.Month.ToString("00") + now.Year.ToString("0000") + ".pdf";
                        document.Close();
                        byte[] bytes = memoryStream.ToArray();
                        memoryStream.Close();
                        Response.Clear();
                        Response.ContentType = "application/pdf";
                        Response.AddHeader("Content-Disposition", "attachment; filename=" + filename + "");
                        Response.ContentType = "application/pdf";
                        Response.Buffer = true;
                        Response.Cache.SetCacheability(HttpCacheability.NoCache);
                        Response.BinaryWrite(bytes);
                        Response.End();
                        Response.Close();

                    }
                    return View();
                }
                else
                {
                    return Redirect(BaseUrl);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

如何设置下一页上的大表,如果包含大与iTextSharp

你可以试试

Image.ScaleToFitLineWhenOverflow = false;