87 lines
2.4 KiB
C#
87 lines
2.4 KiB
C#
using Microsoft.Office.Interop.Word;
|
||
using RodionovLibrary.NonVisualComponents.HelperModels;
|
||
using System.ComponentModel;
|
||
using Application = Microsoft.Office.Interop.Word.Application;
|
||
|
||
namespace RodionovLibrary.NonVisualComponents
|
||
{
|
||
public partial class WordLongTextComponent : Component
|
||
{
|
||
private Application? _wordApp;
|
||
private Document? _document;
|
||
|
||
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 ArgumentException("Не все данные заполнены");
|
||
}
|
||
|
||
_wordApp = new Application();
|
||
_document = _wordApp.Documents.Add();
|
||
|
||
try
|
||
{
|
||
AddText(textInfo);
|
||
_document.SaveAs2(textInfo.FileName);
|
||
}
|
||
finally
|
||
{
|
||
_document.Close();
|
||
_wordApp.Quit();
|
||
}
|
||
}
|
||
|
||
private void AddText(WordLongTextInfo textInfo)
|
||
{
|
||
if (_document == null)
|
||
{
|
||
return;
|
||
}
|
||
|
||
AddParagraph(textInfo.Title, fontSize: 22, 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();
|
||
}
|
||
|
||
private bool CheckData(string[] data)
|
||
{
|
||
return data != null && data.Any() && data.All(d => !string.IsNullOrEmpty(d));
|
||
}
|
||
}
|
||
}
|