PIbd-31_Razubaev_S_M_COP-10/WinFormsLibrary/NonVisualComponents/WordText.cs
2024-10-04 11:08:55 +04:00

81 lines
1.8 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 Microsoft.Office.Interop.Word;
using System.ComponentModel;
using WinFormsLibrary.NonVisualComponents.Helpers;
using Application = Microsoft.Office.Interop.Word.Application;
namespace WinFormsLibrary
{
public partial class WordText : Component
{
private Application? _wordApp;
private Document? _document;
public WordText()
{
InitializeComponent();
}
public WordText(IContainer container)
{
container.Add(this);
InitializeComponent();
}
public void CreateWordText(LongWordInfo textInfo)
{
if ((string.IsNullOrEmpty(textInfo.Path)) || (string.IsNullOrEmpty(textInfo.Title) || !CheckData(textInfo.Paragraphs)))
{
throw new ArgumentException("Не все данные заполнены");
}
_wordApp = new Application();
_document = _wordApp.Documents.Add();
try
{
AddText(textInfo);
_document.SaveAs2(textInfo.Path);
}
finally
{
_document.Close();
_wordApp.Quit();
}
}
private void AddText(LongWordInfo textInfo)
{
if (_document == null)
{
return;
}
AddParagraph(textInfo.Title, fontSize: 20, isBold: true);
foreach(var paragraph in textInfo.Paragraphs)
{
AddParagraph(paragraph, fontSize: 14, isBold: false);
}
}
private void AddParagraph(string text, int fontSize, bool isBold)
{
if (_document== null)
{
return;
}
var paragraph = _document.Content.Paragraphs.Add();
var range = paragraph.Range;
range.Text = text;
range.Font.Size = fontSize;
range.Font.Name = "Times New Roman";
range.Font.Bold = isBold ? 1 : 0;
paragraph.Alignment = WdParagraphAlignment.wdAlignParagraphJustify;
range.InsertParagraphAfter();
}
public bool CheckData(string[] data)
{
return data != null && data.Any() && data.All(dt => !String.IsNullOrEmpty(dt));
}
}
}