itextsharp 导出PDF 包括图片 分页(全面)

//主要代码

 //计算最大table 有多少列
            List<int> clSpanNum = new List<int>();
            clSpanNum.Add(subResult.Count + 5);
            clSpanNum.Add(pList.Count + 5);
            clSpanNum.Add(pListThree.Count + 5);
            clSpanNum.Add(projectListFour.Sum(d => d.OptionNum) + 2);
            int totalSpan = clSpanNum.Max(d => d);
            totalSpan = totalSpan < 10 ? 10 : totalSpan;
            string padfname = string.Format("综合素养报告单-{0}", sId == Service.Constant.LONG_DEFAULT ? className : className + "(" + sName + ")");
            string pdfpath = "~/UploadFile/Downpdf/" + DateTime.Now.ToString("yyMMdd");

            if (!System.IO.Directory.Exists(this.Server.MapPath(pdfpath)))
            {
                System.IO.Directory.CreateDirectory(this.Server.MapPath(pdfpath));
            }
            //复制模板 新pdf文件以身份证号命名(要判断新的文件是否存在)
            string newPdf = Server.MapPath(string.Format("{0}/{1}.pdf", pdfpath, padfname));
            if (!System.IO.File.Exists(newPdf))
            {
                System.IO.File.Create(newPdf).Dispose();//创建文件后一定要是否资源 不然会抛异常
            }
            //设置字体
            BaseFont bfChinese = BaseFont.CreateFont("C:\\WINDOWS\\Fonts\\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            iTextSharp.text.Font fontChinese = new iTextSharp.text.Font(bfChinese, 12, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK); //正常12号字体
            iTextSharp.text.Font boldChinese = new iTextSharp.text.Font(bfChinese, 16, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK); //加粗16号字
            iTextSharp.text.Font bbbChinese = new iTextSharp.text.Font(bfChinese, 12, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK);//加粗12号字

            if (result.Count > 0)
            {

                //创建大小为A4的doc(确定标准的A4纸张的标准边距)
                Document doc = new Document(PageSize.A4, 5, 5, 20, 10);
                //将doc写入到新的pdf中
                FileStream newfs = new FileStream(newPdf, FileMode.Create);
                PdfWriter writer = PdfWriter.GetInstance(doc, newfs);
                //打开doc
                doc.Open();
              

                int studentCount = result.Count;
                int studentIndex = 1;
                foreach (var student in result)
                {
	
  //添加标题  
                Paragraph Title = new Paragraph(yearName + "综合素养报告单", boldChinese);
                Title.Alignment = iTextSharp.text.Rectangle.ALIGN_CENTER;       //设置居中  

                doc.Add(Title);        //将标题段加入PDF文档中  

                //空一行  
                Paragraph nullp = new Paragraph(" ", fontChinese);
                nullp.Leading = 10;
                doc.Add(nullp);  
 
 

 
 
                    float[] widths = new float[totalSpan];
                    for (int i = 0; i < widths.Length; i++)
                    {
                        widths[i] = 0.5f;
                    }

                    #region 学生基本信息
                    //创建一张6列的表格
                    PdfPTable table = new PdfPTable(widths);//float数组中每一个数代表每一列宽度的比例
                    table.TotalWidth = 550f;
                    table.LockedWidth = true;

                    //开始添加单元格(添加单元格的顺序不能打乱)
                    //设置标题
                   // SetCell(table, boldChinese, yearName + "综合素养报告单", 50f, totalSpan, 0, 0);
                    SetCell(table, fontChinese, "班级名称", 29f, 0, 0, 0);
                    SetCell(table, fontChinese, student.ClassName, 29f, 3, 0, 0);
                    SetCell(table, fontChinese, "学生姓名", 29f, 2, 0, 0);
                    SetCell(table, fontChinese, student.StudentName, 29f, totalSpan - 6, 0, 0);
                    SetCell(table, fontChinese, "学校寄语", 100f, 0, 0, 0);
                    PdfPCell valueClassName = new PdfPCell(new Phrase(schoolNote, fontChinese));
                    valueClassName.VerticalAlignment = Element.ALIGN_MIDDLE;
                    valueClassName.HorizontalAlignment = Element.ALIGN_LEFT;
                    valueClassName.FixedHeight = 100f; //设置单元格的高度
                    valueClassName.Colspan = totalSpan - 1;
                    table.AddCell(valueClassName);

                    SetCell(table, fontChinese, "学期评语", 100f, 0, 0, 0);
                    PdfPCell teacherContent = new PdfPCell(new Phrase(student.CommentResul, fontChinese));
                    teacherContent.VerticalAlignment = Element.ALIGN_MIDDLE;
                    teacherContent.HorizontalAlignment = Element.ALIGN_LEFT;
                    teacherContent.FixedHeight = 100f; //设置单元格的高度
                    teacherContent.Colspan = totalSpan - 1;
                    table.AddCell(teacherContent);
                    doc.Add(table);
                    #endregion

                    #region 学科评价一
                    int clspanOne = totalSpan - (eList.Count + 5);
                    PdfPTable tableOne = new PdfPTable(widths);
                    tableOne.TotalWidth = 550f;
                    tableOne.LockedWidth = true;
                    SetCell(tableOne, fontChinese, "学科成绩评价一", 29f, 0, student.resultOne.Count + 1, 0);
                    SetCell(tableOne, fontChinese, "科目", 29f, 0, 0, 0);
                    foreach (var item in eList.OrderBy(d => d.ExamNo).ToList())
                    {
                        SetCell(tableOne, fontChinese, item.ExamName, 29f, 0, 0, 0);
                    }
                    SetCell(tableOne, fontChinese, "总评分数", 29f, 0, 0, 0);
                    SetCell(tableOne, fontChinese, "总评等级", 29f, 0, 0, 0);
                    SetCell(tableOne, fontChinese, "总评学分", 29f, clspanOne + 1, 0, 0);
                    int index = 1;
                    decimal totalScoreOne = student.resultOne.Sum(d => ZHSY.Common.ToolHelper.ConvertToDecimal(d.Score));
                    foreach (var p in student.resultOne)
                    {
                        SetCell(tableOne, fontChinese, p.SubjectName, 29f, 0, 0, 0);
                        foreach (var exam in eList.OrderBy(d => d.ExamNo))
                        {
                            string score = "";
                            if (exam.IsSubjoin == 0)
                            {
                                if (p.ExamInfo != null)
                                {
                                    var mark = p.ExamInfo.Where(d => d.ExamId == exam.ExamId).FirstOrDefault();
                                    score = mark != null ? mark.Score : string.Empty;
                                }

                            }
                            else
                            {
                                if (p.ProInfo != null)
                                {
                                    var mark = p.ProInfo.Where(d => d.ProjectId == exam.ExamId).FirstOrDefault();
                                    score = mark != null ? mark.Vlaue : string.Empty;
                                }
                            }
                            SetCell(tableOne, fontChinese, score, 29f, 0, 0, 0);
                        }
                        SetCell(tableOne, fontChinese, p.Sum, 29f, 0, 0, 0);
                        SetCell(tableOne, fontChinese, p.LevelName, 29f, 0, 0, 0);
                        if (index == 1)
                        {
                            SetCell(tableOne, fontChinese, totalScoreOne.ToString(), 29f, clspanOne + 1, subResult.Count + 1, 0);
                            index++;
                        }

                    }
                    doc.Add(tableOne);


                    #endregion

                    #region 学期评价二
                    int clspanTow = totalSpan - (pList.Count + 5);
                    PdfPTable tableTow = new PdfPTable(widths);
                    tableTow.TotalWidth = 550f;
                    tableTow.LockedWidth = true;
                    SetCell(tableTow, fontChinese, "学科成绩评价二", 29f, 0, student.resultTow.Count + 1, 0);
                    SetCell(tableTow, fontChinese, "科目", 29f, 0, 0, 0);
                    foreach (var item in pList.OrderBy(d => d.ProjectNo))
                    {
                        SetCell(tableTow, fontChinese, item.ProjectName, 29f, 0, 0, 0);
                    }
                    SetCell(tableTow, fontChinese, "总评分数", 29f, 0, 0, 0);
                    SetCell(tableTow, fontChinese, "总评等级", 29f, 0, 0, 0);
                    SetCell(tableTow, fontChinese, "总评学分", 29f, clspanTow + 1, 0, 0);
                    int indexTow = 1;
                    decimal totalScoreTow = student.resultTow.Sum(d => ZHSY.Common.ToolHelper.ConvertToDecimal(d.Score));
                    foreach (var p in student.resultTow)
                    {
                        SetCell(tableTow, fontChinese, p.SubjectName, 29f, 0, 0, 0);
                        foreach (var pj in pList.OrderBy(d => d.ProjectNo))
                        {
                            string score = "";
                            if (p.ProInfo != null)
                            {
                                var mark = p.ProInfo.Where(d => d.ProjectId == pj.ID).FirstOrDefault();
                                score = mark != null ? mark.Vlaue : string.Empty;
                            }
                            SetCell(tableTow, fontChinese, score, 29f, 0, 0, 0);
                        }
                        SetCell(tableTow, fontChinese, p.Sum, 29f, 0, 0, 0);
                        SetCell(tableTow, fontChinese, p.LevelName, 29f, 0, 0, 0);
                        if (indexTow == 1)
                        {
                            SetCell(tableTow, fontChinese, totalScoreTow.ToString(), 29f, clspanTow + 1, student.resultTow.Count, 0);
                            indexTow++;
                        }

                    }
                    doc.Add(tableTow);

                    #endregion

                    #region 拓展课程
                    int clspanThree = totalSpan - (pListThree.Count + 5);
                    PdfPTable tableThree = new PdfPTable(widths);
                    tableThree.TotalWidth = 550f;
                    tableThree.LockedWidth = true;
                    SetCell(tableThree, fontChinese, "拓展课程", 29f, 0, student.resultThree.Count + 2, 0);
                    SetCell(tableThree, fontChinese, "科目", 29f, 0, 0, 0);
                    foreach (var item in pListThree.OrderBy(d => d.ProjectNo))
                    {
                        SetCell(tableThree, fontChinese, item.ProjectName, 29f, 0, 0, 0);
                    }
                    SetCell(tableThree, fontChinese, "总评分数", 29f, 0, 0, 0);
                    SetCell(tableThree, fontChinese, "总评等级", 29f, 0, 0, 0);
                    SetCell(tableThree, fontChinese, "总评学分", 29f, clspanTow + 1, 0, 0);
                    int indexThree = 1;
                    decimal totalScoreThree = student.resultThree.Sum(d => ZHSY.Common.ToolHelper.ConvertToDecimal(d.Score));
                    if (student.resultThree != null && student.resultThree.Count > 0)
                    {
                        foreach (var p in student.resultThree)
                        {
                            SetCell(tableThree, fontChinese, p.SubjectName, 29f, 0, 0, 0);
                            foreach (var pj in pListThree.OrderBy(d => d.ProjectNo))
                            {
                                string score = "";
                                if (p.ProInfo != null)
                                {
                                    var mark = p.ProInfo.Where(d => d.ProjectId == pj.ID).FirstOrDefault();
                                    score = mark != null ? mark.Vlaue : string.Empty;
                                }
                                SetCell(tableThree, fontChinese, score, 29f, 0, 0, 0);
                            }
                            SetCell(tableThree, fontChinese, p.Sum, 29f, 0, 0, 0);
                            SetCell(tableThree, fontChinese, p.LevelName, 29f, 0, 0, 0);
                            if (indexThree == 1)
                            {
                                SetCell(tableThree, fontChinese, totalScoreThree.ToString(), 29f, clspanThree + 1, student.resultThree.Count, 0);
                                indexThree++;
                            }

                        }
                    }
                    else {
                        SetCell(tableThree, fontChinese, "", 29f, totalSpan - 1, 0, 0);
                    }
                    doc.Add(tableThree);

                    #endregion

                    #region 综合实践
                    decimal totalScoreFour = student.resultFour.Sum(d => ZHSY.Common.ToolHelper.ConvertToDecimal(d.Score));
                    int clspanFour = totalSpan - (projectListFour.Sum(d => d.OptionNum) + 2);
                    PdfPTable tableFour = new PdfPTable(widths);
                    tableFour.TotalWidth = 550f;
                    tableFour.LockedWidth = true;
                    SetCell(tableFour, fontChinese, "综合实践评价", 29f, 0, student.resultFour.Count + 3, 0);
                    SetCell(tableFour, fontChinese, "评价项目", 29f, projectListFour.Sum(d => d.OptionNum) + 1, 0, 0);
                    foreach (var item in projectListFour.OrderBy(d => d.ProjectNo))
                    {
                        SetCell(tableFour, fontChinese, item.ProjectName, 29f, item.OptionList.Count, 0, 0);
                    }
                    SetCell(tableFour, fontChinese, "总评学分", 29f, clspanTow + 2, 2, 0);
                    foreach (var pj in projectListFour.OrderBy(d => d.ProjectNo))
                    {
                        foreach (var p in pj.OptionList)
                        {
                            SetCell(tableFour, fontChinese, p.OptionName + "(" + p.OptionValue + ")", 29f, 0, 0, 0);
                        }
                    }
                    foreach (var pj in projectListFour.OrderBy(d => d.ProjectNo))
                    {
                        foreach (var p in pj.OptionList)
                        {
                            var mark = "--";
                            var tt = student.resultFour.Where(d => d.OptionId == p.Id).FirstOrDefault();
                            if (tt != null)
                            {
                                mark = tt.Score > decimal.Zero ? tt.Score.ToString() : "--";
                            }
                            SetCell(tableFour, fontChinese, mark, 29f, 0, 0, 0);
                        }
                    }
                    SetCell(tableFour, fontChinese, totalScoreFour.ToString(), 29f, clspanFour + 2, 0, 0);

                    doc.Add(tableFour);
                    #endregion

                    #region 节庆获奖
                    int fileFiveNum = student.fileList.Where(d => d.type == 0).Count();
                    decimal totalScoreFive = student.resultFive.Sum(d => ZHSY.Common.ToolHelper.ConvertToDecimal(d.Score));
                    int clspanFive = totalSpan - 5;
                    PdfPTable tableFive = new PdfPTable(widths);
                    tableFive.TotalWidth = 550f;
                    tableFive.LockedWidth = true;
                    SetCell(tableFive, fontChinese, "节庆获奖", 29f, 0, student.resultFive.Count + 3 + fileFiveNum + 1, 0);
                    SetCell(tableFive, fontChinese, "节庆名称", 29f, 2, 0, 0);
                    SetCell(tableFive, fontChinese, "获奖时间", 29f, 2, 0, 0);
                    SetCell(tableFive, fontChinese, "获奖等级", 29f, 2, 0, 0);
                    SetCell(tableFive, fontChinese, "折算学分", 29f, 0, 0, 0);
                    SetCell(tableFive, fontChinese, "总评学分", 29f, clspanFive + 1, 0, 0);

                    int indexFive = 1;
                    if (student.resultFive != null && student.resultFive.Count > 0)
                    {
                        foreach (var fl in student.resultFive)
                        {
                            SetCell(tableFive, fontChinese, fl.FestivalName, 29f, 2, 0, 0);
                            SetCell(tableFive, fontChinese, fl.Data, 29f, 2, 0, 0);
                            SetCell(tableFive, fontChinese, fl.Convert, 29f, 2, 0, 0);
                            SetCell(tableFive, fontChinese, fl.Score.ToString(), 29f, 0, 0, 0);
                            if (indexFive == 1)
                            {
                                SetCell(tableFive, fontChinese, totalScoreFive.ToString(), 29f, clspanFive + 1, student.resultFive.Count, 0);
                                indexFive++;
                            }
                        }
                    }
                    else
                    {
                        SetCell(tableFive, fontChinese, "", 29f, totalSpan - 1, 0, 0);
                    }
                    SetCell(tableFive, fontChinese, "获奖证书", 29f, clspanFive + 5, 0, 0);
                    var filefive = student.fileList.Where(d => d.type == 0).ToList();
                    if (filefive != null && filefive.Count > 0)
                    {
                        foreach (var fp in filefive)
                        {
                            //下面对图片进行操作  
                            Image image = Image.GetInstance(Server.MapPath(fp.filePath));
                            float percentage = 1;
                            //这里都是图片最原始的宽度与高度  
                            float resizedWidht = image.Width;
                            float resizedHeight = image.Height;
                            ////这里用计算出来的百分比来缩小图片  
                            image.ScalePercent(percentage * 50);
                            //让图片的中心点与页面的中心店进行重合  
                            //image.SetAbsolutePosition(doc.PageSize.Width / 2 - resizedWidht / 2, doc.PageSize.Height / 2 - resizedHeight / 2);
                            image.ScaleToFit(200f, 230f);
                            image.BorderWidth = 5f;
                            PdfPCell imgCell = new PdfPCell(image);
                            imgCell.VerticalAlignment = Element.ALIGN_MIDDLE;
                            imgCell.HorizontalAlignment = Element.ALIGN_CENTER;
                            imgCell.Colspan = totalSpan - 1;
                            imgCell.FixedHeight = 200f;
                            tableFive.AddCell(imgCell);
                        }
                    }
                    else
                    {
                        SetCell(tableFive, fontChinese, "", 29f, totalSpan - 1, 0, 0);
                    }

                    //可以使单元格内容跨页显示
                    tableFive.SplitLate = false;
                    tableFive.SplitRows = true;
                    doc.Add(tableFive);
                    #endregion

                    #region 特色课程获奖
                    int fileSixNum = student.fileList.Where(d => d.type == 1).Count();
                    decimal totalScoreSix = student.resultSix.Sum(d => ZHSY.Common.ToolHelper.ConvertToDecimal(d.Score));
                    int clspanSix = totalSpan - 5;
                    PdfPTable tableSix = new PdfPTable(widths);
                    tableSix.TotalWidth = 550f;
                    tableSix.LockedWidth = true;
                    SetCell(tableSix, fontChinese, "特色课程获奖", 29f, 0, student.resultSix.Count + 3 + fileSixNum + 2, 0);
                    SetCell(tableSix, fontChinese, "获奖名称", 29f, 2, 0, 0);
                    SetCell(tableSix, fontChinese, "获奖时间", 29f, 2, 0, 0);
                    SetCell(tableSix, fontChinese, "获奖等级", 29f, 2, 0, 0);
                    SetCell(tableSix, fontChinese, "折算学分", 29f, 0, 0, 0);
                    SetCell(tableSix, fontChinese, "总评学分", 29f, clspanFive + 1, 0, 0);

                    int indexSix = 1;
                    if (student.resultSix != null && student.resultSix.Count > 0)
                    {
                        foreach (var fl in student.resultSix)
                        {
                            SetCell(tableSix, fontChinese, fl.AwardName, 29f, 2, 0, 0);
                            SetCell(tableSix, fontChinese, fl.Data, 29f, 2, 0, 0);
                            SetCell(tableSix, fontChinese, fl.Convert, 29f, 2, 0, 0);
                            SetCell(tableSix, fontChinese, fl.Score.ToString(), 29f, 0, 0, 0);
                            if (indexSix == 1)
                            {
                                SetCell(tableSix, fontChinese, totalScoreSix.ToString(), 29f, clspanSix + 1, student.resultSix.Count, 0);
                                indexFive++;
                            }
                        }
                    }
                    else
                    {
                        SetCell(tableSix, fontChinese, "", 29f, clspanSix + 5, 0, 0);
                    }
                    SetCell(tableSix, fontChinese, "获奖证书", 29f, clspanSix + 5, 0, 0);
                    var fileSix = student.fileList.Where(d => d.type == 1).ToList();
                    if (fileSix != null && fileSix.Count > 0)
                    {
                        foreach (var fp in fileSix)
                        {
                            //下面对图片进行操作  
                            Image image = Image.GetInstance(Server.MapPath(fp.filePath));
                            float percentage = 1;
                            //这里都是图片最原始的宽度与高度  
                            float resizedWidht = image.Width;
                            float resizedHeight = image.Height;
                            ////这里用计算出来的百分比来缩小图片  
                            image.ScalePercent(percentage * 50);
                            //让图片的中心点与页面的中心店进行重合  
                            //image.SetAbsolutePosition(doc.PageSize.Width / 2 - resizedWidht / 2, doc.PageSize.Height / 2 - resizedHeight / 2);
                            image.ScaleToFit(200f, 230f);
                            image.BorderWidth = 5f;
                            PdfPCell imgCell = new PdfPCell(image);
                            imgCell.VerticalAlignment = Element.ALIGN_MIDDLE;
                            imgCell.HorizontalAlignment = Element.ALIGN_CENTER;
                            imgCell.Colspan = totalSpan - 1;
                            imgCell.FixedHeight = 200f;
                            tableSix.AddCell(imgCell);
                        }
                    }
                    else
                    {
                        SetCell(tableSix, fontChinese, "", 29f, totalSpan - 1, 0, 0);
                    }


                    doc.Add(tableSix);
                    #endregion

                    #region 家长寄语 自己期望
                    PdfPTable tableNote = new PdfPTable(widths);//float数组中每一个数代表每一列宽度的比例
                    tableNote.TotalWidth = 550f;
                    tableNote.LockedWidth = true;

                    SetCell(tableNote, fontChinese, "家长寄语及期望", 100f, 0, 0, 0);
                    PdfPCell noteCell1 = new PdfPCell(new Phrase("", fontChinese));
                    noteCell1.VerticalAlignment = Element.ALIGN_MIDDLE;
                    noteCell1.HorizontalAlignment = Element.ALIGN_LEFT;
                    noteCell1.FixedHeight = 100f; //设置单元格的高度
                    noteCell1.Colspan = totalSpan - 1;
                    tableNote.AddCell(noteCell1);

                    SetCell(tableNote, fontChinese, "自我评语及愿望", 100f, 0, 0, 0);
                    PdfPCell noteCell2 = new PdfPCell(new Phrase("", fontChinese));
                    noteCell2.VerticalAlignment = Element.ALIGN_MIDDLE;
                    noteCell2.HorizontalAlignment = Element.ALIGN_LEFT;
                    noteCell2.FixedHeight = 100f; //设置单元格的高度
                    noteCell2.Colspan = totalSpan - 1;
                    tableNote.AddCell(noteCell2);
                    tableNote.SplitLate = false;
                    doc.Add(tableNote);
                    #endregion

                    //每个学生相关内容写入完之后,新开一个page接着写下一个学生数据,最后一个学生结束后不需要创建page
                    //所以需要加判断 studentIndex != studentCount
                    if (studentIndex != studentCount)
                    {
                        doc.NewPage();
                    }
                    studentIndex++;
                }
                doc.Close();

                string fileName = System.IO.Path.GetFileName(newPdf);
                FileStream fs = new FileStream(newPdf, FileMode.Open);

                byte[] bytes = new byte[(int)fs.Length];
                fs.Read(bytes, 0, bytes.Length);
                fs.Close();
                return File(bytes, "application/ms-pdf", fileName);
            }

 public void SetCell(PdfPTable table, Font fontChinese, string cellName, float fixedHeight, int colSpan, int rowSpan, float width)
        {
            PdfPCell valueClassName = new PdfPCell(new Phrase(cellName, fontChinese));
            valueClassName.VerticalAlignment = Element.ALIGN_MIDDLE;
            valueClassName.HorizontalAlignment = Element.ALIGN_CENTER;
            //设置单元格的高度 这里需要注意 如果不设置 FixedHeight,MinimumHeight 单元格文本过多时,就不会换行,并且会隐藏掉部分内容
            valueClassName.FixedHeight = fixedHeight; 
            valueClassName.MinimumHeight = fixedHeight;
            if (width > 0)
            {
                valueClassName.Width = width;
            }

            if (colSpan > 0)
            {
                valueClassName.Colspan = colSpan;
            }
            if (rowSpan > 0)
            {
                valueClassName.Rowspan = rowSpan;
            }
            table.AddCell(valueClassName);
        }


 

猜你喜欢

转载自blog.csdn.net/michaelgong/article/details/78923340