1. 程式人生 > >itextsharp 匯出PDF 包括圖片 分頁(全面)

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);
        }