You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在MVC 5 WebAPI中生成含柱状图、饼图的报表PDF

Hey there! Let's walk through a practical way to generate a PDF report with bar and pie charts in an MVC 5 WebAPI. I'll use widely-used libraries that play well with .NET Framework, and break everything down step by step.

Step 1: Install Required Libraries

First, we'll need two main tools to get this done:

  • iTextSharp: For creating and manipulating PDF documents.
  • OxyPlot.SkiaSharp: For generating bar/pie charts and exporting them as image bytes (perfect for embedding into PDFs).

Install these via NuGet Package Manager Console:

Install-Package iTextSharp -Version 5.5.13.2
Install-Package OxyPlot.Core
Install-Package OxyPlot.SkiaSharp
Step 2: Create a Chart Generator Helper Class

Let's make a reusable class to generate our charts. This keeps our controller code clean and makes charts easy to modify later.

using OxyPlot;
using OxyPlot.Series;
using OxyPlot.SkiaSharp;
using System.IO;

public static class ChartGenerator
{
    // Generate a bar chart for monthly sales data
    public static byte[] GenerateMonthlySalesBarChart()
    {
        var plotModel = new PlotModel { Title = "Monthly Sales Performance" };

        // Add column series with sample data
        var columnSeries = new ColumnSeries();
        columnSeries.Items.Add(new ColumnItem(45000) { CategoryIndex = 0 });
        columnSeries.Items.Add(new ColumnItem(62000) { CategoryIndex = 1 });
        columnSeries.Items.Add(new ColumnItem(38000) { CategoryIndex = 2 });
        columnSeries.Items.Add(new ColumnItem(75000) { CategoryIndex = 3 });

        plotModel.Series.Add(columnSeries);

        // Add axes
        plotModel.Axes.Add(new CategoryAxis 
        { 
            Position = AxisPosition.Bottom, 
            Items = new[] { "Jan", "Feb", "Mar", "Apr" } 
        });
        plotModel.Axes.Add(new LinearAxis 
        { 
            Position = AxisPosition.Left, 
            Title = "Sales (USD)", 
            Minimum = 0 
        });

        // Export chart to PNG bytes
        using var memoryStream = new MemoryStream();
        var exporter = new PngExporter { Width = 600, Height = 400 };
        exporter.Export(plotModel, memoryStream);
        return memoryStream.ToArray();
    }

    // Generate a pie chart for product market share
    public static byte[] GenerateProductSharePieChart()
    {
        var plotModel = new PlotModel { Title = "Product Market Share" };

        var pieSeries = new PieSeries 
        { 
            StrokeThickness = 2, 
            InsideLabelPosition = 0.8, 
            AngleSpan = 360, 
            StartAngle = 0 
        };

        // Add pie slices with sample data
        pieSeries.Slices.Add(new PieSlice("Product A", 30) { Fill = OxyColors.SkyBlue });
        pieSeries.Slices.Add(new PieSlice("Product B", 45) { Fill = OxyColors.Orange });
        pieSeries.Slices.Add(new PieSlice("Product C", 25) { Fill = OxyColors.ForestGreen });

        plotModel.Series.Add(pieSeries);

        // Export chart to PNG bytes
        using var memoryStream = new MemoryStream();
        var exporter = new PngExporter { Width = 600, Height = 400 };
        exporter.Export(plotModel, memoryStream);
        return memoryStream.ToArray();
    }
}
Step 3: Build the PDF in Your WebAPI Controller

Now, create an API endpoint that assembles the PDF, adds the charts, and returns it to the client as a downloadable file.

using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
using System.Web.Http;

public class ReportController : ApiController
{
    [HttpGet]
    public IHttpActionResult GetSalesReport()
    {
        // Initialize PDF document (A4 size with margins)
        var document = new Document(PageSize.A4, 20, 20, 20, 20);
        using var pdfStream = new MemoryStream();
        var writer = PdfWriter.GetInstance(document, pdfStream);

        document.Open();

        // Add report title
        var title = new Paragraph("Quarterly Sales Report", 
            FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 18));
        title.Alignment = Element.ALIGN_CENTER;
        document.Add(title);
        document.Add(Chunk.NEWLINE); // Add spacing

        // Add bar chart to PDF
        var barChartBytes = ChartGenerator.GenerateMonthlySalesBarChart();
        var barImage = Image.GetInstance(barChartBytes);
        barImage.ScaleToFit(PageSize.A4.Width - 40, PageSize.A4.Height / 2);
        barImage.Alignment = Element.ALIGN_CENTER;
        document.Add(barImage);
        document.Add(Chunk.NEWLINE);

        // Add pie chart to PDF
        var pieChartBytes = ChartGenerator.GenerateProductSharePieChart();
        var pieImage = Image.GetInstance(pieChartBytes);
        pieImage.ScaleToFit(PageSize.A4.Width - 40, PageSize.A4.Height / 2);
        pieImage.Alignment = Element.ALIGN_CENTER;
        document.Add(pieImage);

        document.Close();

        // Return the PDF as a downloadable file
        return new ByteArrayContent(pdfStream.ToArray())
        {
            Headers = 
            {
                ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/pdf"),
                ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
                {
                    FileName = "SalesReport.pdf"
                }
            }
        };
    }
}
Key Notes & Troubleshooting
  • Non-English Text Support: If you need to display Chinese or other non-Latin languages, register a local font file with FontFactory.Register(@"C:\Path\To\Your\Font.ttf") and use it when creating paragraphs.
  • Memory Management: All IDisposable objects (like MemoryStream, Document) are wrapped in using statements to avoid memory leaks.
  • Chart Customization: OxyPlot lets you tweak colors, labels, sizes, and more—tinker with the PlotModel and Series properties to match your report's style.
  • iTextSharp Compatibility: Stick to version 5.5.13.2 for best compatibility with MVC 5 (.NET Framework 4.5+).

内容的提问来源于stack exchange,提问作者Subhash Tripathi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:15:12