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

87 lines
2.4 KiB
C#
Raw Normal View History

using Microsoft.Office.Interop.Word;
2024-09-22 13:24:14 +04:00
using RodionovLibrary.NonVisualComponents.HelperModels;
using System.ComponentModel;
using Application = Microsoft.Office.Interop.Word.Application;
2024-09-22 13:24:14 +04:00
namespace RodionovLibrary.NonVisualComponents
{
public partial class WordLongTextComponent : Component
{
private Application? _wordApp;
private Document? _document;
2024-09-22 13:24:14 +04:00
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))
{
2024-09-22 23:29:54 +04:00
throw new ArgumentException("Не все данные заполнены");
2024-09-22 13:24:14 +04:00
}
_wordApp = new Application();
_document = _wordApp.Documents.Add();
2024-09-22 13:24:14 +04:00
try
{
AddText(textInfo);
_document.SaveAs2(textInfo.FileName);
}
finally
{
_document.Close();
_wordApp.Quit();
}
2024-09-22 13:24:14 +04:00
}
private void AddText(WordLongTextInfo textInfo)
{
if (_document == null)
2024-09-22 13:24:14 +04:00
{
return;
}
AddParagraph(textInfo.Title, fontSize: 22, isBold: true);
2024-09-22 13:24:14 +04:00
foreach (var paragraph in textInfo.Paragraphs)
{
AddParagraph(paragraph, fontSize: 14, isBold: false);
2024-09-22 13:24:14 +04:00
}
}
private void AddParagraph(string text, int fontSize, bool isBold)
2024-09-22 13:24:14 +04:00
{
if (_document == null)
2024-09-22 13:24:14 +04:00
{
return;
}
var paragraph = _document.Content.Paragraphs.Add();
var range = paragraph.Range;
2024-09-22 13:24:14 +04:00
range.Text = text;
range.Font.Size = fontSize;
range.Font.Name = "Times New Roman";
range.Font.Bold = isBold ? 1 : 0;
paragraph.Alignment = WdParagraphAlignment.wdAlignParagraphJustify;
2024-09-22 13:24:14 +04:00
range.InsertParagraphAfter();
2024-09-22 13:24:14 +04:00
}
private bool CheckData(string[] data)
{
return data != null && data.Any() && data.All(d => !string.IsNullOrEmpty(d));
}
}
}