PIbd-31_Rodionov.I.A._COP_28/COP/RodionovLibrary/NonVisualComponents/WordLongTextComponent.cs

96 lines
2.8 KiB
C#
Raw Normal View History

2024-09-22 13:24:14 +04:00
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using RodionovLibrary.NonVisualComponents.HelperModels;
using System.ComponentModel;
namespace RodionovLibrary.NonVisualComponents
{
public partial class WordLongTextComponent : Component
{
private WordprocessingDocument? _wordDocument;
private Body? _docBody;
public WordLongTextComponent()
{
InitializeComponent();
}
public WordLongTextComponent(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public void CreateWordText(WordLongTextInfo textInfo)
{
if (string.IsNullOrEmpty(textInfo.FileName) || string.IsNullOrEmpty(textInfo.Title) || !CheckData(textInfo.Paragraphs))
{
throw new Exception("Не все данные заполнены");
}
_wordDocument = WordprocessingDocument.Create(textInfo.FileName, WordprocessingDocumentType.Document);
MainDocumentPart mainPart = _wordDocument.AddMainDocumentPart();
mainPart.Document = new Document();
_docBody = mainPart.Document.AppendChild(new Body());
AddText(textInfo);
_wordDocument.MainDocumentPart!.Document.Save();
_wordDocument.Dispose();
}
private void AddText(WordLongTextInfo textInfo)
{
if (_docBody == null || _wordDocument == null)
{
return;
}
AddParagraph(textInfo.Title, fontSize: "48", isBold: true);
foreach (var paragraph in textInfo.Paragraphs)
{
AddParagraph(paragraph, fontSize: "24", isBold: false);
}
}
private void AddParagraph(string text, string fontSize, bool isBold)
{
if (_docBody == null)
{
return;
}
ParagraphProperties paragraphProperties = new();
paragraphProperties.AppendChild(new Justification { Val = JustificationValues.Both });
Paragraph paragraph = new();
paragraph.AppendChild(paragraphProperties);
Run docRun = new();
RunProperties runProperties = new();
runProperties.AppendChild(new FontSize { Val = fontSize });
if (isBold)
{
runProperties.AppendChild(new Bold());
}
docRun.AppendChild(runProperties);
docRun.AppendChild(new Text(text));
paragraph.AppendChild(docRun);
_docBody.Append(paragraph);
}
private bool CheckData(string[] data)
{
return data != null && data.Any() && data.All(d => !string.IsNullOrEmpty(d));
}
}
}