博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
mvc导出数据到pdf
阅读量:6984 次
发布时间:2019-06-27

本文共 10171 字,大约阅读时间需要 33 分钟。

 

using iTextSharp;

using iTextSharp.text;
using iTextSharp.text.pdf;

public ActionResult PdfExport(int y = 2014, int m = 1, string departmentcd = "",string outFlag="1")        {            System.Collections.ArrayList anonymousEntities = new System.Collections.ArrayList();            foreach (var item in db.WorkRecords.ToList())            {                WorkRecords workrecord = new WorkRecords();                workrecord.UserCD = item.UserCD;                workrecord.UserName = item.UserName;                anonymousEntities.Add(workrecord);            }            byte[] file = new byte[1];            string depname = new BLL.DepartMentsBLL().GetDepartmentNameByCD(int.Parse(departmentcd));            string filename = depname + y.ToString() + "年" + m.ToString() + "月.pdf";           // filename = HttpUtility.UrlEncode(filename);            Document document = new Document(PageSize.A4, 5, 5, 20, 10);            //PdfWriter writer = PdfWriter.GetInstance(document, new System.IO.FileStream(System.Web.HttpContext.Current.Server.MapPath("/material/pdfsample.pdf"), System.IO.FileMode.Create));            PdfWriter writer = PdfWriter.GetInstance(document, new System.IO.FileStream(System.Web.HttpContext.Current.Server.MapPath("/PDF/pdfsample.pdf"), System.IO.FileMode.Create));             BaseFont bfChinese =iTextSharp.text.pdf.BaseFont.CreateFont(@"C:\WINDOWS\Fonts\MSMINCHO.TTC,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);            Font fontChinese1 = new Font(bfChinese, 10);            Font ftitle = new Font(bfChinese, 16, Font.NORMAL, BaseColor.BLACK);            Font fontRukuHeader = new Font(bfChinese, 14, Font.NORMAL, BaseColor.BLACK);            Font footerChinese = new Font(bfChinese,12, Font.NORMAL, BaseColor.BLACK);            Font footerChinese_3 = new Font(bfChinese, 9, Font.NORMAL, BaseColor.BLACK);            document.Open();            Paragraph title1 = new Paragraph("注意事項", ftitle);            title1.Alignment = Element.ALIGN_LEFT;             document.Add(title1);            Paragraph title2 = new Paragraph("申请", ftitle);            title2.Alignment = Element.ALIGN_CENTER;             document.Add(title2);            document.NewPage();//创建下一页            PdfPTable table = new PdfPTable(6);            //Paragraph title3 = new Paragraph("一覧\n", ftitle);            //title3.Alignment = Element.ALIGN_LEFT;             //document.Add(title3);            Chunk ch = new Chunk("一覧");            ch.setLineHeight(2);            ch.Font = ftitle;            document.Add(ch);                          table.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;            table.DefaultCell.VerticalAlignment = PdfPCell.ALIGN_CENTER;            table.WidthPercentage = 90;            Font headerfont1 = new Font(bfChinese, 12, Font.BOLD, BaseColor.WHITE);            //table header            table.AddCell(makerCell("社員番号", headerfont1));            table.AddCell(makerCell("社員名", headerfont1));            table.AddCell(makerCell("時間外", headerfont1));            table.AddCell(makerCell("休日出勤", headerfont1));            table.AddCell(makerCell("祝日出勤", headerfont1));            table.AddCell(makerCell("総計", headerfont1));                               string DepartmentCDs = "";                if (String.IsNullOrEmpty(departmentcd))                {                    departmentcd = new NewWorkManager.BLL.UsersBLL().GetDepartmentCD(User.Identity.Name).ToString();                    DepartmentCDs = departmentcd;                }                else                {                    int intid = int.Parse(departmentcd);                    var dep = db.Departments.Where(a => a.FatherDepartmentCD == intid).ToList();                    foreach (var item in dep)                    {                        DepartmentCDs += item.DepartmentCD.ToString() + ",";                        var smalldep = db.Departments.Where(a => a.FatherDepartmentCD == item.DepartmentCD).ToList();                        foreach (var smallitem in smalldep)                        {                            DepartmentCDs += smallitem.DepartmentCD.ToString() + ",";                        }                    }                }                ViewBag.id = new SelectList(db.Departments.Where(a => a.IsActiveFlg == 1), "DepartmentCD", "DepartmentName", departmentcd);                string[] s = DepartmentCDs.Split(new char[] { ',' });                List
list = new List
{ }; foreach (var a in s) { if (!String.IsNullOrEmpty(a)) { list.Add(int.Parse(a)); } } list.Add(int.Parse(departmentcd)); var dbthisDepartment = from w in db.WorkRecords where list.Contains(w.DepartmentCD) select w; DateTime clearmonth = DateTime.Parse(y.ToString() + "/" + m.ToString() + "/1"); var dbapplication = dbthisDepartment.Where(a => a.ClearingMonth == clearmonth && a.ApproveFlg1 == 1 && a.ApproveFlg2 == 1 && (a.IsAdjustFlg == 0 || (a.IsAdjustFlg == 1 && a.WorkType == 3))).ToList(); table.DefaultCell.HorizontalAlignment = PdfPCell.ALIGN_CENTER; foreach (var item in dbapplication.Select(a => a.UserCD).Distinct().ToList()) { table.AddCell(new Phrase(item.ToString(), footerChinese)); table.AddCell(new Phrase(new NewWorkManager.BLL.UsersBLL().getRealNameByName(item).ToString(), footerChinese)); table.AddCell(new Phrase(dbapplication.Where(a => a.UserCD == item && a.WorkType == 1).Select(a => a.WorkTimeTotalHour).Sum().ToString(), footerChinese)); table.AddCell(new Phrase(dbapplication.Where(a => a.UserCD == item && (a.WorkType == 2 || (a.WorkType == 3 && a.IsAdjustFlg == 1))).Select(a => a.WorkTimeTotalHour).Sum().ToString(), footerChinese)); table.AddCell(new Phrase(dbapplication.Where(a => a.UserCD == item && a.WorkType == 3 && a.IsAdjustFlg == 0).Select(a => a.WorkTimeTotalHour).Sum().ToString(), footerChinese)); table.AddCell(new Phrase(dbapplication.Where(a => a.UserCD == item).Select(a => a.WorkTimeTotalHour).Sum().ToString(), footerChinese)); } table.AddCell(new Phrase("")); table.AddCell(new Phrase("合計",footerChinese)); table.AddCell(new Phrase(dbapplication.Where(a => a.WorkType == 1).Select(a => a.WorkTimeTotalHour).Sum().ToString(),footerChinese)); table.AddCell(new Phrase(dbapplication.Where(a => (a.WorkType == 2 || (a.WorkType == 3 && a.IsAdjustFlg == 1))).Select(a => a.WorkTimeTotalHour).Sum().ToString(),footerChinese)); table.AddCell(new Phrase(dbapplication.Where(a => a.WorkType == 3 && a.IsAdjustFlg == 0).Select(a => a.WorkTimeTotalHour).Sum().ToString(),footerChinese)); table.AddCell(new Phrase(dbapplication.Select(a => a.WorkTimeTotalHour).Sum().ToString(),footerChinese)); document.Add(table); document.Close(); string fullFileName = System.Web.HttpContext.Current.Server.MapPath("/PDF/pdfsample.pdf"); Byte[] btArray = WriteToPdf(fullFileName, DateTime.Now.ToString("yyyyMMddhhmmssff"), bfChinese); //fullFileName = Server.MapPath("/material/pdfsample.pdf"); FileStream fs = new FileStream(fullFileName, FileMode.Create, FileAccess.Write); fs.Write(btArray, 0, btArray.Length); fs.Flush(); fs.Close(); //fullFileName = Server.MapPath("/material/pdfsample.pdf"); filename = depname + y.ToString() + "年" + m.ToString() + "月.pdf"; FileInfo downloadFile = new FileInfo(fullFileName); Response.Clear(); Response.ClearHeaders(); Response.Buffer = false; Response.ContentType = "application/octet-stream"; Response.AppendHeader("Content-Disposition", "attachment;filename=" + filename); Response.AppendHeader("Content-Length", downloadFile.Length.ToString()); //System.Web.HttpContext.Current.Response.WriteFile(downloadFile.FullName); Response.WriteFile(downloadFile.FullName); Response.Flush(); Response.End(); return null; } public PdfPCell makerCell(string str,Font fon){ PdfPCell cell=new PdfPCell(new Phrase(str,fon)); BaseColor bs = new BaseColor(System.Drawing.Color.FromArgb(79, 129, 189)); cell.BackgroundColor = bs; return cell; } public static byte[] WriteToPdf(string sourceFile, string stringToWriteToPdf, BaseFont bfChinese) { PdfReader reader = new PdfReader(sourceFile); using (MemoryStream stream = new MemoryStream()) { PdfStamper pdfstamper = new PdfStamper(reader, stream); for (int i = 1; i <= reader.NumberOfPages; i++) { Rectangle pageSize = reader.GetPageSizeWithRotation(i); PdfContentByte pdfpageContents = pdfstamper.GetUnderContent(i); pdfpageContents.BeginText(); pdfpageContents.SetFontAndSize(bfChinese, 40); pdfpageContents.SetRGBColorFill(192, 192, 192); float textAngle = 45.0f; pdfpageContents.ShowTextAligned(PdfContentByte.ALIGN_CENTER, stringToWriteToPdf, pageSize.Width / 2, pageSize.Height / 2, textAngle); pdfpageContents.EndText(); } pdfstamper.FormFlattening = true; pdfstamper.Close(); reader.Close(); return stream.ToArray(); } }

参照:http://www.cnblogs.com/hfliyi/archive/2012/07/07/2580763.html

http://www.cnblogs.com/LifelongLearning/archive/2011/06/22/2086802.html

http://blog.csdn.net/aeolus1019/article/details/8208226

http://www.cnblogs.com/yangfan/archive/2008/05/23/1205976.html

转载于:https://www.cnblogs.com/yaoqj/p/4238161.html

你可能感兴趣的文章
ES6新特征总结与介绍——声明与表达式
查看>>
python3实现抓取网页资源的 N 种方法(内附200GPython学习资料)
查看>>
不用软件,手动修复双系统引导进win7,xp的多种方法
查看>>
python 访问需要HTTP Basic Authentication认证的资源
查看>>
java中比较字符串的大小用String的compareTo()
查看>>
plist使用
查看>>
Linux RAR 安装和使用
查看>>
【OC】【一秒就会】【collectionView 头部吸住功能】
查看>>
51CTO下载 好资料分享
查看>>
linux 下转换UTC到本地时间
查看>>
Linux的起源与各发行版的基本知识
查看>>
单播包、广播包、组播包、洪泛包
查看>>
iptables命令结构之命令
查看>>
RabbitMQ之Exchange分类
查看>>
综合布线系统的构成
查看>>
计算机硬件 — 计算机简介
查看>>
关于重写session实现的时候可能会导至nginx 502的问题
查看>>
7z(p7zip)压缩软件在Linux下的安装和使用
查看>>
jetbrick-template 1.1.0 发布,支持 #tag, #macro, layout
查看>>
TCP的六个控制位
查看>>