COP_Petrushin_PIbd-32/Library14Petrushin/PdfCirclDiagr.cs
2024-10-01 10:26:35 +04:00

96 lines
3.5 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using Library14Petrushin.Classes;
using PdfSharp.Drawing;
using PdfSharp.Pdf;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Library14Petrushin
{
public partial class PdfCirclDiagr : Component
{
public void GeneratePdf(
string fileName,
string documentTitle,
string chartTitle,
LegendPosition legendPosition,
List<ChartData> chartData)
{
// Проверка на заполненность входных данных
if (string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(documentTitle) ||
string.IsNullOrEmpty(chartTitle) || chartData == null || !chartData.Any())
{
throw new ArgumentException("Все входные данные должны быть заполнены.");
}
PdfDocument document = new PdfDocument();
PdfPage page = document.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);
XFont font = new XFont("Verdana", 10);
gfx.DrawString(documentTitle, new XFont("Verdana", 16, XFontStyleEx.Bold), XBrushes.Black, new XRect(0, 0, page.Width, 50), XStringFormats.Center);
gfx.DrawString(chartTitle, font, XBrushes.Black, new XRect(50, 50, page.Width - 100, 30), XStringFormats.Center);
DrawPieChart(gfx, new XRect(50, 100, 300, 300), chartData, legendPosition);
// Сохранение документа
document.Save(fileName);
}
private void DrawPieChart(XGraphics gfx, XRect rect, List<ChartData> chartData, LegendPosition legendPosition)
{
double total = chartData.Sum(d => d.Value);
double startAngle = 0;
int legendX = 0;
int legendY = 0;
// Определение расположения легенды
switch (legendPosition)
{
case LegendPosition.Top:
legendX = (int)rect.X + (int)rect.Width / 2;
legendY = (int)rect.Y - 50;
break;
case LegendPosition.Bottom:
legendX = (int)rect.X + (int)rect.Width / 2;
legendY = (int)rect.Y + (int)rect.Height + 20;
break;
case LegendPosition.Left:
legendX = (int)rect.X - 100;
legendY = (int)rect.Y + (int)rect.Height / 2;
break;
case LegendPosition.Right:
legendX = (int)rect.X + (int)rect.Width + 20;
legendY = (int)rect.Y + (int)rect.Height / 2;
break;
}
// Отрисовка секторов диаграммы и легенды
foreach (var data in chartData)
{
double sweepAngle = 360 * (data.Value / total);
gfx.DrawPie(GetRandomBrush(), rect, startAngle, sweepAngle);
startAngle += sweepAngle;
gfx.DrawString(data.SeriesName, new XFont("Verdana", 8), XBrushes.Black, new XPoint(legendX, legendY));
legendY += 20;
}
}
private XBrush GetRandomBrush()
{
Random random = new Random();
return new XSolidBrush(XColor.FromArgb(random.Next(256), random.Next(256), random.Next(256)));
}
}
}