在这个示例中,咱们使用的是微软给咱们提供的数据库,也就是家喻户晓的Northwind数据库。要下载Microsoft的免费样本Northwind数据库,您须要访问如下URL。下载Northwind数据库在页面上,您将找到下载按钮,如如下屏幕截图所示。html
若是由于数据库版本问题或其余缘由,附加不上,那你就用那几个脚本文件。数据库
这玩腻更新的仍是比较快的,因此可用性仍是比较大的。如今咱们建立一个model(用于绑定图标值)浏览器
public class OrderModel
{
public string ShipCity { get; set; } public int TotalOrders { get; set; } }
咱们如今确定是要去建立咱们的控制器了,定义以下。app
using System;
using System.Collections.Generic; using System.Linq; using System.Web.Mvc; using System.IO; using iTextSharp.text; using iTextSharp.text.pdf; using WebApplication1.Models; using System.Web.Helpers; namespace WebApplication1.Controllers { public class PdfController : Controller { public static PdfContext pdfcontextoBJ = new PdfContext(); // GET: Pdf public ActionResult Index() { byte[] bytes = PopulateChart(); ViewBag.ChartImageUrl = "data:image/png;base64," + Convert.ToBase64String(bytes, 0, bytes.Length); return View(); } [HttpPost] public FileResult Export() { byte[] bytes = PopulateChart(); ViewBag.ChartImageUrl = "data:image/png;base64," + Convert.ToBase64String(bytes, 0, bytes.Length); using (MemoryStream stream = new System.IO.MemoryStream()) { //Initialize the PDF document object. using (Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 10f)) { PdfWriter writer = PdfWriter.GetInstance(pdfDoc, stream); pdfDoc.Open(); //Add the Image file to the PDF document object. iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(bytes); pdfDoc.Add(img); pdfDoc.Close(); //Download the PDF file. return File(stream.ToArray(), "application/pdf", "Chart.pdf"); } } } private static byte[] PopulateChart() { List<OrderModel> chartData = new List<OrderModel>(); //根据id统计的脚本 var objList = pdfcontextoBJ.Orders.GroupBy(u => u.ShipCity) .Select(s => new { TotalOrders = s.Key, count = s.Count() }).ToList().Take(5).ToList(); foreach (var item in objList) { chartData.Add(new OrderModel() { TotalOrders = item.count, ShipCity = item.TotalOrders }); } Chart chart = new Chart(width: 500, height: 500, theme: ChartTheme.Blue); chart.AddTitle("USA City Distribution"); chart.AddSeries("Default", chartType: "Pie", xValue: chartData, xField: "ShipCity", yValues: chartData, yFields: "TotalOrders"); return chart.GetBytes(format: "jpeg"); } } }
在view中定义以下:spa
@{
Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <img alt="Chart" src="@ViewBag.ChartImageUrl" style="height:300px; width:300px" /> <br /> @using (Html.BeginForm("Export", "Pdf", FormMethod.Post)) { <input type="submit" id="btnSubmit" value="Export" /> } </body> </html>