mvc导出数据到pdf


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<int> list = new List<int> { };
                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

时间: 2024-10-29 15:33:37

mvc导出数据到pdf的相关文章

MVC导出数据到EXCEL新方法:将视图或分部视图转换为HTML后再直接返回FileResult

MVC导出数据到EXCEL新方法:将视图或分部视图转换为HTML后再直接返回FileResult 导出EXCEL方法总结:MVC导出数据到EXCEL的方法有很多种,常见的是: 1.采用EXCEL COM组件来动态生成XLS文件并保存到服务器上,然后转到该文件存放路径即可:优点:可设置丰富的EXCEL格式,缺点:需要依赖EXCEL组件,且EXCEL进程在服务器中无法及时关闭,以及服务器上会存留大量的不必要的XLS文件: 2.设置输出头为:application/ms-excel,再输出拼接的HTM

MVC导出Excel到客户端

MVC导出数据到Excel详解 今天为大家分享一个利用NPIO导出数据到Excel 客户端的例子!(刚毕业的小白,第一次写博,如有错误 还望各位大咖指正) 1.NPOI官方网站:(http://npoi.codeplex.com/) 需要引用的dll文件如下: 2.用到的ExcelHelper类: 1 using Common.Logging; 2 using NPOI.HPSF; 3 using NPOI.HSSF.UserModel; 4 using NPOI.HSSF.Util; 5 us

AspxGridView导出excel、pdf

AspxGridView导出excel.pdf ASPxGridViewExporter用于ASPxGridView的数据导出,导出的格式有csv,pdf,rtf,xls,使用非常简单,只用一个函数就可以完成数据的导出. 关于ASPxGridView的数据绑定就不用多说了,主要介绍一下数据导出 1.拖放一个ASPxGridViewExporter,ID设置为你要导出的AspxGridView的ID 2.拖放一个按钮,实现按钮的方法就一句话 public void ToExcel(object s

12.在AspxGridView中导出数据

内置数据导出的前提条件 使用DevExpress.Web.ASPxGridView.Export.ASPxGridViewExporter实现数据导出.注意一定要将该控件放在页面上才可. 使用该控件必须引入以下dll文件: DevExpress.Utils.v9.1.dllDevExpress.Web.ASPxGridView.v9.1.Export.dllDevExpress.XtraPrinting.v9.1.dll 在Asp.Net页面注册该控件的代码: <%@ Register Asse

MVC 导出 简单范例合适初学者

界面: <div id="tbl">                 <a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-remove',plain:true" onclick="Delete()">删除</a>                 <a h

导出数据到Excel表格

开发工具与关键技术:Visual Studio 和 ASP.NET.MVC,作者:陈鸿鹏撰写时间:2019年5月25日123下面是我们来学习的导出数据到Excel表格的总结首先在视图层写导出数据的点击事件function 自定义点击事件名(){//然后这里获取当前表格数据的筛选条件var 自定义下拉框名 = $("#下拉框id “).val();//后面根据你的条件数依次写……var 自定义文本框名 = $(”#文本框id ").val(); //然后这里写判断它是否为空 if (自定

PHPexcel导出数据

百度PHPexcel 进入后 选择branches  进入选择版本 拷贝classes文件 改名为PHPexcel 下面是我用thinkphp3.2.3写的一个简单导出 public function PHPexcel(){ $path=str_replace('\\','/',__FILE__);//替\为/ $arr=explode('/',$path); $str = $arr[0].'/'.$arr[1].'/'.$arr[2].'/'.$arr[3].'/';//拼装文件路径 $a =

mysql数据库导入导出数据

导入数据: 形式:load data infile '路径' into table xxx;outfile:将信息输出到文件上(自动创建文件,不可以重新文件,为了保护文件)select * from hd_cate; select * into outfile 'e:/demo/one' from hd_cate;生成的文件格式;默认的,采用行来区分记录,而采用制表符,来区分字段为了满足某种特别的需求,会采用不同的分割方式,支持,在导出数据时,设置记录,与字段的分隔符 通过如下的选项fields

Oracle—— 导入/导出 数据:exp,imp 命令

exp,imp 命令是需要在windows  的 cmd  命令中执行的命令,主要用于数据的导入和导出工作,方便高效. 远程地址--  @ip:port/orcl   注:该远程地址不写,就意味着执行本地的库. Oracle的数据导出 (1)导出数据的提示模式: exp  jl_bhps/[email protected]:1521/orcl (2)表方式:将指定表的数据导出. exp  jl_bhps/[email protected]:1521/orcl  file=d:temp/1.dmp