82 lines
2.3 KiB
C#
82 lines
2.3 KiB
C#
using MigraDoc.DocumentObjectModel;
|
|
using MigraDoc.DocumentObjectModel.Shapes.Charts;
|
|
using MigraDoc.Rendering;
|
|
|
|
namespace ProjectGSM.Documents;
|
|
|
|
public class PdfBuilder
|
|
{
|
|
private readonly string _filePath;
|
|
private readonly Document _document;
|
|
|
|
public PdfBuilder(string filePath)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(filePath))
|
|
{
|
|
throw new ArgumentNullException(nameof(filePath));
|
|
}
|
|
|
|
if (File.Exists(filePath))
|
|
{
|
|
File.Delete(filePath);
|
|
}
|
|
|
|
_filePath = filePath;
|
|
_document = new Document();
|
|
DefineStyles();
|
|
}
|
|
|
|
public PdfBuilder AddHeader(string header)
|
|
{
|
|
_document.AddSection().AddParagraph(header, "NormalBold");
|
|
return this;
|
|
}
|
|
|
|
public PdfBuilder AddPieChart(string title, List<(string Caption, double
|
|
Value)> data)
|
|
{
|
|
if (data == null || data.Count == 0)
|
|
{
|
|
return this;
|
|
}
|
|
|
|
var chart = new Chart(ChartType.Pie2D);
|
|
var series = chart.SeriesCollection.AddSeries();
|
|
series.Add(data.Select(x => x.Value).ToArray());
|
|
var xseries = chart.XValues.AddXSeries();
|
|
xseries.Add(data.Select(x => x.Caption).ToArray());
|
|
chart.DataLabel.Type = DataLabelType.Percent;
|
|
chart.DataLabel.Position = DataLabelPosition.OutsideEnd;
|
|
chart.Width = Unit.FromCentimeter(16);
|
|
chart.Height = Unit.FromCentimeter(12);
|
|
chart.TopArea.AddParagraph(title);
|
|
chart.XAxis.MajorTickMark = TickMarkType.Outside;
|
|
chart.YAxis.MajorTickMark = TickMarkType.Outside;
|
|
chart.YAxis.HasMajorGridlines = true;
|
|
chart.PlotArea.LineFormat.Width = 1;
|
|
chart.PlotArea.LineFormat.Visible = true;
|
|
chart.TopArea.AddLegend();
|
|
_document.LastSection.Add(chart);
|
|
return this;
|
|
}
|
|
|
|
public void Build()
|
|
{
|
|
var renderer = new PdfDocumentRenderer(true)
|
|
{
|
|
Document = _document
|
|
};
|
|
renderer.RenderDocument();
|
|
renderer.PdfDocument.Save(_filePath);
|
|
}
|
|
|
|
private void DefineStyles()
|
|
{
|
|
var normalStyle = _document.Styles["Normal"];
|
|
normalStyle.Font.Name = "Arial";
|
|
normalStyle.Font.Size = 12;
|
|
|
|
var normalBoldStyle = _document.Styles.AddStyle("NormalBold", "Normal");
|
|
normalBoldStyle.Font.Bold = true;
|
|
}
|
|
} |