102 lines
3.9 KiB
C#
Raw Normal View History

2024-11-27 23:43:53 +04:00
using WinFormsLibrary1.HelperClasses;
using MigraDoc.DocumentObjectModel;
using MigraDoc.Rendering;
using OxyPlot.Series;
using OxyPlot;
using System.ComponentModel;
using OxyPlot.WindowsForms;
using OxyPlot.Legends;
namespace WinFormsLibrary1
{
public partial class PDFHistogram : Component
{
public PDFHistogram()
{
InitializeComponent();
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
}
public PDFHistogram(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public void CreateHistogramPdf(string filePath, string documentTitle, string chartTitle, LegendPosition legendPosition, List<ChartData> chartData)
{
if (string.IsNullOrEmpty(filePath))
throw new ArgumentException("Путь к файлу не должен быть пустым.");
if (string.IsNullOrEmpty(documentTitle))
throw new ArgumentException("Название документа не должно быть пустым.");
if (string.IsNullOrEmpty(chartTitle))
throw new ArgumentException("Заголовок диаграммы не должен быть пустым.");
if (chartData == null || chartData.Count == 0)
throw new ArgumentException("Набор данных не должен быть пустым.");
foreach (var data in chartData)
{
if (string.IsNullOrEmpty(data.SeriesName) || data.Data == null || data.Data.Count == 0)
throw new ArgumentException($"Набор данных для серии '{data.SeriesName}' некорректен.");
}
// создание графика
var plotModel = new PlotModel { Title = chartTitle };
foreach (var data in chartData)
{
var barSeries = new BarSeries { Title = data.SeriesName };
foreach (var item in data.Data)
{
barSeries.Items.Add(new BarItem(item.Value));
}
plotModel.Series.Add(barSeries);
}
// Добавление легенды
AddLegend(plotModel, legendPosition);
// сохранение графика в изображение
var pngExporter = new PngExporter { Width = 600, Height = 400 };
using (var stream = new MemoryStream())
{
pngExporter.Export(plotModel, stream);
File.WriteAllBytes("chart.png", stream.ToArray());
}
// создание документа
Document document = new Document();
document.Info.Title = documentTitle;
document.Info.Subject = "Гистограмма";
Section section = document.AddSection();
section.AddParagraph(chartTitle, "Heading1");
// вставка изображения в PDF
var image = section.AddImage("chart.png");
image.Width = Unit.FromCentimeter(15);
PdfDocumentRenderer renderer = new PdfDocumentRenderer(true) { Document = document };
renderer.RenderDocument();
renderer.PdfDocument.Save(filePath);
File.Delete("chart.png");
}
//добавление легенды
private void AddLegend(PlotModel plotModel, LegendPosition legendPosition)
{
// Создание легенды
var legend = new OxyPlot.Legends.Legend
{
LegendPlacement = LegendPlacement.Outside,
LegendPosition = legendPosition,
LegendOrientation = LegendOrientation.Vertical
};
plotModel.Legends.Add(legend);
}
}
}