PDF 下载:
视图:
//制造数据 <table class="table table-bordered"> <tr> <th>PDF导出 @Html.ActionLink("导出", "PDFPost", new { to = "pdf" })</th> </tr> @using System.Data @{ var data = new DataTable(); data.Columns.Add("Id", typeof(int)); data.Columns.Add("Name", typeof(string)); data.Columns.Add("Age", typeof(int)); DataRow dr; for (int i = 0; i < 20; i++) { dr = data.NewRow(); dr[0] = i; dr[1] = Guid.NewGuid().ToString().Substring(0, 6); dr[2] = i.ToString().Substring(0, 1) + i.ToString().Substring(0, 1); data.Rows.Add(dr); } } <tr> <td>@data.Columns[0]</td> <td>@data.Columns[1]</td> <td>@data.Columns[2]</td> </tr> @for (int i = 0; i < data.Rows.Count; i++) { <tr> <td>@data.Rows[i][0].ToString()</td> <td>@data.Rows[i][1].ToString()</td> <td>@data.Rows[i][2].ToString()</td> </tr> } </table>
//控制器 需要下载包源 iTextSharp
public FileResult PDFPost() { //准备PDF var pdfDoc = new Document(PageSize.LETTER, 40f, 40f, 60f, 60f); var path = Server.MapPath("~/App_Data/PDF/New.pdf"); PdfWriter.GetInstance(pdfDoc, new FileStream(path, FileMode.OpenOrCreate)); pdfDoc.Open();
//添加Logo var logoPath = Server.MapPath("~/App_Data/File/38.jpg"); using (FileStream fs = new FileStream(logoPath, FileMode.Open)) { var png = iTextSharp.text.Image.GetInstance(System.Drawing.Image.FromStream(fs), ImageFormat.Png); png.ScalePercent(5.0f); png.SetAbsolutePosition(pdfDoc.Left, pdfDoc.Top); pdfDoc.Add(png); } //添加一个空行 var spacer = new Paragraph(""); spacer.SpacingBefore = 10f; spacer.SpacingAfter = 10f; pdfDoc.Add(spacer);
//设置显示内容Table var table = new PdfPTable(new[] { 0.75f, 1f, 1.5f }) { //设置表格显示样式 HorizontalAlignment = 0, WidthPercentage = 100, DefaultCell = { MinimumHeight = 20 } }; //添加合并表头 string ARIALUNI_TFF = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "simhei.ttf"); BaseFont df = BaseFont.CreateFont(ARIALUNI_TFF, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); Font f = new Font(df, 12, Font.NORMAL);
var mergeHeader = new PdfPCell(new Phrase("PDF文档格式标题", f)) { Colspan = 3, HorizontalAlignment = 1, MinimumHeight = 30f }; table.AddCell(mergeHeader);
//模拟数据 var data = new DataTable(); data.Columns.Add("Id", typeof(int)); data.Columns.Add("Name", typeof(string)); data.Columns.Add("Age", typeof(int)); DataRow dr; for (int i = 0; i < 20; i++) { dr = data.NewRow(); dr[0] = i; dr[1] = Guid.NewGuid().ToString().Substring(0, 6); dr[2] = i.ToString().Substring(0, 1) + i.ToString().Substring(0, 1); data.Rows.Add(dr); } //数据源内容添加到PDF表格中 data.Columns.OfType<DataColumn>().ToList().ForEach(a => table.AddCell(a.ColumnName)); data.Rows.OfType<DataRow>().ToList().ForEach(r => { r.ItemArray.ToList().ForEach(item => table.AddCell(item.ToString())); });
//显示内容的表格添加 pdfDoc.Add(table);
//关闭 pdfDoc.Close();
//下载 return File(path, "application/force-download", Path.GetFileName(path)); }
|
请发表评论