COP_Petrushin_PIbd-32/Library14Petrushin/PdfCirclDiagr.cs

96 lines
3.5 KiB
C#
Raw Normal View History

2024-09-30 11:24:43 +04:00
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("Все входные данные должны быть заполнены.");
}
2024-10-01 10:26:35 +04:00
2024-09-30 11:24:43 +04:00
PdfDocument document = new PdfDocument();
PdfPage page = document.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);
XFont font = new XFont("Verdana", 10);
2024-10-01 10:26:35 +04:00
2024-09-30 11:24:43 +04:00
gfx.DrawString(documentTitle, new XFont("Verdana", 16, XFontStyleEx.Bold), XBrushes.Black, new XRect(0, 0, page.Width, 50), XStringFormats.Center);
2024-10-01 10:26:35 +04:00
2024-09-30 11:24:43 +04:00
gfx.DrawString(chartTitle, font, XBrushes.Black, new XRect(50, 50, page.Width - 100, 30), XStringFormats.Center);
2024-10-01 10:26:35 +04:00
2024-09-30 11:24:43 +04:00
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;
}
2024-10-01 10:26:35 +04:00
// Отрисовка секторов диаграммы и легенды
2024-09-30 11:24:43 +04:00
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)));
}
}
}